Global.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. // Required for building boost::stacktrace on macOS.
  100. // See https://github.com/boostorg/stacktrace/issues/88
  101. #if defined(VCMI_APPLE)
  102. #define _GNU_SOURCE
  103. #endif
  104. #define _USE_MATH_DEFINES
  105. #include <algorithm>
  106. #include <any>
  107. #include <array>
  108. #include <atomic>
  109. #include <bitset>
  110. #include <cassert>
  111. #include <chrono>
  112. #include <climits>
  113. #include <cmath>
  114. #include <condition_variable>
  115. #include <cstdio>
  116. #include <cstdlib>
  117. #include <fstream>
  118. #include <functional>
  119. #include <iomanip>
  120. #include <iostream>
  121. #include <map>
  122. #include <memory>
  123. #include <mutex>
  124. #include <numeric>
  125. #include <optional>
  126. #include <queue>
  127. #include <random>
  128. #include <regex>
  129. #include <set>
  130. #include <shared_mutex>
  131. #include <sstream>
  132. #include <string>
  133. #include <thread>
  134. #include <unordered_map>
  135. #include <unordered_set>
  136. #include <utility>
  137. #include <variant>
  138. #include <vector>
  139. //The only available version is 3, as of Boost 1.50
  140. #include <boost/version.hpp>
  141. #define BOOST_FILESYSTEM_VERSION 3
  142. #if BOOST_VERSION > 105000
  143. # define BOOST_THREAD_VERSION 3
  144. #endif
  145. #if BOOST_VERSION == 107400
  146. # define BOOST_ALLOW_DEPRECATED_HEADERS
  147. #endif
  148. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  149. //need to link boost thread dynamically to avoid https://stackoverflow.com/questions/35978572/boost-thread-interupt-does-not-work-when-crossing-a-dll-boundary
  150. //for example VCAI::finish() may freeze on thread join after interrupt when linking this statically
  151. #ifndef BOOST_THREAD_USE_DLL
  152. # define BOOST_THREAD_USE_DLL
  153. #endif
  154. #define BOOST_BIND_NO_PLACEHOLDERS
  155. #if BOOST_VERSION >= 106600
  156. #define BOOST_ASIO_ENABLE_OLD_SERVICES
  157. #endif
  158. #include <boost/algorithm/hex.hpp>
  159. #include <boost/algorithm/string.hpp>
  160. #include <boost/crc.hpp>
  161. #include <boost/current_function.hpp>
  162. #include <boost/container/small_vector.hpp>
  163. #include <boost/container/static_vector.hpp>
  164. #include <boost/filesystem.hpp>
  165. #include <boost/filesystem/fstream.hpp>
  166. #include <boost/filesystem/path.hpp>
  167. #include <boost/format.hpp>
  168. #include <boost/functional/hash.hpp>
  169. #include <boost/lexical_cast.hpp>
  170. #ifdef VCMI_WINDOWS
  171. #include <boost/locale/generator.hpp>
  172. #endif
  173. #include <boost/logic/tribool.hpp>
  174. #include <boost/multi_array.hpp>
  175. #include <boost/range/adaptor/filtered.hpp>
  176. #include <boost/range/adaptor/reversed.hpp>
  177. #include <boost/range/algorithm.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. using TLockGuard = std::lock_guard<std::mutex>;
  200. using TLockGuardRec = std::lock_guard<std::recursive_mutex>;
  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. // old iOS SDKs compatibility
  231. #ifdef VCMI_IOS
  232. #include <AvailabilityVersions.h>
  233. #ifndef __IPHONE_13_0
  234. #define __IPHONE_13_0 130000
  235. #endif
  236. #endif // VCMI_IOS
  237. // single-process build makes 2 copies of the main lib by wrapping it in a namespace
  238. #ifdef VCMI_LIB_NAMESPACE
  239. #define VCMI_LIB_NAMESPACE_BEGIN namespace VCMI_LIB_NAMESPACE {
  240. #define VCMI_LIB_NAMESPACE_END }
  241. #define VCMI_LIB_USING_NAMESPACE using namespace VCMI_LIB_NAMESPACE;
  242. #define VCMI_LIB_WRAP_NAMESPACE(x) VCMI_LIB_NAMESPACE::x
  243. #else
  244. #define VCMI_LIB_NAMESPACE_BEGIN
  245. #define VCMI_LIB_NAMESPACE_END
  246. #define VCMI_LIB_USING_NAMESPACE
  247. #define VCMI_LIB_WRAP_NAMESPACE(x) ::x
  248. #endif
  249. /* ---------------------------------------------------------------------------- */
  250. /* VCMI standard library */
  251. /* ---------------------------------------------------------------------------- */
  252. #include <vstd/CLoggerBase.h>
  253. VCMI_LIB_NAMESPACE_BEGIN
  254. namespace vstd
  255. {
  256. // combine hashes. Present in boost but not in std
  257. template <class T>
  258. inline void hash_combine(std::size_t& seed, const T& v)
  259. {
  260. std::hash<T> hasher;
  261. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  262. }
  263. //returns true if container c contains item i
  264. template <typename Container, typename Item>
  265. bool contains(const Container & c, const Item &i)
  266. {
  267. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  268. }
  269. //returns true if container c contains item i
  270. template <typename Container, typename Pred>
  271. bool contains_if(const Container & c, Pred p)
  272. {
  273. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  274. }
  275. //returns true if map c contains item i
  276. template <typename V, typename Item, typename Item2>
  277. bool contains(const std::map<Item,V> & c, const Item2 &i)
  278. {
  279. return c.find(i)!=c.end();
  280. }
  281. //returns true if unordered set c contains item i
  282. template <typename Item>
  283. bool contains(const std::unordered_set<Item> & c, const Item &i)
  284. {
  285. return c.find(i)!=c.end();
  286. }
  287. template <typename V, typename Item, typename Item2>
  288. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  289. {
  290. return c.find(i)!=c.end();
  291. }
  292. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  293. template <typename Container, typename T2>
  294. int find_pos(const Container & c, const T2 &s)
  295. {
  296. int i=0;
  297. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  298. if(*iter == s)
  299. return i;
  300. return -1;
  301. }
  302. //Func f tells if element matches
  303. template <typename Container, typename Func>
  304. int find_pos_if(const Container & c, const Func &f)
  305. {
  306. auto ret = boost::range::find_if(c, f);
  307. if(ret != std::end(c))
  308. return std::distance(std::begin(c), ret);
  309. return -1;
  310. }
  311. //returns iterator to the given element if present in container, end() if not
  312. template <typename Container, typename Item>
  313. typename Container::iterator find(Container & c, const Item &i)
  314. {
  315. return std::find(c.begin(),c.end(),i);
  316. }
  317. //returns const iterator to the given element if present in container, end() if not
  318. template <typename Container, typename Item>
  319. typename Container::const_iterator find(const Container & c, const Item &i)
  320. {
  321. return std::find(c.begin(),c.end(),i);
  322. }
  323. // returns existing value from map, or default value if key does not exists
  324. template <typename Map>
  325. const typename Map::mapped_type & find_or(const Map& m, const typename Map::key_type& key, const typename Map::mapped_type& defaultValue) {
  326. auto it = m.find(key);
  327. if (it == m.end())
  328. return defaultValue;
  329. return it->second;
  330. }
  331. // given a map from keys to values, creates a new map from values to keys
  332. template<typename K, typename V>
  333. static std::map<V, K> reverseMap(const std::map<K, V>& m) {
  334. std::map<V, K> r;
  335. for (const auto& kv : m)
  336. r[kv.second] = kv.first;
  337. return r;
  338. }
  339. //returns first key that maps to given value if present, returns success via found if provided
  340. template <typename Key, typename T>
  341. Key findKey(const std::map<Key, T> & map, const T & value, bool * found = nullptr)
  342. {
  343. for(auto iter = map.cbegin(); iter != map.cend(); iter++)
  344. {
  345. if(iter->second == value)
  346. {
  347. if(found)
  348. *found = true;
  349. return iter->first;
  350. }
  351. }
  352. if(found)
  353. *found = false;
  354. return Key();
  355. }
  356. //removes element i from container c, returns false if c does not contain i
  357. template <typename Container, typename Item>
  358. typename Container::size_type operator-=(Container &c, const Item &i)
  359. {
  360. typename Container::iterator itr = find(c,i);
  361. if(itr == c.end())
  362. return false;
  363. c.erase(itr);
  364. return true;
  365. }
  366. //assigns greater of (a, b) to a and returns maximum of (a, b)
  367. template <typename t1, typename t2>
  368. t1 &amax(t1 &a, const t2 &b)
  369. {
  370. if(a >= (t1)b)
  371. return a;
  372. else
  373. {
  374. a = t1(b);
  375. return a;
  376. }
  377. }
  378. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  379. template <typename t1, typename t2>
  380. t1 &amin(t1 &a, const t2 &b)
  381. {
  382. if(a <= (t1)b)
  383. return a;
  384. else
  385. {
  386. a = t1(b);
  387. return a;
  388. }
  389. }
  390. //makes a to fit the range <b, c>
  391. template <typename T>
  392. void abetween(T &value, const T &min, const T &max)
  393. {
  394. value = std::clamp(value, min, max);
  395. }
  396. //checks if a is between b and c
  397. template <typename t1, typename t2, typename t3>
  398. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  399. {
  400. return value > (t1)min && value < (t1)max;
  401. }
  402. //checks if a is within b and c
  403. template <typename t1, typename t2, typename t3>
  404. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  405. {
  406. return value >= (t1)min && value <= (t1)max;
  407. }
  408. template <typename t1, typename t2>
  409. struct assigner
  410. {
  411. public:
  412. t1 &op1;
  413. t2 op2;
  414. assigner(t1 &a1, const t2 & a2)
  415. :op1(a1), op2(a2)
  416. {}
  417. void operator()()
  418. {
  419. op1 = op2;
  420. }
  421. };
  422. //deleted pointer and sets it to nullptr
  423. template <typename T>
  424. void clear_pointer(T* &ptr)
  425. {
  426. delete ptr;
  427. ptr = nullptr;
  428. }
  429. template <typename Container>
  430. typename Container::const_reference circularAt(const Container &r, size_t index)
  431. {
  432. assert(r.size());
  433. index %= r.size();
  434. auto itr = std::begin(r);
  435. std::advance(itr, index);
  436. return *itr;
  437. }
  438. template <typename Container, typename Item>
  439. void erase(Container &c, const Item &item)
  440. {
  441. c.erase(boost::remove(c, item), c.end());
  442. }
  443. template<typename Range, typename Predicate>
  444. void erase_if(Range &vec, Predicate pred)
  445. {
  446. vec.erase(boost::remove_if(vec, pred),vec.end());
  447. }
  448. template<typename Elem, typename Predicate>
  449. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  450. {
  451. auto itr = setContainer.begin();
  452. auto endItr = setContainer.end();
  453. while(itr != endItr)
  454. {
  455. auto tmpItr = itr++;
  456. if(pred(*tmpItr))
  457. setContainer.erase(tmpItr);
  458. }
  459. }
  460. template<typename Elem, typename Predicate>
  461. void erase_if(std::unordered_set<Elem> &setContainer, Predicate pred)
  462. {
  463. auto itr = setContainer.begin();
  464. auto endItr = setContainer.end();
  465. while(itr != endItr)
  466. {
  467. auto tmpItr = itr++;
  468. if(pred(*tmpItr))
  469. setContainer.erase(tmpItr);
  470. }
  471. }
  472. //works for map and std::map, maybe something else
  473. template<typename Key, typename Val, typename Predicate>
  474. void erase_if(std::map<Key, Val> &container, Predicate pred)
  475. {
  476. auto itr = container.begin();
  477. auto endItr = container.end();
  478. while(itr != endItr)
  479. {
  480. auto tmpItr = itr++;
  481. if(pred(*tmpItr))
  482. container.erase(tmpItr);
  483. }
  484. }
  485. //works for std::unordered_map, maybe something else
  486. template<typename Key, typename Val, typename Predicate>
  487. void erase_if(std::unordered_map<Key, Val> & container, Predicate pred)
  488. {
  489. auto itr = container.begin();
  490. auto endItr = container.end();
  491. while(itr != endItr)
  492. {
  493. auto tmpItr = itr++;
  494. if(pred(*tmpItr))
  495. container.erase(tmpItr);
  496. }
  497. }
  498. // Removes all duplicate elements from the vector
  499. template<typename T>
  500. void unique(std::vector<T> &vec)
  501. {
  502. std::sort(vec.begin(), vec.end());
  503. auto newEnd = std::unique(vec.begin(), vec.end());
  504. vec.erase(newEnd, vec.end());
  505. }
  506. template<typename InputRange, typename OutputIterator, typename Predicate>
  507. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  508. {
  509. return std::copy_if(std::cbegin(input), std::end(input), result, pred);
  510. }
  511. template <typename Container>
  512. std::insert_iterator<Container> set_inserter(Container &c)
  513. {
  514. return std::inserter(c, c.end());
  515. }
  516. //Returns iterator to the element for which the value of ValueFunction is minimal
  517. template<class ForwardRange, class ValueFunction>
  518. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  519. {
  520. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  521. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  522. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  523. * directly for both function parameters.
  524. */
  525. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  526. {
  527. return vf(lhs) < vf(rhs);
  528. });
  529. }
  530. //Returns iterator to the element for which the value of ValueFunction is maximal
  531. template<class ForwardRange, class ValueFunction>
  532. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  533. {
  534. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  535. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  536. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  537. * directly for both function parameters.
  538. */
  539. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  540. {
  541. return vf(lhs) < vf(rhs);
  542. });
  543. }
  544. /// Increments value by specific delta
  545. /// similar to std::next but works with other types, e.g. enum class
  546. template<typename T>
  547. T next(const T &obj, int change)
  548. {
  549. return static_cast<T>(static_cast<ptrdiff_t>(obj) + change);
  550. }
  551. template <typename Container>
  552. 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)
  553. {
  554. if(c.size())
  555. return c.back();
  556. else
  557. return typename Container::value_type();
  558. }
  559. template <typename Container>
  560. 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)
  561. {
  562. if(c.size())
  563. return c.front();
  564. else
  565. return nullptr;
  566. }
  567. template <typename Container, typename Index>
  568. bool isValidIndex(const Container &c, Index i)
  569. {
  570. return i >= 0 && i < c.size();
  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 Container>
  602. void removeDuplicates(Container &vec)
  603. {
  604. std::sort(vec.begin(), vec.end());
  605. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  606. }
  607. template <typename Container>
  608. void concatenate(Container &dest, const Container &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 T>
  623. std::set<T> difference(const std::set<T> &s1, const std::set<T> s2)
  624. {
  625. std::set<T> s3;
  626. std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(s3, s3.end()));
  627. return s3;
  628. }
  629. template <typename Key, typename V>
  630. bool containsMapping(const std::multimap<Key,V> & map, const std::pair<const Key,V> & mapping)
  631. {
  632. auto range = map.equal_range(mapping.first);
  633. for(auto contained = range.first; contained != range.second; contained++)
  634. {
  635. if(mapping.second == contained->second)
  636. return true;
  637. }
  638. return false;
  639. }
  640. //c++20 feature
  641. template<typename Arithmetic, typename Floating>
  642. Arithmetic lerp(const Arithmetic & a, const Arithmetic & b, const Floating & f)
  643. {
  644. return a + (b - a) * f;
  645. }
  646. /// Divides dividend by divisor and rounds result up
  647. /// For use with integer-only arithmetic
  648. template<typename Integer1, typename Integer2>
  649. Integer1 divideAndCeil(const Integer1 & dividend, const Integer2 & divisor)
  650. {
  651. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  652. return (dividend + divisor - 1) / divisor;
  653. }
  654. /// Divides dividend by divisor and rounds result to nearest
  655. /// For use with integer-only arithmetic
  656. template<typename Integer1, typename Integer2>
  657. Integer1 divideAndRound(const Integer1 & dividend, const Integer2 & divisor)
  658. {
  659. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  660. return (dividend + divisor / 2 - 1) / divisor;
  661. }
  662. /// Divides dividend by divisor and rounds result down
  663. /// For use with integer-only arithmetic
  664. template<typename Integer1, typename Integer2>
  665. Integer1 divideAndFloor(const Integer1 & dividend, const Integer2 & divisor)
  666. {
  667. static_assert(std::is_integral_v<Integer1> && std::is_integral_v<Integer2>, "This function should only be used with integral types");
  668. return dividend / divisor;
  669. }
  670. template<typename Floating>
  671. bool isAlmostZero(const Floating & value)
  672. {
  673. constexpr Floating epsilon(0.00001);
  674. return std::abs(value) <= epsilon;
  675. }
  676. template<typename Floating1, typename Floating2>
  677. bool isAlmostEqual(const Floating1 & left, const Floating2 & right)
  678. {
  679. using Floating = decltype(left + right);
  680. constexpr Floating epsilon(0.00001);
  681. const Floating relativeEpsilon = std::max(std::abs(left), std::abs(right)) * epsilon;
  682. const Floating value = std::abs(left - right);
  683. return value <= relativeEpsilon;
  684. }
  685. ///compile-time version of std::abs for ints for int3, in clang++15 std::abs is constexpr
  686. static constexpr int abs(int i) {
  687. if(i < 0) return -i;
  688. return i;
  689. }
  690. ///C++23
  691. template< class Enum > constexpr std::underlying_type_t<Enum> to_underlying( Enum e ) noexcept
  692. {
  693. return static_cast<std::underlying_type_t<Enum>>(e);
  694. }
  695. }
  696. using vstd::operator-=;
  697. VCMI_LIB_NAMESPACE_END