Global.h 21 KB

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