Global.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. /*
  2. * Global.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. /* ---------------------------------------------------------------------------- */
  12. /* Compiler detection */
  13. /* ---------------------------------------------------------------------------- */
  14. // Fixed width bool data type is important for serialization
  15. static_assert(sizeof(bool) == 1, "Bool needs to be 1 byte in size.");
  16. #ifdef __GNUC__
  17. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__)
  18. #endif
  19. #if !defined(__clang__) && defined(__GNUC__) && (GCC_VERSION < 470)
  20. # error VCMI requires at least gcc-4.7.2 for successful compilation or clang-3.1. Please update your compiler
  21. #endif
  22. #if defined(__GNUC__) && (GCC_VERSION == 470 || GCC_VERSION == 471)
  23. # error This GCC version has buggy std::array::at version and should not be used. Please update to 4.7.2 or later
  24. #endif
  25. /* ---------------------------------------------------------------------------- */
  26. /* Suppress some compiler warnings */
  27. /* ---------------------------------------------------------------------------- */
  28. #ifdef _MSC_VER
  29. # pragma warning (disable : 4800 ) /* disable conversion to bool warning -- I think it's intended in all places */
  30. #endif
  31. /* ---------------------------------------------------------------------------- */
  32. /* System detection. */
  33. /* ---------------------------------------------------------------------------- */
  34. // Based on: http://sourceforge.net/p/predef/wiki/OperatingSystems/
  35. // and on: http://stackoverflow.com/questions/5919996/how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor
  36. // TODO?: Should be moved to vstd\os_detect.h (and then included by Global.h)
  37. #ifdef _WIN16 // Defined for 16-bit environments
  38. # error "16-bit Windows isn't supported"
  39. #elif defined(_WIN64) // Defined for 64-bit environments
  40. # define VCMI_WINDOWS
  41. # define VCMI_WINDOWS_64
  42. #elif defined(_WIN32) // Defined for both 32-bit and 64-bit environments
  43. # define VCMI_WINDOWS
  44. # define VCMI_WINDOWS_32
  45. #elif defined(_WIN32_WCE)
  46. # error "Windows CE isn't supported"
  47. #elif defined(__linux__) || defined(__gnu_linux__) || defined(linux) || defined(__linux)
  48. # define VCMI_UNIX
  49. # define VCMI_XDG
  50. # ifdef __ANDROID__
  51. # define VCMI_ANDROID
  52. # endif
  53. #elif defined(__FreeBSD_kernel__) || defined(__FreeBSD__)
  54. # define VCMI_UNIX
  55. # define VCMI_XDG
  56. # define VCMI_FREEBSD
  57. #elif defined(__GNU__) || defined(__gnu_hurd__) || (defined(__MACH__) && !defined(__APPLE__))
  58. # define VCMI_UNIX
  59. # define VCMI_XDG
  60. # define VCMI_HURD
  61. #elif defined(__APPLE__) && defined(__MACH__)
  62. # define VCMI_UNIX
  63. # define VCMI_APPLE
  64. # include "TargetConditionals.h"
  65. # if TARGET_OS_SIMULATOR || TARGET_IPHONE_SIMULATOR
  66. # define VCMI_IOS
  67. # define VCMI_IOS_SIM
  68. # elif TARGET_OS_IPHONE
  69. # define VCMI_IOS
  70. # elif TARGET_OS_MAC
  71. # define VCMI_MAC
  72. # else
  73. //# warning "Unknown Apple target."?
  74. # endif
  75. #else
  76. # error "VCMI supports only Windows, OSX, Linux and Android targets"
  77. #endif
  78. // Each compiler uses own way to supress fall through warning. Try to find it.
  79. #ifdef __has_cpp_attribute
  80. # if __has_cpp_attribute(fallthrough)
  81. # define FALLTHROUGH [[fallthrough]];
  82. # elif __has_cpp_attribute(gnu::fallthrough)
  83. # define FALLTHROUGH [[gnu::fallthrough]];
  84. # elif __has_cpp_attribute(clang::fallthrough)
  85. # define FALLTHROUGH [[clang::fallthrough]];
  86. # else
  87. # define FALLTHROUGH
  88. # endif
  89. #else
  90. # define FALLTHROUGH
  91. #endif
  92. /* ---------------------------------------------------------------------------- */
  93. /* Commonly used C++, Boost headers */
  94. /* ---------------------------------------------------------------------------- */
  95. #ifdef VCMI_WINDOWS
  96. # define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers - delete this line if something is missing.
  97. # define NOMINMAX // Exclude min/max macros from <Windows.h>. Use std::[min/max] from <algorithm> instead.
  98. # define _NO_W32_PSEUDO_MODIFIERS // Exclude more macros for compiling with MinGW on Linux.
  99. #endif
  100. #ifdef VCMI_ANDROID
  101. # define NO_STD_TOSTRING // android runtime (gnustl) currently doesn't support std::to_string, so we provide our impl in this case
  102. #endif // VCMI_ANDROID
  103. /* ---------------------------------------------------------------------------- */
  104. /* A macro to force inlining some of our functions */
  105. /* ---------------------------------------------------------------------------- */
  106. // Compiler (at least MSVC) is not so smart here-> without that displaying is MUCH slower
  107. #ifdef _MSC_VER
  108. # define STRONG_INLINE __forceinline
  109. #elif __GNUC__
  110. # define STRONG_INLINE inline __attribute__((always_inline))
  111. #else
  112. # define STRONG_INLINE inline
  113. #endif
  114. #define TO_STRING_HELPER(x) #x
  115. #define TO_STRING(x) TO_STRING_HELPER(x)
  116. #define LINE_IN_FILE __FILE__ ":" TO_STRING(__LINE__)
  117. #define _USE_MATH_DEFINES
  118. #include <cstdio>
  119. #include <stdio.h>
  120. #include <algorithm>
  121. #include <array>
  122. #include <cassert>
  123. #include <climits>
  124. #include <cmath>
  125. #include <cstdlib>
  126. #include <functional>
  127. #include <fstream>
  128. #include <iomanip>
  129. #include <iostream>
  130. #include <map>
  131. #include <memory>
  132. #include <numeric>
  133. #include <queue>
  134. #include <random>
  135. #include <set>
  136. #include <sstream>
  137. #include <string>
  138. #include <unordered_set>
  139. #include <unordered_map>
  140. #include <utility>
  141. #include <vector>
  142. #include <atomic>
  143. //The only available version is 3, as of Boost 1.50
  144. #include <boost/version.hpp>
  145. #define BOOST_FILESYSTEM_VERSION 3
  146. #if BOOST_VERSION > 105000
  147. # define BOOST_THREAD_VERSION 3
  148. #endif
  149. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  150. //need to link boost thread dynamically to avoid https://stackoverflow.com/questions/35978572/boost-thread-interupt-does-not-work-when-crossing-a-dll-boundary
  151. #define BOOST_THREAD_USE_DLL //for example VCAI::finish() may freeze on thread join after interrupt when linking this statically
  152. #define BOOST_BIND_NO_PLACEHOLDERS
  153. #if defined(_MSC_VER) && (_MSC_VER == 1900 || _MSC_VER == 1910 || _MSC_VER == 1911)
  154. #define BOOST_NO_CXX11_VARIADIC_TEMPLATES //Variadic templates are buggy in VS2015 and VS2017, so turn this off to avoid compile errors
  155. #endif
  156. #if BOOST_VERSION >= 106600
  157. #define BOOST_ASIO_ENABLE_OLD_SERVICES
  158. #endif
  159. #include <boost/algorithm/string.hpp>
  160. #include <boost/any.hpp>
  161. #include <boost/cstdint.hpp>
  162. #include <boost/current_function.hpp>
  163. #include <boost/crc.hpp>
  164. #include <boost/date_time/posix_time/posix_time.hpp>
  165. #include <boost/date_time/posix_time/posix_time_io.hpp>
  166. #include <boost/filesystem.hpp>
  167. #include <boost/filesystem/path.hpp>
  168. #include <boost/filesystem/fstream.hpp>
  169. #include <boost/format.hpp>
  170. #include <boost/functional/hash.hpp>
  171. #include <boost/lexical_cast.hpp>
  172. #ifdef VCMI_WINDOWS
  173. #include <boost/locale/generator.hpp>
  174. #endif
  175. #include <boost/logic/tribool.hpp>
  176. #include <boost/optional.hpp>
  177. #include <boost/optional/optional_io.hpp>
  178. #include <boost/range/adaptor/filtered.hpp>
  179. #include <boost/range/adaptor/reversed.hpp>
  180. #include <boost/range/algorithm.hpp>
  181. #include <boost/thread.hpp>
  182. #include <boost/variant.hpp>
  183. #include <boost/math/special_functions/round.hpp>
  184. #include <boost/multi_array.hpp>
  185. #ifndef M_PI
  186. # define M_PI 3.14159265358979323846
  187. #endif
  188. /* ---------------------------------------------------------------------------- */
  189. /* Usings */
  190. /* ---------------------------------------------------------------------------- */
  191. using namespace std::placeholders;
  192. namespace range = boost::range;
  193. /* ---------------------------------------------------------------------------- */
  194. /* Typedefs */
  195. /* ---------------------------------------------------------------------------- */
  196. // Integral data types
  197. typedef uint64_t ui64; //unsigned int 64 bits (8 bytes)
  198. typedef uint32_t ui32; //unsigned int 32 bits (4 bytes)
  199. typedef uint16_t ui16; //unsigned int 16 bits (2 bytes)
  200. typedef uint8_t ui8; //unsigned int 8 bits (1 byte)
  201. typedef int64_t si64; //signed int 64 bits (8 bytes)
  202. typedef int32_t si32; //signed int 32 bits (4 bytes)
  203. typedef int16_t si16; //signed int 16 bits (2 bytes)
  204. typedef int8_t si8; //signed int 8 bits (1 byte)
  205. // Lock typedefs
  206. typedef boost::lock_guard<boost::mutex> TLockGuard;
  207. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  208. /* ---------------------------------------------------------------------------- */
  209. /* Macros */
  210. /* ---------------------------------------------------------------------------- */
  211. // Import + Export macro declarations
  212. #ifdef VCMI_WINDOWS
  213. # ifdef __GNUC__
  214. # define DLL_IMPORT __attribute__((dllimport))
  215. # define DLL_EXPORT __attribute__((dllexport))
  216. # else
  217. # define DLL_IMPORT __declspec(dllimport)
  218. # define DLL_EXPORT __declspec(dllexport)
  219. # endif
  220. # define ELF_VISIBILITY
  221. #else
  222. # ifdef __GNUC__
  223. # define DLL_IMPORT __attribute__ ((visibility("default")))
  224. # define DLL_EXPORT __attribute__ ((visibility("default")))
  225. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  226. # endif
  227. #endif
  228. #ifdef VCMI_DLL
  229. # define DLL_LINKAGE DLL_EXPORT
  230. #else
  231. # define DLL_LINKAGE DLL_IMPORT
  232. #endif
  233. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  234. // can be used for counting arrays
  235. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  236. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  237. // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
  238. #define UNUSED(VAR) ((void)VAR)
  239. // single-process build makes 2 copies of the main lib by wrapping it in a namespace
  240. #ifdef VCMI_LIB_NAMESPACE
  241. #define VCMI_LIB_NAMESPACE_BEGIN namespace VCMI_LIB_NAMESPACE {
  242. #define VCMI_LIB_NAMESPACE_END }
  243. #define VCMI_LIB_USING_NAMESPACE using namespace VCMI_LIB_NAMESPACE;
  244. #define VCMI_LIB_WRAP_NAMESPACE(x) VCMI_LIB_NAMESPACE::x
  245. #else
  246. #define VCMI_LIB_NAMESPACE_BEGIN
  247. #define VCMI_LIB_NAMESPACE_END
  248. #define VCMI_LIB_USING_NAMESPACE
  249. #define VCMI_LIB_WRAP_NAMESPACE(x) x
  250. #endif
  251. /* ---------------------------------------------------------------------------- */
  252. /* VCMI standard library */
  253. /* ---------------------------------------------------------------------------- */
  254. #include <vstd/CLoggerBase.h>
  255. VCMI_LIB_NAMESPACE_BEGIN
  256. void inline handleException()
  257. {
  258. try
  259. {
  260. throw;
  261. }
  262. catch(const std::exception & ex)
  263. {
  264. logGlobal->error(ex.what());
  265. }
  266. catch(const std::string & ex)
  267. {
  268. logGlobal->error(ex);
  269. }
  270. catch(...)
  271. {
  272. logGlobal->error("Sorry, caught unknown exception type. No more info available.");
  273. }
  274. }
  275. namespace vstd
  276. {
  277. // combine hashes. Present in boost but not in std
  278. template <class T>
  279. inline void hash_combine(std::size_t& seed, const T& v)
  280. {
  281. std::hash<T> hasher;
  282. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  283. }
  284. //returns true if container c contains item i
  285. template <typename Container, typename Item>
  286. bool contains(const Container & c, const Item &i)
  287. {
  288. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  289. }
  290. //returns true if container c contains item i
  291. template <typename Container, typename Pred>
  292. bool contains_if(const Container & c, Pred p)
  293. {
  294. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  295. }
  296. //returns true if map c contains item i
  297. template <typename V, typename Item, typename Item2>
  298. bool contains(const std::map<Item,V> & c, const Item2 &i)
  299. {
  300. return c.find(i)!=c.end();
  301. }
  302. //returns true if unordered set c contains item i
  303. template <typename Item>
  304. bool contains(const std::unordered_set<Item> & c, const Item &i)
  305. {
  306. return c.find(i)!=c.end();
  307. }
  308. template <typename V, typename Item, typename Item2>
  309. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  310. {
  311. return c.find(i)!=c.end();
  312. }
  313. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  314. template <typename Container, typename T2>
  315. int find_pos(const Container & c, const T2 &s)
  316. {
  317. int i=0;
  318. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  319. if(*iter == s)
  320. return i;
  321. return -1;
  322. }
  323. //Func f tells if element matches
  324. template <typename Container, typename Func>
  325. int find_pos_if(const Container & c, const Func &f)
  326. {
  327. auto ret = boost::range::find_if(c, f);
  328. if(ret != std::end(c))
  329. return std::distance(std::begin(c), ret);
  330. return -1;
  331. }
  332. //returns iterator to the given element if present in container, end() if not
  333. template <typename Container, typename Item>
  334. typename Container::iterator find(Container & c, const Item &i)
  335. {
  336. return std::find(c.begin(),c.end(),i);
  337. }
  338. //returns const iterator to the given element if present in container, end() if not
  339. template <typename Container, typename Item>
  340. typename Container::const_iterator find(const Container & c, const Item &i)
  341. {
  342. return std::find(c.begin(),c.end(),i);
  343. }
  344. //returns first key that maps to given value if present, returns success via found if provided
  345. template <typename Key, typename T>
  346. Key findKey(const std::map<Key, T> & map, const T & value, bool * found = nullptr)
  347. {
  348. for(auto iter = map.cbegin(); iter != map.cend(); iter++)
  349. {
  350. if(iter->second == value)
  351. {
  352. if(found)
  353. *found = true;
  354. return iter->first;
  355. }
  356. }
  357. if(found)
  358. *found = false;
  359. return Key();
  360. }
  361. //removes element i from container c, returns false if c does not contain i
  362. template <typename Container, typename Item>
  363. typename Container::size_type operator-=(Container &c, const Item &i)
  364. {
  365. typename Container::iterator itr = find(c,i);
  366. if(itr == c.end())
  367. return false;
  368. c.erase(itr);
  369. return true;
  370. }
  371. //assigns greater of (a, b) to a and returns maximum of (a, b)
  372. template <typename t1, typename t2>
  373. t1 &amax(t1 &a, const t2 &b)
  374. {
  375. if(a >= (t1)b)
  376. return a;
  377. else
  378. {
  379. a = t1(b);
  380. return a;
  381. }
  382. }
  383. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  384. template <typename t1, typename t2>
  385. t1 &amin(t1 &a, const t2 &b)
  386. {
  387. if(a <= (t1)b)
  388. return a;
  389. else
  390. {
  391. a = t1(b);
  392. return a;
  393. }
  394. }
  395. //makes a to fit the range <b, c>
  396. template <typename t1, typename t2, typename t3>
  397. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  398. {
  399. amax(a,b);
  400. amin(a,c);
  401. return a;
  402. }
  403. //checks if a is between b and c
  404. template <typename t1, typename t2, typename t3>
  405. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  406. {
  407. return value > (t1)min && value < (t1)max;
  408. }
  409. //checks if a is within b and c
  410. template <typename t1, typename t2, typename t3>
  411. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  412. {
  413. return value >= (t1)min && value <= (t1)max;
  414. }
  415. template <typename t1, typename t2>
  416. struct assigner
  417. {
  418. public:
  419. t1 &op1;
  420. t2 op2;
  421. assigner(t1 &a1, const t2 & a2)
  422. :op1(a1), op2(a2)
  423. {}
  424. void operator()()
  425. {
  426. op1 = op2;
  427. }
  428. };
  429. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  430. // with the () operator.
  431. template <typename t1, typename t2>
  432. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  433. {
  434. return assigner<t1,t2>(a1,a2);
  435. }
  436. //deleted pointer and sets it to nullptr
  437. template <typename T>
  438. void clear_pointer(T* &ptr)
  439. {
  440. delete ptr;
  441. ptr = nullptr;
  442. }
  443. #if _MSC_VER >= 1800
  444. using std::make_unique;
  445. #else
  446. template<typename T>
  447. std::unique_ptr<T> make_unique()
  448. {
  449. return std::unique_ptr<T>(new T());
  450. }
  451. template<typename T, typename Arg1>
  452. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  453. {
  454. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  455. }
  456. template<typename T, typename Arg1, typename Arg2>
  457. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  458. {
  459. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  460. }
  461. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  462. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  463. {
  464. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  465. }
  466. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  467. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  468. {
  469. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  470. }
  471. #endif
  472. template <typename Container>
  473. typename Container::const_reference circularAt(const Container &r, size_t index)
  474. {
  475. assert(r.size());
  476. index %= r.size();
  477. auto itr = std::begin(r);
  478. std::advance(itr, index);
  479. return *itr;
  480. }
  481. template<typename Range, typename Predicate>
  482. void erase_if(Range &vec, Predicate pred)
  483. {
  484. vec.erase(boost::remove_if(vec, pred),vec.end());
  485. }
  486. template<typename Elem, typename Predicate>
  487. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  488. {
  489. auto itr = setContainer.begin();
  490. auto endItr = setContainer.end();
  491. while(itr != endItr)
  492. {
  493. auto tmpItr = itr++;
  494. if(pred(*tmpItr))
  495. setContainer.erase(tmpItr);
  496. }
  497. }
  498. //works for map and std::map, maybe something else
  499. template<typename Key, typename Val, typename Predicate>
  500. void erase_if(std::map<Key, Val> &container, Predicate pred)
  501. {
  502. auto itr = container.begin();
  503. auto endItr = container.end();
  504. while(itr != endItr)
  505. {
  506. auto tmpItr = itr++;
  507. if(pred(*tmpItr))
  508. container.erase(tmpItr);
  509. }
  510. }
  511. template<typename InputRange, typename OutputIterator, typename Predicate>
  512. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  513. {
  514. return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
  515. }
  516. template <typename Container>
  517. std::insert_iterator<Container> set_inserter(Container &c)
  518. {
  519. return std::inserter(c, c.end());
  520. }
  521. //Returns iterator to the element for which the value of ValueFunction is minimal
  522. template<class ForwardRange, class ValueFunction>
  523. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  524. {
  525. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  526. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  527. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  528. * directly for both function parameters.
  529. */
  530. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  531. {
  532. return vf(lhs) < vf(rhs);
  533. });
  534. }
  535. //Returns iterator to the element for which the value of ValueFunction is maximal
  536. template<class ForwardRange, class ValueFunction>
  537. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  538. {
  539. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  540. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  541. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  542. * directly for both function parameters.
  543. */
  544. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  545. {
  546. return vf(lhs) < vf(rhs);
  547. });
  548. }
  549. template<typename T>
  550. void advance(T &obj, int change)
  551. {
  552. obj = (T)(((int)obj) + change);
  553. }
  554. template <typename Container>
  555. typename Container::value_type backOrNull(const Container &c) //returns last element of container or nullptr if it is empty (to be used with containers of pointers)
  556. {
  557. if(c.size())
  558. return c.back();
  559. else
  560. return typename Container::value_type();
  561. }
  562. template <typename Container>
  563. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or nullptr if it is empty (to be used with containers of pointers)
  564. {
  565. if(c.size())
  566. return c.front();
  567. else
  568. return nullptr;
  569. }
  570. template <typename Container, typename Index>
  571. bool isValidIndex(const Container &c, Index i)
  572. {
  573. return i >= 0 && i < c.size();
  574. }
  575. template <typename Container, typename Index>
  576. boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
  577. {
  578. if(isValidIndex(c, i))
  579. {
  580. auto itr = c.begin();
  581. std::advance(itr, i);
  582. return *itr;
  583. }
  584. return boost::none;
  585. }
  586. template <typename Container, typename Pred>
  587. static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
  588. {
  589. auto pos = range::find_if(r, t);
  590. if(pos == boost::end(r))
  591. return boost::none;
  592. else
  593. return *pos;
  594. }
  595. template <typename Container>
  596. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  597. {
  598. if(index < r.size())
  599. return r[index];
  600. return defaultValue;
  601. }
  602. template <typename Container, typename Item>
  603. bool erase_if_present(Container &c, const Item &item)
  604. {
  605. auto i = std::find(c.begin(), c.end(), item);
  606. if (i != c.end())
  607. {
  608. c.erase(i);
  609. return true;
  610. }
  611. return false;
  612. }
  613. template <typename V, typename Item, typename Item2>
  614. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  615. {
  616. auto i = c.find(item);
  617. if (i != c.end())
  618. {
  619. c.erase(i);
  620. return true;
  621. }
  622. return false;
  623. }
  624. template <typename Container, typename Pred>
  625. void erase(Container &c, Pred pred)
  626. {
  627. c.erase(boost::remove_if(c, pred), c.end());
  628. }
  629. template<typename T>
  630. void removeDuplicates(std::vector<T> &vec)
  631. {
  632. boost::sort(vec);
  633. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  634. }
  635. template <typename T>
  636. void concatenate(std::vector<T> &dest, const std::vector<T> &src)
  637. {
  638. dest.reserve(dest.size() + src.size());
  639. dest.insert(dest.end(), src.begin(), src.end());
  640. }
  641. template <typename T>
  642. std::vector<T> intersection(std::vector<T> &v1, std::vector<T> &v2)
  643. {
  644. std::vector<T> v3;
  645. std::sort(v1.begin(), v1.end());
  646. std::sort(v2.begin(), v2.end());
  647. std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
  648. return v3;
  649. }
  650. template <typename Key, typename V>
  651. bool containsMapping(const std::multimap<Key,V> & map, const std::pair<const Key,V> & mapping)
  652. {
  653. auto range = map.equal_range(mapping.first);
  654. for(auto contained = range.first; contained != range.second; contained++)
  655. {
  656. if(mapping.second == contained->second)
  657. return true;
  658. }
  659. return false;
  660. }
  661. using boost::math::round;
  662. }
  663. using vstd::operator-=;
  664. using vstd::make_unique;
  665. #ifdef NO_STD_TOSTRING
  666. namespace std
  667. {
  668. template <typename T>
  669. inline std::string to_string(const T& value)
  670. {
  671. std::ostringstream ss;
  672. ss << value;
  673. return ss.str();
  674. }
  675. }
  676. #endif // NO_STD_TOSTRING
  677. VCMI_LIB_NAMESPACE_END