Global.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. #pragma once
  2. /*
  3. * Global.h, part of VCMI engine
  4. *
  5. * Authors: listed in file AUTHORS in main folder
  6. *
  7. * License: GNU General Public License v2.0 or later
  8. * Full text of license available in license.txt file, in main folder
  9. *
  10. */
  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. #if defined _M_X64 && defined _WIN32 //Win64 -> cannot load 32-bit DLLs for video handling
  17. # define DISABLE_VIDEO
  18. #endif
  19. #ifdef __GNUC__
  20. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10 + __GNUC_PATCHLEVEL__)
  21. #endif
  22. #if !defined(__clang__) && defined(__GNUC__) && (GCC_VERSION < 470)
  23. # error VCMI requires at least gcc-4.7.2 for successful compilation or clang-3.1. Please update your compiler
  24. #endif
  25. #if defined(__GNUC__) && (GCC_VERSION == 470 || GCC_VERSION == 471)
  26. # error This GCC version has buggy std::array::at version and should not be used. Please update to 4.7.2 or later
  27. #endif
  28. /* ---------------------------------------------------------------------------- */
  29. /* Guarantee compiler features */
  30. /* ---------------------------------------------------------------------------- */
  31. //defining available c++11 features
  32. //initialization lists - gcc or clang
  33. #if defined(__clang__) || defined(__GNUC__)
  34. # define CPP11_USE_INITIALIZERS_LIST
  35. #endif
  36. /* ---------------------------------------------------------------------------- */
  37. /* Suppress some compiler warnings */
  38. /* ---------------------------------------------------------------------------- */
  39. #ifdef _MSC_VER
  40. # pragma warning (disable : 4800 ) /* disable conversion to bool warning -- I think it's intended in all places */
  41. #endif
  42. /* ---------------------------------------------------------------------------- */
  43. /* Commonly used C++, Boost headers */
  44. /* ---------------------------------------------------------------------------- */
  45. #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
  46. #define _USE_MATH_DEFINES
  47. #include <cstdio>
  48. #include <stdio.h>
  49. #include <algorithm>
  50. #include <array>
  51. #include <cassert>
  52. #include <climits>
  53. #include <cmath>
  54. #include <cstdlib>
  55. #include <functional>
  56. #include <fstream>
  57. #include <iomanip>
  58. #include <iostream>
  59. #include <map>
  60. #include <memory>
  61. #include <numeric>
  62. #include <queue>
  63. #include <random>
  64. #include <set>
  65. #include <sstream>
  66. #include <string>
  67. #include <unordered_set>
  68. #include <unordered_map>
  69. #include <utility>
  70. #include <vector>
  71. //The only available version is 3, as of Boost 1.50
  72. #include <boost/version.hpp>
  73. #define BOOST_FILESYSTEM_VERSION 3
  74. #if BOOST_VERSION > 105000
  75. #define BOOST_THREAD_VERSION 3
  76. #endif
  77. #define BOOST_THREAD_DONT_PROVIDE_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE 1
  78. //#define BOOST_BIND_NO_PLACEHOLDERS
  79. #include <boost/algorithm/string.hpp>
  80. #include <boost/assign.hpp>
  81. #include <boost/cstdint.hpp>
  82. #include <boost/current_function.hpp>
  83. #include <boost/crc.hpp>
  84. #include <boost/date_time/posix_time/posix_time.hpp>
  85. #include <boost/date_time/posix_time/posix_time_io.hpp>
  86. #include <boost/filesystem.hpp>
  87. #include <boost/format.hpp>
  88. #include <boost/lexical_cast.hpp>
  89. #include <boost/logic/tribool.hpp>
  90. #include <boost/optional.hpp>
  91. #include <boost/program_options.hpp>
  92. #include <boost/range/adaptor/filtered.hpp>
  93. #include <boost/range/adaptor/reversed.hpp>
  94. #include <boost/range/algorithm.hpp>
  95. #include <boost/thread.hpp>
  96. #include <boost/variant.hpp>
  97. #include <boost/math/special_functions/round.hpp>
  98. #ifdef ANDROID
  99. #include <android/log.h>
  100. #endif
  101. /* ---------------------------------------------------------------------------- */
  102. /* Usings */
  103. /* ---------------------------------------------------------------------------- */
  104. using std::shared_ptr;
  105. using std::unique_ptr;
  106. using std::make_shared;
  107. //using namespace std::placeholders;
  108. namespace range = boost::range;
  109. /* ---------------------------------------------------------------------------- */
  110. /* Typedefs */
  111. /* ---------------------------------------------------------------------------- */
  112. // Integral data types
  113. typedef boost::uint64_t ui64; //unsigned int 64 bits (8 bytes)
  114. typedef boost::uint32_t ui32; //unsigned int 32 bits (4 bytes)
  115. typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
  116. typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
  117. typedef boost::int64_t si64; //signed int 64 bits (8 bytes)
  118. typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
  119. typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
  120. typedef boost::int8_t si8; //signed int 8 bits (1 byte)
  121. // Lock typedefs
  122. typedef boost::lock_guard<boost::mutex> TLockGuard;
  123. typedef boost::lock_guard<boost::recursive_mutex> TLockGuardRec;
  124. /* ---------------------------------------------------------------------------- */
  125. /* Macros */
  126. /* ---------------------------------------------------------------------------- */
  127. // Import + Export macro declarations
  128. #ifdef _WIN32
  129. # ifdef __GNUC__
  130. # define DLL_EXPORT __attribute__((dllexport))
  131. # else
  132. # define DLL_EXPORT __declspec(dllexport)
  133. # endif
  134. # define ELF_VISIBILITY
  135. #else
  136. # ifdef __GNUC__
  137. # define DLL_EXPORT __attribute__ ((visibility("default")))
  138. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  139. # endif
  140. #endif
  141. #ifdef _WIN32
  142. # ifdef __GNUC__
  143. # define DLL_IMPORT __attribute__((dllimport))
  144. # else
  145. # define DLL_IMPORT __declspec(dllimport)
  146. # endif
  147. # define ELF_VISIBILITY
  148. #else
  149. # ifdef __GNUC__
  150. # define DLL_IMPORT __attribute__ ((visibility("default")))
  151. # define ELF_VISIBILITY __attribute__ ((visibility("default")))
  152. # endif
  153. #endif
  154. #ifdef VCMI_DLL
  155. # define DLL_LINKAGE DLL_EXPORT
  156. #else
  157. # define DLL_LINKAGE DLL_IMPORT
  158. #endif
  159. #define THROW_FORMAT(message, formatting_elems) throw std::runtime_error(boost::str(boost::format(message) % formatting_elems))
  160. #define ASSERT_IF_CALLED_WITH_PLAYER if(!player) {logGlobal->errorStream() << BOOST_CURRENT_FUNCTION; assert(0);}
  161. //XXX pls dont - 'debug macros' are usually more trouble than it's worth
  162. #define HANDLE_EXCEPTION \
  163. catch (const std::exception& e) { \
  164. logGlobal->errorStream() << e.what(); \
  165. throw; \
  166. } \
  167. catch (const std::exception * e) \
  168. { \
  169. logGlobal->errorStream() << e->what(); \
  170. throw; \
  171. } \
  172. catch (const std::string& e) { \
  173. logGlobal->errorStream() << e; \
  174. throw; \
  175. }
  176. #define HANDLE_EXCEPTIONC(COMMAND) \
  177. catch (const std::exception& e) { \
  178. COMMAND; \
  179. logGlobal->errorStream() << e.what(); \
  180. throw; \
  181. } \
  182. catch (const std::string &e) \
  183. { \
  184. COMMAND; \
  185. logGlobal->errorStream() << e; \
  186. throw; \
  187. }
  188. // can be used for counting arrays
  189. template<typename T, size_t N> char (&_ArrayCountObj(const T (&)[N]))[N];
  190. #define ARRAY_COUNT(arr) (sizeof(_ArrayCountObj(arr)))
  191. // should be used for variables that becomes unused in release builds (e.g. only used for assert checks)
  192. #define UNUSED(VAR) ((void)VAR)
  193. /* ---------------------------------------------------------------------------- */
  194. /* VCMI standard library */
  195. /* ---------------------------------------------------------------------------- */
  196. #include "lib/logging/CLogger.h"
  197. void inline handleException()
  198. {
  199. try
  200. {
  201. throw;
  202. }
  203. catch(const std::exception & ex)
  204. {
  205. logGlobal->errorStream() << ex.what();
  206. }
  207. catch(const std::string & ex)
  208. {
  209. logGlobal->errorStream() << ex;
  210. }
  211. catch(...)
  212. {
  213. logGlobal->errorStream() << "Sorry, caught unknown exception type. No more info available.";
  214. }
  215. }
  216. template<typename T>
  217. std::ostream & operator<<(std::ostream & out, const boost::optional<T> & opt)
  218. {
  219. if(opt) return out << *opt;
  220. else return out << "empty";
  221. }
  222. template<typename T>
  223. std::ostream & operator<<(std::ostream & out, const std::vector<T> & container)
  224. {
  225. out << "[";
  226. for(auto it = container.begin(); it != container.end(); ++it)
  227. {
  228. out << *it;
  229. if(std::prev(container.end()) != it) out << ", ";
  230. }
  231. return out << "]";
  232. }
  233. namespace vstd
  234. {
  235. // combine hashes. Present in boost but not in std
  236. template <class T>
  237. inline void hash_combine(std::size_t& seed, const T& v)
  238. {
  239. std::hash<T> hasher;
  240. seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
  241. }
  242. //returns true if container c contains item i
  243. template <typename Container, typename Item>
  244. bool contains(const Container & c, const Item &i)
  245. {
  246. return std::find(std::begin(c), std::end(c),i) != std::end(c);
  247. }
  248. //returns true if container c contains item i
  249. template <typename Container, typename Pred>
  250. bool contains_if(const Container & c, Pred p)
  251. {
  252. return std::find_if(std::begin(c), std::end(c), p) != std::end(c);
  253. }
  254. //returns true if map c contains item i
  255. template <typename V, typename Item, typename Item2>
  256. bool contains(const std::map<Item,V> & c, const Item2 &i)
  257. {
  258. return c.find(i)!=c.end();
  259. }
  260. //returns true if unordered set c contains item i
  261. template <typename Item>
  262. bool contains(const std::unordered_set<Item> & c, const Item &i)
  263. {
  264. return c.find(i)!=c.end();
  265. }
  266. template <typename V, typename Item, typename Item2>
  267. bool contains(const std::unordered_map<Item,V> & c, const Item2 &i)
  268. {
  269. return c.find(i)!=c.end();
  270. }
  271. //returns position of first element in vector c equal to s, if there is no such element, -1 is returned
  272. template <typename Container, typename T2>
  273. int find_pos(const Container & c, const T2 &s)
  274. {
  275. size_t i=0;
  276. for (auto iter = std::begin(c); iter != std::end(c); iter++, i++)
  277. if(*iter == s)
  278. return i;
  279. return -1;
  280. }
  281. //Func f tells if element matches
  282. template <typename Container, typename Func>
  283. int find_pos_if(const Container & c, const Func &f)
  284. {
  285. auto ret = boost::range::find_if(c, f);
  286. if(ret != std::end(c))
  287. return std::distance(std::begin(c), ret);
  288. return -1;
  289. }
  290. //returns iterator to the given element if present in container, end() if not
  291. template <typename Container, typename Item>
  292. typename Container::iterator find(Container & c, const Item &i)
  293. {
  294. return std::find(c.begin(),c.end(),i);
  295. }
  296. //returns const iterator to the given element if present in container, end() if not
  297. template <typename Container, typename Item>
  298. typename Container::const_iterator find(const Container & c, const Item &i)
  299. {
  300. return std::find(c.begin(),c.end(),i);
  301. }
  302. //removes element i from container c, returns false if c does not contain i
  303. template <typename Container, typename Item>
  304. typename Container::size_type operator-=(Container &c, const Item &i)
  305. {
  306. typename Container::iterator itr = find(c,i);
  307. if(itr == c.end())
  308. return false;
  309. c.erase(itr);
  310. return true;
  311. }
  312. //assigns greater of (a, b) to a and returns maximum of (a, b)
  313. template <typename t1, typename t2>
  314. t1 &amax(t1 &a, const t2 &b)
  315. {
  316. if(a >= b)
  317. return a;
  318. else
  319. {
  320. a = b;
  321. return a;
  322. }
  323. }
  324. //assigns smaller of (a, b) to a and returns minimum of (a, b)
  325. template <typename t1, typename t2>
  326. t1 &amin(t1 &a, const t2 &b)
  327. {
  328. if(a <= b)
  329. return a;
  330. else
  331. {
  332. a = b;
  333. return a;
  334. }
  335. }
  336. //makes a to fit the range <b, c>
  337. template <typename t1, typename t2, typename t3>
  338. t1 &abetween(t1 &a, const t2 &b, const t3 &c)
  339. {
  340. amax(a,b);
  341. amin(a,c);
  342. return a;
  343. }
  344. //checks if a is between b and c
  345. template <typename t1, typename t2, typename t3>
  346. bool isbetween(const t1 &value, const t2 &min, const t3 &max)
  347. {
  348. return value > min && value < max;
  349. }
  350. //checks if a is within b and c
  351. template <typename t1, typename t2, typename t3>
  352. bool iswithin(const t1 &value, const t2 &min, const t3 &max)
  353. {
  354. return value >= min && value <= max;
  355. }
  356. template <typename t1, typename t2>
  357. struct assigner
  358. {
  359. public:
  360. t1 &op1;
  361. t2 op2;
  362. assigner(t1 &a1, const t2 & a2)
  363. :op1(a1), op2(a2)
  364. {}
  365. void operator()()
  366. {
  367. op1 = op2;
  368. }
  369. };
  370. // Assigns value a2 to a1. The point of time of the real operation can be controlled
  371. // with the () operator.
  372. template <typename t1, typename t2>
  373. assigner<t1,t2> assigno(t1 &a1, const t2 &a2)
  374. {
  375. return assigner<t1,t2>(a1,a2);
  376. }
  377. //deleted pointer and sets it to nullptr
  378. template <typename T>
  379. void clear_pointer(T* &ptr)
  380. {
  381. delete ptr;
  382. ptr = nullptr;
  383. }
  384. #if _MSC_VER >= 1800
  385. using std::make_unique;
  386. #else
  387. template<typename T>
  388. std::unique_ptr<T> make_unique()
  389. {
  390. return std::unique_ptr<T>(new T());
  391. }
  392. template<typename T, typename Arg1>
  393. std::unique_ptr<T> make_unique(Arg1 &&arg1)
  394. {
  395. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1)));
  396. }
  397. template<typename T, typename Arg1, typename Arg2>
  398. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2)
  399. {
  400. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)));
  401. }
  402. template<typename T, typename Arg1, typename Arg2, typename Arg3>
  403. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3)
  404. {
  405. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)));
  406. }
  407. template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
  408. std::unique_ptr<T> make_unique(Arg1 &&arg1, Arg2 &&arg2, Arg3 &&arg3, Arg4 &&arg4)
  409. {
  410. return std::unique_ptr<T>(new T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)));
  411. }
  412. #endif
  413. template <typename Container>
  414. typename Container::const_reference circularAt(const Container &r, size_t index)
  415. {
  416. assert(r.size());
  417. index %= r.size();
  418. auto itr = std::begin(r);
  419. std::advance(itr, index);
  420. return *itr;
  421. }
  422. template<typename Range, typename Predicate>
  423. void erase_if(Range &vec, Predicate pred)
  424. {
  425. vec.erase(boost::remove_if(vec, pred),vec.end());
  426. }
  427. template<typename Elem, typename Predicate>
  428. void erase_if(std::set<Elem> &setContainer, Predicate pred)
  429. {
  430. auto itr = setContainer.begin();
  431. auto endItr = setContainer.end();
  432. while(itr != endItr)
  433. {
  434. auto tmpItr = itr++;
  435. if(pred(*tmpItr))
  436. setContainer.erase(tmpItr);
  437. }
  438. }
  439. //works for map and std::map, maybe something else
  440. template<typename Key, typename Val, typename Predicate>
  441. void erase_if(std::map<Key, Val> &container, Predicate pred)
  442. {
  443. auto itr = container.begin();
  444. auto endItr = container.end();
  445. while(itr != endItr)
  446. {
  447. auto tmpItr = itr++;
  448. if(pred(*tmpItr))
  449. container.erase(tmpItr);
  450. }
  451. }
  452. template<typename InputRange, typename OutputIterator, typename Predicate>
  453. OutputIterator copy_if(const InputRange &input, OutputIterator result, Predicate pred)
  454. {
  455. return std::copy_if(boost::const_begin(input), std::end(input), result, pred);
  456. }
  457. template <typename Container>
  458. std::insert_iterator<Container> set_inserter(Container &c)
  459. {
  460. return std::inserter(c, c.end());
  461. }
  462. //Returns iterator to the element for which the value of ValueFunction is minimal
  463. template<class ForwardRange, class ValueFunction>
  464. auto minElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  465. {
  466. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  467. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  468. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  469. * directly for both function parameters.
  470. */
  471. return boost::min_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  472. {
  473. return vf(lhs) < vf(rhs);
  474. });
  475. }
  476. //Returns iterator to the element for which the value of ValueFunction is maximal
  477. template<class ForwardRange, class ValueFunction>
  478. auto maxElementByFun(const ForwardRange& rng, ValueFunction vf) -> decltype(std::begin(rng))
  479. {
  480. /* Clang crashes when instantiating this function template and having PCH compilation enabled.
  481. * There is a bug report here: http://llvm.org/bugs/show_bug.cgi?id=18744
  482. * Current bugfix is to don't use a typedef for decltype(*std::begin(rng)) and to use decltype
  483. * directly for both function parameters.
  484. */
  485. return boost::max_element(rng, [&] (decltype(*std::begin(rng)) lhs, decltype(*std::begin(rng)) rhs) -> bool
  486. {
  487. return vf(lhs) < vf(rhs);
  488. });
  489. }
  490. template<typename T>
  491. void advance(T &obj, int change)
  492. {
  493. obj = (T)(((int)obj) + change);
  494. }
  495. template <typename Container>
  496. 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)
  497. {
  498. if(c.size())
  499. return c.back();
  500. else
  501. return typename Container::value_type();
  502. }
  503. template <typename Container>
  504. 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)
  505. {
  506. if(c.size())
  507. return c.front();
  508. else
  509. return nullptr;
  510. }
  511. template <typename Container, typename Index>
  512. bool isValidIndex(const Container &c, Index i)
  513. {
  514. return i >= 0 && i < c.size();
  515. }
  516. template <typename Container, typename Index>
  517. boost::optional<typename Container::const_reference> tryAt(const Container &c, Index i)
  518. {
  519. if(isValidIndex(c, i))
  520. {
  521. auto itr = c.begin();
  522. std::advance(itr, i);
  523. return *itr;
  524. }
  525. return boost::none;
  526. }
  527. template <typename Container, typename Pred>
  528. static boost::optional<typename Container::const_reference> tryFindIf(const Container &r, const Pred &t)
  529. {
  530. auto pos = range::find_if(r, t);
  531. if(pos == boost::end(r))
  532. return boost::none;
  533. else
  534. return *pos;
  535. }
  536. template <typename Container>
  537. typename Container::const_reference atOrDefault(const Container &r, size_t index, const typename Container::const_reference &defaultValue)
  538. {
  539. if(index < r.size())
  540. return r[index];
  541. return defaultValue;
  542. }
  543. template <typename Container, typename Item>
  544. bool erase_if_present(Container &c, const Item &item)
  545. {
  546. auto i = std::find(c.begin(), c.end(), item);
  547. if (i != c.end())
  548. {
  549. c.erase(i);
  550. return true;
  551. }
  552. return false;
  553. }
  554. template <typename V, typename Item, typename Item2>
  555. bool erase_if_present(std::map<Item,V> & c, const Item2 &item)
  556. {
  557. auto i = c.find(item);
  558. if (i != c.end())
  559. {
  560. c.erase(i);
  561. return true;
  562. }
  563. return false;
  564. }
  565. template <typename Container, typename Pred>
  566. void erase(Container &c, Pred pred)
  567. {
  568. c.erase(boost::remove_if(c, pred), c.end());
  569. }
  570. template<typename T>
  571. void removeDuplicates(std::vector<T> &vec)
  572. {
  573. boost::sort(vec);
  574. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  575. }
  576. using boost::math::round;
  577. }
  578. using vstd::operator-=;
  579. using vstd::make_unique;