Functions.h 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. // Copyright (C) 2009-2021, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. /// @file
  6. /// Contains misc functions
  7. #pragma once
  8. #include <AnKi/Util/StdTypes.h>
  9. #include <AnKi/Util/Assert.h>
  10. #include <cmath>
  11. #include <utility>
  12. #include <new>
  13. #include <cstring>
  14. #include <algorithm>
  15. #include <functional>
  16. namespace anki {
  17. /// @addtogroup util_other
  18. /// @{
  19. #define _ANKI_CONCATENATE(a, b) a##b
  20. /// Concatenate 2 preprocessor tokens.
  21. #define ANKI_CONCATENATE(a, b) _ANKI_CONCATENATE(a, b)
  22. #define _ANKI_STRINGIZE(a) #a
  23. /// Make a preprocessor token a string.
  24. #define ANKI_STRINGIZE(a) _ANKI_STRINGIZE(a)
  25. /// Format to print bits
  26. #define ANKI_PRIb8 "c%c%c%c%c%c%c%c"
  27. #define ANKI_PRIb16 ANKI_PRIb8 "%c%c%c%c%c%c%c%c"
  28. #define ANKI_PRIb32 ANKI_PRIb16 "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c"
  29. #define ANKI_PRIb64 ANKI_PRIb32 "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c"
  30. #define _ANKI_FORMAT_HELPER(byte, bit) (U64(byte) & (U64(1) << U64(bit))) ? '1' : '0'
  31. #define ANKI_FORMAT_U8(byte) \
  32. _ANKI_FORMAT_HELPER((byte), 7), _ANKI_FORMAT_HELPER((byte), 6), _ANKI_FORMAT_HELPER((byte), 5), \
  33. _ANKI_FORMAT_HELPER((byte), 4), _ANKI_FORMAT_HELPER((byte), 3), _ANKI_FORMAT_HELPER((byte), 2), \
  34. _ANKI_FORMAT_HELPER((byte), 1), _ANKI_FORMAT_HELPER((byte), 0)
  35. #define ANKI_FORMAT_U16(u16) ANKI_FORMAT_U8(u16 >> 8), ANKI_FORMAT_U8(u16)
  36. #define ANKI_FORMAT_U32(u32) ANKI_FORMAT_U16(u32 >> 16), ANKI_FORMAT_U16(u32)
  37. #define ANKI_FORMAT_U64(u64) ANKI_FORMAT_U32(u64 >> 32), ANKI_FORMAT_U32(u64)
  38. // ANKI_ENABLE_METHOD & ANKI_ENABLE_ARG trickery copied from Tick library
  39. template<typename T, int N>
  40. struct DummyType
  41. {
  42. };
  43. #if defined(_MSC_VER)
  44. template<bool B>
  45. struct RequiresBool
  46. {
  47. static constexpr bool VALUE = B;
  48. };
  49. template<typename T, int N>
  50. struct RequiresUnwrap : T
  51. {
  52. };
  53. template<int N>
  54. struct PrivateEnum
  55. {
  56. enum class Type
  57. {
  58. NA
  59. };
  60. };
  61. # define ANKI_REQUIRES_BOOL(line, ...) RequiresUnwrap<decltype(RequiresBool<(__VA_ARGS__)>{}), line>::VALUE
  62. # define ANKI_ENABLE_INTERNAL(line, ...) \
  63. typename PrivateEnum<line>::Type ANKI_CONCATENATE( \
  64. privateEnum, line) = PrivateEnum<line>::Type::NA, \
  65. bool ANKI_CONCATENATE(privateBool, line) = true, \
  66. typename = typename std::enable_if_t<(ANKI_CONCATENATE(privateBool, line) \
  67. && ANKI_REQUIRES_BOOL(line, __VA_ARGS__))>
  68. #else
  69. # define ANKI_ENABLE_INTERNAL(line, ...) \
  70. bool privateBool##line = true, typename std::enable_if_t<(privateBool##line && __VA_ARGS__), int> = 0
  71. #endif
  72. /// Use it to enable a method based on a constant expression.
  73. /// @code
  74. /// template<int N> class Foo {
  75. /// ANKI_ENABLE_METHOD(N == 10)
  76. /// void foo() {}
  77. /// };
  78. /// @endcode
  79. #define ANKI_ENABLE_METHOD(...) template<ANKI_ENABLE_INTERNAL(__LINE__, __VA_ARGS__)>
  80. /// Use it to enable a method based on a constant expression.
  81. /// @code
  82. /// class Foo {
  83. /// void foo(ANKI_ENABLE_ARG(Boo, expr) b) {}
  84. /// };
  85. /// @endcode
  86. #define ANKI_ENABLE_ARG(type_, expression) \
  87. typename std::conditional<(expression), type_, DummyType<type_, __LINE__>>::type
  88. /// Use it to enable a method based on a constant expression.
  89. /// @code
  90. /// template<typename T, ANKI_ENABLE(std::is_whatever<T>::value)>
  91. /// void foo(T x) {}
  92. /// @endcode
  93. #define ANKI_ENABLE(...) ANKI_ENABLE_INTERNAL(__LINE__, __VA_ARGS__)
  94. /// OS specific debug breakpoint
  95. #if ANKI_OS_WINDOWS
  96. # define ANKI_DEBUG_BREAK() __debugbreak()
  97. #else
  98. # define ANKI_DEBUG_BREAK() abort()
  99. #endif
  100. /// Get a pseudo random number.
  101. U64 getRandom();
  102. /// Pick a random number from min to max
  103. template<typename T, ANKI_ENABLE(std::is_floating_point<T>::value)>
  104. T getRandomRange(T min, T max)
  105. {
  106. ANKI_ASSERT(min <= max);
  107. const F64 r = F64(getRandom()) / F64(MAX_U64);
  108. return T(min + r * (max - min));
  109. }
  110. template<typename T, ANKI_ENABLE(std::is_integral<T>::value)>
  111. T getRandomRange(T min, T max)
  112. {
  113. ANKI_ASSERT(min <= max);
  114. const U64 r = getRandom();
  115. return T(r % U64(max - min + 1)) + min;
  116. }
  117. /// Get min of two values.
  118. template<typename T>
  119. inline constexpr T min(T a, T b)
  120. {
  121. return (a < b) ? a : b;
  122. }
  123. /// Get max of two values.
  124. template<typename T>
  125. inline constexpr T max(T a, T b)
  126. {
  127. return (a > b) ? a : b;
  128. }
  129. /// Check if a number is a power of 2
  130. template<typename Int, ANKI_ENABLE(std::is_integral<Int>::value)>
  131. inline constexpr Bool isPowerOfTwo(Int x)
  132. {
  133. return !(x == 0) && !(x & (x - 1));
  134. }
  135. /// Get the next power of two number. For example if x is 130 this will return 256.
  136. template<typename Int, ANKI_ENABLE(std::is_integral<Int>::value)>
  137. inline constexpr Int nextPowerOfTwo(Int x)
  138. {
  139. const F64 d = F64(x);
  140. const F64 res = pow(2.0, ceil(log(d) / log(2.0)));
  141. return Int(res);
  142. }
  143. /// Get the aligned number rounded up.
  144. /// @param alignment The bytes of alignment
  145. /// @param value The value to align
  146. template<typename TInt, ANKI_ENABLE(std::is_integral<TInt>::value)>
  147. inline constexpr TInt getAlignedRoundUp(PtrSize alignment, TInt value)
  148. {
  149. ANKI_ASSERT(alignment > 0);
  150. PtrSize v = PtrSize(value);
  151. v = ((v + alignment - 1) / alignment) * alignment;
  152. return TInt(v);
  153. }
  154. /// Get the aligned number rounded up.
  155. /// @param alignment The bytes of alignment
  156. /// @param value The value to align
  157. template<typename TFloat, ANKI_ENABLE(std::is_floating_point<TFloat>::value)>
  158. inline constexpr TFloat getAlignedRoundUp(TFloat alignment, TFloat value)
  159. {
  160. ANKI_ASSERT(alignment > TFloat(0.0));
  161. return ceil(value / alignment) * alignment;
  162. }
  163. /// Align number
  164. /// @param alignment The bytes of alignment
  165. /// @param value The value to align
  166. template<typename TAlignment, typename TValue>
  167. inline void alignRoundUp(TAlignment alignment, TValue& value)
  168. {
  169. value = getAlignedRoundUp(alignment, value);
  170. }
  171. /// Get the aligned number rounded down.
  172. /// @param alignment The bytes of alignment
  173. /// @param value The value to align
  174. template<typename TInt, ANKI_ENABLE(std::is_integral<TInt>::value)>
  175. inline constexpr TInt getAlignedRoundDown(PtrSize alignment, TInt value)
  176. {
  177. ANKI_ASSERT(alignment > 0);
  178. PtrSize v = PtrSize(value);
  179. v = (v / alignment) * alignment;
  180. return TInt(v);
  181. }
  182. /// Get the aligned number rounded down.
  183. /// @param alignment The bytes of alignment
  184. /// @param value The value to align
  185. template<typename TFloat, ANKI_ENABLE(std::is_floating_point<TFloat>::value)>
  186. inline constexpr TFloat getAlignedRoundDown(TFloat alignment, TFloat value)
  187. {
  188. ANKI_ASSERT(alignment > TFloat(0.0));
  189. return floor(value / alignment) * alignment;
  190. }
  191. /// Align number
  192. /// @param alignment The bytes of alignment
  193. /// @param value The value to align
  194. template<typename TAlignment, typename TValue>
  195. inline void alignRoundDown(TAlignment alignment, TValue& value)
  196. {
  197. value = getAlignedRoundDown(alignment, value);
  198. }
  199. /// Check if a number is aligned
  200. template<typename Type>
  201. inline constexpr Bool isAligned(PtrSize alignment, Type value)
  202. {
  203. return (PtrSize(value) % alignment) == 0;
  204. }
  205. template<typename T>
  206. inline void swapValues(T& a, T& b)
  207. {
  208. const T tmp = b;
  209. b = a;
  210. a = tmp;
  211. }
  212. /// Convert any pointer to a number.
  213. template<typename TPtr>
  214. inline PtrSize ptrToNumber(TPtr ptr)
  215. {
  216. const uintptr_t i = reinterpret_cast<uintptr_t>(ptr);
  217. const PtrSize size = i;
  218. return size;
  219. }
  220. /// Convert a number to a pointer.
  221. template<typename TPtr>
  222. inline constexpr TPtr numberToPtr(PtrSize num)
  223. {
  224. uintptr_t i = static_cast<uintptr_t>(num);
  225. TPtr ptr = reinterpret_cast<TPtr>(i);
  226. return ptr;
  227. }
  228. /// A simple template trick to remove the pointer from one type
  229. ///
  230. /// Example:
  231. /// @code
  232. /// using Ptr = double*;
  233. /// RemovePointer<Ptr>::Type b = 666.0;
  234. /// @endcode
  235. /// The b is of type double
  236. template<typename T>
  237. struct RemovePointer;
  238. template<typename T>
  239. struct RemovePointer<T*>
  240. {
  241. using Type = T;
  242. };
  243. /// Zero memory of an object
  244. template<typename T>
  245. void zeroMemory(T& x)
  246. {
  247. memset(&x, 0, sizeof(T));
  248. }
  249. /// Find a value in a shorted container.
  250. template<class TForwardIterator, class T, class TCompare = std::less<>>
  251. TForwardIterator binarySearch(TForwardIterator first, TForwardIterator last, const T& value, TCompare comp = {})
  252. {
  253. first = std::lower_bound(first, last, value, comp);
  254. return (first != last && !comp(value, *first)) ? first : last;
  255. }
  256. /// Individual classes should specialize that function if they are packed. If a class is packed it can be used as
  257. /// whole in hashing.
  258. template<typename T>
  259. constexpr Bool isPacked()
  260. {
  261. return false;
  262. }
  263. /// Unflatten 3D array index.
  264. /// Imagine an array [sizeA][sizeB][sizeC] and a flat index in that array. Then this function will compute the unflatten
  265. /// indices.
  266. template<typename T, typename TI, typename TOut>
  267. inline void unflatten3dArrayIndex(const T sizeA, const T sizeB, const T sizeC, const TI flatIdx, TOut& a, TOut& b,
  268. TOut& c)
  269. {
  270. ANKI_ASSERT(flatIdx < (sizeA * sizeB * sizeC));
  271. a = (flatIdx / (sizeB * sizeC)) % sizeA;
  272. b = (flatIdx / sizeC) % sizeB;
  273. c = flatIdx % sizeC;
  274. }
  275. /// Given a threaded problem split it into smaller ones. This function accepts the number of threads and the size of
  276. /// the threaded problem. Then given a thread index it chooses a range that the thread can operate into. That range is
  277. /// supposed to be as evenly split as possible across threads.
  278. inline void splitThreadedProblem(U32 threadId, U32 threadCount, U32 problemSize, U32& start, U32& end)
  279. {
  280. ANKI_ASSERT(threadCount > 0 && threadId < threadCount);
  281. const U32 div = problemSize / threadCount;
  282. start = threadId * div;
  283. end = (threadId == threadCount - 1) ? problemSize : (threadId + 1u) * div;
  284. ANKI_ASSERT(!(threadId == threadCount - 1 && end != problemSize));
  285. }
  286. /// @}
  287. } // end namespace anki