Global.h 22 KB

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