Global.h 22 KB

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