Global.h 23 KB

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