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.

526 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  19. #define __JUCE_MATHSFUNCTIONS_JUCEHEADER__
  20. //==============================================================================
  21. /*
  22. This file sets up some handy mathematical typdefs and functions.
  23. */
  24. //==============================================================================
  25. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  26. /** A platform-independent 8-bit signed integer type. */
  27. typedef signed char int8;
  28. /** A platform-independent 8-bit unsigned integer type. */
  29. typedef unsigned char uint8;
  30. /** A platform-independent 16-bit signed integer type. */
  31. typedef signed short int16;
  32. /** A platform-independent 16-bit unsigned integer type. */
  33. typedef unsigned short uint16;
  34. /** A platform-independent 32-bit signed integer type. */
  35. typedef signed int int32;
  36. /** A platform-independent 32-bit unsigned integer type. */
  37. typedef unsigned int uint32;
  38. #if JUCE_MSVC
  39. /** A platform-independent 64-bit integer type. */
  40. typedef __int64 int64;
  41. /** A platform-independent 64-bit unsigned integer type. */
  42. typedef unsigned __int64 uint64;
  43. /** A platform-independent macro for writing 64-bit literals, needed because
  44. different compilers have different syntaxes for this.
  45. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  46. GCC, or 0x1000000000 for MSVC.
  47. */
  48. #define literal64bit(longLiteral) ((__int64) longLiteral)
  49. #else
  50. /** A platform-independent 64-bit integer type. */
  51. typedef long long int64;
  52. /** A platform-independent 64-bit unsigned integer type. */
  53. typedef unsigned long long uint64;
  54. /** A platform-independent macro for writing 64-bit literals, needed because
  55. different compilers have different syntaxes for this.
  56. E.g. writing literal64bit (0x1000000000) will translate to 0x1000000000LL for
  57. GCC, or 0x1000000000 for MSVC.
  58. */
  59. #define literal64bit(longLiteral) (longLiteral##LL)
  60. #endif
  61. #if JUCE_64BIT
  62. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  63. typedef int64 pointer_sized_int;
  64. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  65. typedef uint64 pointer_sized_uint;
  66. #elif JUCE_MSVC
  67. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  68. typedef _W64 int pointer_sized_int;
  69. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  70. typedef _W64 unsigned int pointer_sized_uint;
  71. #else
  72. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  73. typedef int pointer_sized_int;
  74. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  75. typedef unsigned int pointer_sized_uint;
  76. #endif
  77. #if JUCE_MSVC
  78. typedef pointer_sized_int ssize_t;
  79. #endif
  80. //==============================================================================
  81. // Some indispensible min/max functions
  82. /** Returns the larger of two values. */
  83. template <typename Type>
  84. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  85. /** Returns the larger of three values. */
  86. template <typename Type>
  87. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  88. /** Returns the larger of four values. */
  89. template <typename Type>
  90. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  91. /** Returns the smaller of two values. */
  92. template <typename Type>
  93. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  94. /** Returns the smaller of three values. */
  95. template <typename Type>
  96. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  97. /** Returns the smaller of four values. */
  98. template <typename Type>
  99. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  100. /** Scans an array of values, returning the minimum value that it contains. */
  101. template <typename Type>
  102. const Type findMinimum (const Type* data, int numValues)
  103. {
  104. if (numValues <= 0)
  105. return Type();
  106. Type result (*data++);
  107. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  108. {
  109. const Type& v = *data++;
  110. if (v < result) result = v;
  111. }
  112. return result;
  113. }
  114. /** Scans an array of values, returning the minimum value that it contains. */
  115. template <typename Type>
  116. const Type findMaximum (const Type* values, int numValues)
  117. {
  118. if (numValues <= 0)
  119. return Type();
  120. Type result (*values++);
  121. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  122. {
  123. const Type& v = *values++;
  124. if (result > v) result = v;
  125. }
  126. return result;
  127. }
  128. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  129. template <typename Type>
  130. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  131. {
  132. if (numValues <= 0)
  133. {
  134. lowest = Type();
  135. highest = Type();
  136. }
  137. else
  138. {
  139. Type mn (*values++);
  140. Type mx (mn);
  141. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  142. {
  143. const Type& v = *values++;
  144. if (mx < v) mx = v;
  145. if (v < mn) mn = v;
  146. }
  147. lowest = mn;
  148. highest = mx;
  149. }
  150. }
  151. //==============================================================================
  152. /** Constrains a value to keep it within a given range.
  153. This will check that the specified value lies between the lower and upper bounds
  154. specified, and if not, will return the nearest value that would be in-range. Effectively,
  155. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  156. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  157. the results will be unpredictable.
  158. @param lowerLimit the minimum value to return
  159. @param upperLimit the maximum value to return
  160. @param valueToConstrain the value to try to return
  161. @returns the closest value to valueToConstrain which lies between lowerLimit
  162. and upperLimit (inclusive)
  163. @see jlimit0To, jmin, jmax
  164. */
  165. template <typename Type>
  166. inline Type jlimit (const Type lowerLimit,
  167. const Type upperLimit,
  168. const Type valueToConstrain) noexcept
  169. {
  170. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  171. return (valueToConstrain < lowerLimit) ? lowerLimit
  172. : ((upperLimit < valueToConstrain) ? upperLimit
  173. : valueToConstrain);
  174. }
  175. /** Returns true if a value is at least zero, and also below a specified upper limit.
  176. This is basically a quicker way to write:
  177. @code valueToTest >= 0 && valueToTest < upperLimit
  178. @endcode
  179. */
  180. template <typename Type>
  181. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  182. {
  183. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  184. return Type() <= valueToTest && valueToTest < upperLimit;
  185. }
  186. template <>
  187. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  188. {
  189. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  190. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  191. }
  192. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  193. This is basically a quicker way to write:
  194. @code valueToTest >= 0 && valueToTest <= upperLimit
  195. @endcode
  196. */
  197. template <typename Type>
  198. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  199. {
  200. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  201. return Type() <= valueToTest && valueToTest <= upperLimit;
  202. }
  203. template <>
  204. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  205. {
  206. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  207. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  208. }
  209. //==============================================================================
  210. /** Handy function to swap two values. */
  211. template <typename Type>
  212. inline void swapVariables (Type& variable1, Type& variable2)
  213. {
  214. std::swap (variable1, variable2);
  215. }
  216. /** Handy function for getting the number of elements in a simple const C array.
  217. E.g.
  218. @code
  219. static int myArray[] = { 1, 2, 3 };
  220. int numElements = numElementsInArray (myArray) // returns 3
  221. @endcode
  222. */
  223. template <typename Type, int N>
  224. inline int numElementsInArray (Type (&array)[N])
  225. {
  226. (void) array; // (required to avoid a spurious warning in MS compilers)
  227. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  228. return N;
  229. }
  230. //==============================================================================
  231. // Some useful maths functions that aren't always present with all compilers and build settings.
  232. /** Using juce_hypot is easier than dealing with the different types of hypot function
  233. that are provided by the various platforms and compilers. */
  234. template <typename Type>
  235. inline Type juce_hypot (Type a, Type b) noexcept
  236. {
  237. #if JUCE_WINDOWS
  238. return static_cast <Type> (_hypot (a, b));
  239. #else
  240. return static_cast <Type> (hypot (a, b));
  241. #endif
  242. }
  243. /** 64-bit abs function. */
  244. inline int64 abs64 (const int64 n) noexcept
  245. {
  246. return (n >= 0) ? n : -n;
  247. }
  248. /** This templated negate function will negate pointers as well as integers */
  249. template <typename Type>
  250. inline Type juce_negate (Type n) noexcept
  251. {
  252. return sizeof (Type) == 1 ? (Type) -(signed char) n
  253. : (sizeof (Type) == 2 ? (Type) -(short) n
  254. : (sizeof (Type) == 4 ? (Type) -(int) n
  255. : ((Type) -(int64) n)));
  256. }
  257. /** This templated negate function will negate pointers as well as integers */
  258. template <typename Type>
  259. inline Type* juce_negate (Type* n) noexcept
  260. {
  261. return (Type*) -(pointer_sized_int) n;
  262. }
  263. //==============================================================================
  264. /** A predefined value for Pi, at double-precision.
  265. @see float_Pi
  266. */
  267. const double double_Pi = 3.1415926535897932384626433832795;
  268. /** A predefined value for Pi, at sngle-precision.
  269. @see double_Pi
  270. */
  271. const float float_Pi = 3.14159265358979323846f;
  272. //==============================================================================
  273. /** The isfinite() method seems to vary between platforms, so this is a
  274. platform-independent function for it.
  275. */
  276. template <typename FloatingPointType>
  277. inline bool juce_isfinite (FloatingPointType value)
  278. {
  279. #if JUCE_WINDOWS
  280. return _finite (value);
  281. #elif JUCE_ANDROID
  282. return isfinite (value);
  283. #else
  284. return std::isfinite (value);
  285. #endif
  286. }
  287. //==============================================================================
  288. #if JUCE_MSVC
  289. #pragma optimize ("t", off)
  290. #pragma float_control (precise, on, push)
  291. #endif
  292. /** Fast floating-point-to-integer conversion.
  293. This is faster than using the normal c++ cast to convert a float to an int, and
  294. it will round the value to the nearest integer, rather than rounding it down
  295. like the normal cast does.
  296. Note that this routine gets its speed at the expense of some accuracy, and when
  297. rounding values whose floating point component is exactly 0.5, odd numbers and
  298. even numbers will be rounded up or down differently.
  299. */
  300. template <typename FloatType>
  301. inline int roundToInt (const FloatType value) noexcept
  302. {
  303. union { int asInt[2]; double asDouble; } n;
  304. n.asDouble = ((double) value) + 6755399441055744.0;
  305. #if JUCE_BIG_ENDIAN
  306. return n.asInt [1];
  307. #else
  308. return n.asInt [0];
  309. #endif
  310. }
  311. #if JUCE_MSVC
  312. #pragma float_control (pop)
  313. #pragma optimize ("", on) // resets optimisations to the project defaults
  314. #endif
  315. /** Fast floating-point-to-integer conversion.
  316. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  317. fine for values above zero, but negative numbers are rounded the wrong way.
  318. */
  319. inline int roundToIntAccurate (const double value) noexcept
  320. {
  321. return roundToInt (value + 1.5e-8);
  322. }
  323. /** Fast floating-point-to-integer conversion.
  324. This is faster than using the normal c++ cast to convert a double to an int, and
  325. it will round the value to the nearest integer, rather than rounding it down
  326. like the normal cast does.
  327. Note that this routine gets its speed at the expense of some accuracy, and when
  328. rounding values whose floating point component is exactly 0.5, odd numbers and
  329. even numbers will be rounded up or down differently. For a more accurate conversion,
  330. see roundDoubleToIntAccurate().
  331. */
  332. inline int roundDoubleToInt (const double value) noexcept
  333. {
  334. return roundToInt (value);
  335. }
  336. /** Fast floating-point-to-integer conversion.
  337. This is faster than using the normal c++ cast to convert a float to an int, and
  338. it will round the value to the nearest integer, rather than rounding it down
  339. like the normal cast does.
  340. Note that this routine gets its speed at the expense of some accuracy, and when
  341. rounding values whose floating point component is exactly 0.5, odd numbers and
  342. even numbers will be rounded up or down differently.
  343. */
  344. inline int roundFloatToInt (const float value) noexcept
  345. {
  346. return roundToInt (value);
  347. }
  348. //==============================================================================
  349. /** Returns true if the specified integer is a power-of-two.
  350. */
  351. template <typename IntegerType>
  352. bool isPowerOfTwo (IntegerType value)
  353. {
  354. return (value & (value - 1)) == 0;
  355. }
  356. /** Returns the next power-of-two which is equal to or greater than the given integer.
  357. */
  358. inline int nextPowerOfTwo (int n)
  359. {
  360. --n;
  361. n |= (n >> 1);
  362. n |= (n >> 2);
  363. n |= (n >> 4);
  364. n |= (n >> 8);
  365. n |= (n >> 16);
  366. return n + 1;
  367. }
  368. /** Performs a modulo operation, but can cope with the dividend being negative.
  369. The divisor must be greater than zero.
  370. */
  371. template <typename IntegerType>
  372. int negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  373. {
  374. jassert (divisor > 0);
  375. dividend %= divisor;
  376. return (dividend < 0) ? (dividend + divisor) : dividend;
  377. }
  378. //==============================================================================
  379. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  380. /** This macro can be applied to a float variable to check whether it contains a denormalised
  381. value, and to normalise it if necessary.
  382. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  383. */
  384. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  385. #else
  386. #define JUCE_UNDENORMALISE(x)
  387. #endif
  388. //==============================================================================
  389. /** This namespace contains a few template classes for helping work out class type variations.
  390. */
  391. namespace TypeHelpers
  392. {
  393. #if JUCE_VC8_OR_EARLIER
  394. #define PARAMETER_TYPE(type) const type&
  395. #else
  396. /** The ParameterType struct is used to find the best type to use when passing some kind
  397. of object as a parameter.
  398. Of course, this is only likely to be useful in certain esoteric template situations.
  399. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  400. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  401. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  402. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  403. pass-by-value, but passing objects as a const reference, to avoid copying.
  404. */
  405. template <typename Type> struct ParameterType { typedef const Type& type; };
  406. #if ! DOXYGEN
  407. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  408. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  409. template <> struct ParameterType <char> { typedef char type; };
  410. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  411. template <> struct ParameterType <short> { typedef short type; };
  412. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  413. template <> struct ParameterType <int> { typedef int type; };
  414. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  415. template <> struct ParameterType <long> { typedef long type; };
  416. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  417. template <> struct ParameterType <int64> { typedef int64 type; };
  418. template <> struct ParameterType <uint64> { typedef uint64 type; };
  419. template <> struct ParameterType <bool> { typedef bool type; };
  420. template <> struct ParameterType <float> { typedef float type; };
  421. template <> struct ParameterType <double> { typedef double type; };
  422. #endif
  423. /** A helpful macro to simplify the use of the ParameterType template.
  424. @see ParameterType
  425. */
  426. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  427. #endif
  428. /** These templates are designed to take a type, and if it's a double, they return a double
  429. type; for anything else, they return a float type.
  430. */
  431. template <typename Type> struct SmallestFloatType { typedef float type; };
  432. template <> struct SmallestFloatType <double> { typedef double type; };
  433. }
  434. //==============================================================================
  435. #endif // __JUCE_MATHSFUNCTIONS_JUCEHEADER__