juce_MathsFunctions.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. /** Scans an array of values, returning the minimum value that it contains. */
  100. template <typename Type>
  101. const Type findMinimum (const Type* data, int numValues)
  102. {
  103. if (numValues <= 0)
  104. return Type();
  105. Type result (*data++);
  106. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  107. {
  108. const Type& v = *data++;
  109. if (v < result) result = v;
  110. }
  111. return result;
  112. }
  113. /** Scans an array of values, returning the maximum value that it contains. */
  114. template <typename Type>
  115. const Type findMaximum (const Type* values, int numValues)
  116. {
  117. if (numValues <= 0)
  118. return Type();
  119. Type result (*values++);
  120. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  121. {
  122. const Type& v = *values++;
  123. if (result < v) result = v;
  124. }
  125. return result;
  126. }
  127. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  128. template <typename Type>
  129. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  130. {
  131. if (numValues <= 0)
  132. {
  133. lowest = Type();
  134. highest = Type();
  135. }
  136. else
  137. {
  138. Type mn (*values++);
  139. Type mx (mn);
  140. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  141. {
  142. const Type& v = *values++;
  143. if (mx < v) mx = v;
  144. if (v < mn) mn = v;
  145. }
  146. lowest = mn;
  147. highest = mx;
  148. }
  149. }
  150. //==============================================================================
  151. /** Constrains a value to keep it within a given range.
  152. This will check that the specified value lies between the lower and upper bounds
  153. specified, and if not, will return the nearest value that would be in-range. Effectively,
  154. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  155. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  156. the results will be unpredictable.
  157. @param lowerLimit the minimum value to return
  158. @param upperLimit the maximum value to return
  159. @param valueToConstrain the value to try to return
  160. @returns the closest value to valueToConstrain which lies between lowerLimit
  161. and upperLimit (inclusive)
  162. @see jlimit0To, jmin, jmax
  163. */
  164. template <typename Type>
  165. inline Type jlimit (const Type lowerLimit,
  166. const Type upperLimit,
  167. const Type valueToConstrain) noexcept
  168. {
  169. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  170. return (valueToConstrain < lowerLimit) ? lowerLimit
  171. : ((upperLimit < valueToConstrain) ? upperLimit
  172. : valueToConstrain);
  173. }
  174. /** Returns true if a value is at least zero, and also below a specified upper limit.
  175. This is basically a quicker way to write:
  176. @code valueToTest >= 0 && valueToTest < upperLimit
  177. @endcode
  178. */
  179. template <typename Type>
  180. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  181. {
  182. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  183. return Type() <= valueToTest && valueToTest < upperLimit;
  184. }
  185. template <>
  186. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  187. {
  188. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  189. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  190. }
  191. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  192. This is basically a quicker way to write:
  193. @code valueToTest >= 0 && valueToTest <= upperLimit
  194. @endcode
  195. */
  196. template <typename Type>
  197. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  198. {
  199. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  200. return Type() <= valueToTest && valueToTest <= upperLimit;
  201. }
  202. template <>
  203. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  204. {
  205. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  206. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  207. }
  208. //==============================================================================
  209. /** Handy function to swap two values. */
  210. template <typename Type>
  211. inline void swapVariables (Type& variable1, Type& variable2)
  212. {
  213. std::swap (variable1, variable2);
  214. }
  215. /** Handy function for getting the number of elements in a simple const C array.
  216. E.g.
  217. @code
  218. static int myArray[] = { 1, 2, 3 };
  219. int numElements = numElementsInArray (myArray) // returns 3
  220. @endcode
  221. */
  222. template <typename Type, int N>
  223. inline int numElementsInArray (Type (&array)[N])
  224. {
  225. (void) array; // (required to avoid a spurious warning in MS compilers)
  226. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  227. return N;
  228. }
  229. //==============================================================================
  230. // Some useful maths functions that aren't always present with all compilers and build settings.
  231. /** Using juce_hypot is easier than dealing with the different types of hypot function
  232. that are provided by the various platforms and compilers. */
  233. template <typename Type>
  234. inline Type juce_hypot (Type a, Type b) noexcept
  235. {
  236. #if JUCE_MSVC
  237. return static_cast <Type> (_hypot (a, b));
  238. #else
  239. return static_cast <Type> (hypot (a, b));
  240. #endif
  241. }
  242. /** 64-bit abs function. */
  243. inline int64 abs64 (const int64 n) noexcept
  244. {
  245. return (n >= 0) ? n : -n;
  246. }
  247. #if JUCE_MSVC && ! defined (DOXYGEN) // The MSVC libraries omit these functions for some reason...
  248. template<typename Type> Type asinh (Type x) noexcept { return std::log (x + std::sqrt (x * x + (Type) 1)); }
  249. template<typename Type> Type acosh (Type x) noexcept { return std::log (x + std::sqrt (x * x - (Type) 1)); }
  250. template<typename Type> Type atanh (Type x) noexcept { return (std::log (x + (Type) 1) - std::log (((Type) 1) - x)) / (Type) 2; }
  251. #endif
  252. //==============================================================================
  253. /** A predefined value for Pi, at double-precision.
  254. @see float_Pi
  255. */
  256. const double double_Pi = 3.1415926535897932384626433832795;
  257. /** A predefined value for Pi, at single-precision.
  258. @see double_Pi
  259. */
  260. const float float_Pi = 3.14159265358979323846f;
  261. //==============================================================================
  262. /** The isfinite() method seems to vary between platforms, so this is a
  263. platform-independent function for it.
  264. */
  265. template <typename FloatingPointType>
  266. inline bool juce_isfinite (FloatingPointType value)
  267. {
  268. #if JUCE_WINDOWS
  269. return _finite (value);
  270. #elif JUCE_ANDROID
  271. return isfinite (value);
  272. #else
  273. return std::isfinite (value);
  274. #endif
  275. }
  276. //==============================================================================
  277. #if JUCE_MSVC
  278. #pragma optimize ("t", off)
  279. #ifndef __INTEL_COMPILER
  280. #pragma float_control (precise, on, push)
  281. #endif
  282. #endif
  283. /** Fast floating-point-to-integer conversion.
  284. This is faster than using the normal c++ cast to convert a float to an int, and
  285. it will round the value to the nearest integer, rather than rounding it down
  286. like the normal cast does.
  287. Note that this routine gets its speed at the expense of some accuracy, and when
  288. rounding values whose floating point component is exactly 0.5, odd numbers and
  289. even numbers will be rounded up or down differently.
  290. */
  291. template <typename FloatType>
  292. inline int roundToInt (const FloatType value) noexcept
  293. {
  294. #ifdef __INTEL_COMPILER
  295. #pragma float_control (precise, on, push)
  296. #endif
  297. union { int asInt[2]; double asDouble; } n;
  298. n.asDouble = ((double) value) + 6755399441055744.0;
  299. #if JUCE_BIG_ENDIAN
  300. return n.asInt [1];
  301. #else
  302. return n.asInt [0];
  303. #endif
  304. }
  305. inline int roundToInt (int value) noexcept
  306. {
  307. return value;
  308. }
  309. #if JUCE_MSVC
  310. #ifndef __INTEL_COMPILER
  311. #pragma float_control (pop)
  312. #endif
  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. #ifdef __INTEL_COMPILER
  322. #pragma float_control (pop)
  323. #endif
  324. return roundToInt (value + 1.5e-8);
  325. }
  326. /** Fast floating-point-to-integer conversion.
  327. This is faster than using the normal c++ cast to convert a double to an int, and
  328. it will round the value to the nearest integer, rather than rounding it down
  329. like the normal cast does.
  330. Note that this routine gets its speed at the expense of some accuracy, and when
  331. rounding values whose floating point component is exactly 0.5, odd numbers and
  332. even numbers will be rounded up or down differently. For a more accurate conversion,
  333. see roundDoubleToIntAccurate().
  334. */
  335. inline int roundDoubleToInt (const double value) noexcept
  336. {
  337. return roundToInt (value);
  338. }
  339. /** Fast floating-point-to-integer conversion.
  340. This is faster than using the normal c++ cast to convert a float to an int, and
  341. it will round the value to the nearest integer, rather than rounding it down
  342. like the normal cast does.
  343. Note that this routine gets its speed at the expense of some accuracy, and when
  344. rounding values whose floating point component is exactly 0.5, odd numbers and
  345. even numbers will be rounded up or down differently.
  346. */
  347. inline int roundFloatToInt (const float value) noexcept
  348. {
  349. return roundToInt (value);
  350. }
  351. //==============================================================================
  352. /** Returns true if the specified integer is a power-of-two.
  353. */
  354. template <typename IntegerType>
  355. bool isPowerOfTwo (IntegerType value)
  356. {
  357. return (value & (value - 1)) == 0;
  358. }
  359. /** Returns the smallest power-of-two which is equal to or greater than the given integer.
  360. */
  361. inline int nextPowerOfTwo (int n) noexcept
  362. {
  363. --n;
  364. n |= (n >> 1);
  365. n |= (n >> 2);
  366. n |= (n >> 4);
  367. n |= (n >> 8);
  368. n |= (n >> 16);
  369. return n + 1;
  370. }
  371. /** Performs a modulo operation, but can cope with the dividend being negative.
  372. The divisor must be greater than zero.
  373. */
  374. template <typename IntegerType>
  375. IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  376. {
  377. jassert (divisor > 0);
  378. dividend %= divisor;
  379. return (dividend < 0) ? (dividend + divisor) : dividend;
  380. }
  381. /** Returns the square of its argument. */
  382. template <typename NumericType>
  383. NumericType square (NumericType n) noexcept
  384. {
  385. return n * n;
  386. }
  387. //==============================================================================
  388. #if (JUCE_INTEL && JUCE_32BIT) || defined (DOXYGEN)
  389. /** This macro can be applied to a float variable to check whether it contains a denormalised
  390. value, and to normalise it if necessary.
  391. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  392. */
  393. #define JUCE_UNDENORMALISE(x) x += 1.0f; x -= 1.0f;
  394. #else
  395. #define JUCE_UNDENORMALISE(x)
  396. #endif
  397. //==============================================================================
  398. /** This namespace contains a few template classes for helping work out class type variations.
  399. */
  400. namespace TypeHelpers
  401. {
  402. #if JUCE_VC8_OR_EARLIER
  403. #define PARAMETER_TYPE(type) const type&
  404. #else
  405. /** The ParameterType struct is used to find the best type to use when passing some kind
  406. of object as a parameter.
  407. Of course, this is only likely to be useful in certain esoteric template situations.
  408. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  409. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  410. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  411. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  412. pass-by-value, but passing objects as a const reference, to avoid copying.
  413. */
  414. template <typename Type> struct ParameterType { typedef const Type& type; };
  415. #if ! DOXYGEN
  416. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  417. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  418. template <> struct ParameterType <char> { typedef char type; };
  419. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  420. template <> struct ParameterType <short> { typedef short type; };
  421. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  422. template <> struct ParameterType <int> { typedef int type; };
  423. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  424. template <> struct ParameterType <long> { typedef long type; };
  425. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  426. template <> struct ParameterType <int64> { typedef int64 type; };
  427. template <> struct ParameterType <uint64> { typedef uint64 type; };
  428. template <> struct ParameterType <bool> { typedef bool type; };
  429. template <> struct ParameterType <float> { typedef float type; };
  430. template <> struct ParameterType <double> { typedef double type; };
  431. #endif
  432. /** A helpful macro to simplify the use of the ParameterType template.
  433. @see ParameterType
  434. */
  435. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  436. #endif
  437. /** These templates are designed to take a type, and if it's a double, they return a double
  438. type; for anything else, they return a float type.
  439. */
  440. template <typename Type> struct SmallestFloatType { typedef float type; };
  441. template <> struct SmallestFloatType <double> { typedef double type; };
  442. }
  443. //==============================================================================
  444. #endif // JUCE_MATHSFUNCTIONS_H_INCLUDED