Global.h 22 KB

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