Triangles.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * Triangles
  3. * Copyright (C) 2016 POSITIVE MENTAL ATTITUDE
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <sstream>
  18. #include <thread>
  19. #include <fstream>
  20. #include <iomanip>
  21. #include "Triangles.hpp"
  22. #include "IngameState.hpp"
  23. #include "MenuState.hpp"
  24. #include "Utility.hpp"
  25. Triangles::Triangles(int argc, char** argv):
  26. _returnCode(0),
  27. _window("Triangles", sf::Vector2u(640u, 480u)),
  28. _current(nullptr),
  29. _initialState(State::Menu)
  30. {
  31. _variables.fullscreen = false;
  32. _variables.vsync = false;
  33. _variables.running = true;
  34. _variables.needsUpdate = false;
  35. _variables.shaders = true;
  36. _variables.window = &_window;
  37. _variables.assets = &_assets;
  38. _variables.core = this;
  39. _variables.foreground = nullptr;
  40. passArguments(argc, argv);
  41. if(_variables.running)
  42. {
  43. init();
  44. refresh();
  45. load(_initialState);
  46. }
  47. }
  48. void Triangles::init()
  49. {
  50. _context = _variables;
  51. _window.setContext(&_context);
  52. _window.recreate();
  53. _fps.setFont(_assets.loadFont("data/ttf/canonical/Ubuntu-L.ttf"));
  54. _fps.setCharacterSize(12);
  55. _fps.setColor(sf::Color::Black);
  56. _fps.setPosition(10, 10);
  57. _fps.setString("TRIANGLES");
  58. _fpsRect.setPosition(0, 0);
  59. _fpsRect.setSize(sf::Vector2f(375.f, 60.f));
  60. _fpsRect.setFillColor(sf::Color(255, 255, 255, 120));
  61. _loadingText.setString("Loading");
  62. _loadingHint.setFont(_assets.loadFont("data/ttf/canonical/Ubuntu-L.ttf"));
  63. _loadingText.setFont(_assets.loadFont("data/ttf/canonical/Ubuntu-L.ttf"));
  64. _loadingHint.setColor(sf::Color::White);
  65. _loadingText.setColor(sf::Color::White);
  66. _loadingTriangle.setColor(sf::Color::White);
  67. std::ifstream ifs;
  68. ifs.open("data/hints.txt");
  69. while(ifs.good())
  70. {
  71. std::string s;
  72. std::getline(ifs, s);
  73. if(s.size() > 1)
  74. _loadingHints.push_back(sf::String(s));
  75. }
  76. ifs.close();
  77. if(_loadingHints.empty())
  78. _loadingHints.push_back(sf::String(""));
  79. }
  80. void Triangles::passArguments(int argc, char** argv)
  81. {
  82. std::string argvStr[argc];
  83. for(int i = 0; i < argc; ++i)
  84. {
  85. argvStr[i] = argv[i];
  86. if(argvStr[i].size() < 2)
  87. argvStr[i] = "--kaczka";
  88. }
  89. searchArgument(argc, argvStr, 'f', "fullscreen", [this]()
  90. {
  91. _variables.fullscreen = true;
  92. });
  93. searchArgument(argc, argvStr, 'w', "window", [this]()
  94. {
  95. _variables.fullscreen = false;
  96. });
  97. searchArgument(argc, argvStr, 'v', "vsync", [this]()
  98. {
  99. _variables.vsync = true;
  100. });
  101. searchArgument(argc, argvStr, 's', "skip", [this]()
  102. {
  103. _initialState = State::Ingame;
  104. });
  105. searchArgument(argc, argvStr, 'r', "resolution", [this](std::string param)
  106. {
  107. if(param == "640x480")
  108. {
  109. std::cerr << "What year is it?\n";
  110. _returnCode = 1;
  111. _variables.running = false;
  112. }
  113. std::size_t found = param.rfind('x');
  114. if(found == std::string::npos)
  115. return;
  116. std::string sub = param;
  117. std::string sup = param;
  118. sub.erase(sub.begin() + found, sub.end());
  119. sup.erase(sup.begin(), sup.begin() + found + 1);
  120. unsigned w, h;
  121. std::stringstream ss;
  122. ss << sub;
  123. ss >> w;
  124. ss.str(std::string());
  125. ss.clear();
  126. ss << sup;
  127. ss >> h;
  128. _window.setSize(w, h);
  129. });
  130. searchArgument(argc, argvStr, 'h', "help", [this]()
  131. {
  132. std::cout << "triangles: triangles [OPTION]..." << std::endl;
  133. std::cout << "A pseudogame not meant to be run by sane people." << std::endl << std::endl;
  134. std::cout << "Copyright (C) 2016 POSITIVE MENTAL ATTITUDE" << std::endl;
  135. std::cout << "This program comes with ABSOLUTELY NO WARRANTY;" << std::endl;
  136. std::cout << "This is free software, and you are welcome to redistribute it" << std::endl;
  137. std::cout << "under certain conditions; see LICENSE.md" << std::endl << std::endl;
  138. std::cout << std::setw(8) << "-f" << " or " << std::setw(16) << "--fullscreen" << " prevents from playing in windowed mode; try F11" << std::endl;
  139. std::cout << std::setw(8) << "-w" << " or " << std::setw(16) << "--window" << " prevents from playing in fullscreen mode; try F11" << std::endl;
  140. std::cout << std::setw(8) << "-v" << " or " << std::setw(16) << "--vsync" << " prevents from playing without vertical synchronization; try F10" << std::endl;
  141. std::cout << std::setw(8) << "-s" << " or " << std::setw(16) << "--skip" << " prevents from going to the main menu; try Escape" << std::endl;
  142. std::cout << std::setw(8) << "-h" << " or " << std::setw(16) << "--help" << " prevents from running the actual game" << std::endl;
  143. std::cout << std::setw(8) << "-r WxH" << " or " << std::setw(16) << "--resolution=WxH" << " prevents from running at 640x480" << std::endl;
  144. _variables.running = false;
  145. });
  146. }
  147. void Triangles::searchArgument(int argc, std::string argvStr[], char callShort, std::string callLong, std::function<void()> lambda)
  148. {
  149. for(int i = 1; i < argc; ++i)
  150. {
  151. if((argvStr[i][0] == '-' and argvStr[i][1] == callShort) or argvStr[i] == "--" + callLong)
  152. {
  153. lambda();
  154. break;
  155. }
  156. }
  157. }
  158. void Triangles::searchArgument(int argc, std::string argvStr[], char callShort, std::string callLong, std::function<void(std::string param)> lambda)
  159. {
  160. for(int i = 1; i < argc; ++i)
  161. {
  162. if(argvStr[i][0] == '-' and argvStr[i][1] == callShort and i < argc - 1)
  163. {
  164. lambda(argvStr[i + 1]);
  165. break;
  166. }
  167. std::size_t found = argvStr[i].rfind('=');
  168. if(found == std::string::npos)
  169. continue;
  170. std::string sub = argvStr[i];
  171. std::string sup = argvStr[i];
  172. sub.erase(sub.begin() + found, sub.end());
  173. sup.erase(sup.begin(), sup.begin() + found + 1);
  174. if(sub == "--" + callLong)
  175. {
  176. lambda(sup);
  177. break;
  178. }
  179. }
  180. }
  181. void Triangles::refresh()
  182. {
  183. float u = _window.getSize().x >= 1024 ? 1.f : 0.75f;
  184. _loadingHint.setCharacterSize(20 * u);
  185. _loadingText.setCharacterSize(20 * u);
  186. _loadingTriangle.setSize(12.f * u);
  187. _loadingTriangle.setPosition(_window.getSize().x - 140.f, _window.getSize().y - (u == 1.f ? 45.f : 50.f));
  188. _loadingText.setPosition(_window.getSize().x - 120.f, _window.getSize().y - 60.f);
  189. }
  190. void Triangles::load(int stateType)
  191. {
  192. Echo::debug("Deleting current state.");
  193. if(_current)
  194. delete _current;
  195. Echo::debug("Loading state ID: ", stateType);
  196. switch(stateType)
  197. {
  198. case State::Menu:
  199. _current = new MenuState;
  200. break;
  201. case State::Ingame:
  202. _current = new IngameState;
  203. break;
  204. default:
  205. return;
  206. }
  207. _current->setContext(&_context);
  208. _loadingHint.setString(_loadingHints[rand() % _loadingHints.size()]);
  209. _loadingHint.setPosition(_window.getSize().x / 2.f - _loadingHint.getLocalBounds().width / 2.f, _window.getSize().y - 60.f);
  210. _window.lockFramerate(true);
  211. _window.setActive(false);
  212. std::thread t1(&Triangles::loadingRender, this);
  213. std::thread t2(&State::init, _current);
  214. t1.join();
  215. t2.join();
  216. _window.lockFramerate(false);
  217. _current->refresh();
  218. Echo::debug("Done.");
  219. }
  220. int Triangles::run(unsigned count)
  221. {
  222. sf::Clock clock;
  223. sf::Time delta, epsilon = sf::seconds(1.f / 60.f);
  224. if(_context.running)
  225. {
  226. Echo::out(Echo::Empty, "Triangles version -1.0.0.0");
  227. Echo::out(Echo::Empty, "Copyright (C) 2016 POSITIVE MENTAL ATTITUDE");
  228. Echo::out(Echo::Empty, "This program comes with ABSOLUTELY NO WARRANTY;");
  229. Echo::out(Echo::Empty, "This is free software, and you are welcome to redistribute it");
  230. Echo::out(Echo::Empty, "under certain conditions; see LICENSE.md");
  231. Echo::out(Echo::Info, "This is #", count, " Triangles run on this install.", count >= 666 ? " Thanks for being addicted!" : " I like cookies.");
  232. }
  233. /**
  234. * Main loop
  235. */
  236. while(_context.running)
  237. {
  238. if(_context.needsUpdate)
  239. {
  240. refresh();
  241. _current->refresh();
  242. _context.needsUpdate = false;
  243. _variables = _context;
  244. }
  245. if(_current->status() != State::Ongoing)
  246. {
  247. load(_current->status());
  248. }
  249. coreThink();
  250. coreInput();
  251. delta = clock.restart();
  252. fpsCalc(delta);
  253. while(delta > epsilon)
  254. {
  255. delta -= epsilon;
  256. coreUpdate(epsilon);
  257. }
  258. coreUpdate(delta);
  259. coreRender();
  260. }
  261. return _returnCode;
  262. }
  263. void Triangles::coreThink()
  264. {
  265. sf::Event event;
  266. while(_window.pollEvent(event))
  267. {
  268. if(_current->status())
  269. _current->coreThink(event);
  270. _window.think(event);
  271. if(event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::F11)
  272. _context.fullscreen = !_context.fullscreen, _variables.fullscreen = _context.fullscreen, _window.recreate();
  273. if(event.type == sf::Event::KeyPressed and event.key.code == sf::Keyboard::F10)
  274. _context.vsync = !_context.vsync, _variables.vsync = _context.vsync, _window.recreate();
  275. }
  276. }
  277. void Triangles::coreInput()
  278. {
  279. _current->coreInput();
  280. _window.think();
  281. }
  282. void Triangles::fpsCalc(sf::Time delta)
  283. {
  284. static sf::Clock clock;
  285. static float avg = 0.f, avgL = 0.f;
  286. static float min = 10000.f, max = 0.f;
  287. static float minL = 0.f, maxL = 0.f;
  288. static unsigned avgC = 0;
  289. float curr = 1.f / delta.asSeconds();
  290. if(avgC == 0)
  291. {
  292. avg = curr, avgC = 1;
  293. min = curr;
  294. max = curr;
  295. }
  296. else
  297. {
  298. avg = (avg * avgC + curr) / (avgC + 1);
  299. ++avgC; // Called explicitly in order to avoid undefined behaviour.
  300. min = std::min(min, curr);
  301. max = std::max(max, curr);
  302. }
  303. if(clock.getElapsedTime() >= sf::seconds(1.f))
  304. {
  305. minL = min;
  306. maxL = max;
  307. avgL = avg;
  308. avgC = 0;
  309. clock.restart();
  310. }
  311. std::ostringstream oss;
  312. oss << "Build time: " << __DATE__ << ' ' << __TIME__ << '\n';
  313. oss << "Framerate: (min/max/avg/curr): " << minL << '/' << maxL << '/' << avgL << '/' << curr << '\n';
  314. oss << "Settings: " << (_variables.vsync ? "vsync " : "") << (_variables.fullscreen ? "fullscreen " : "") << (_variables.shaders ? "shaders " : "") << '\n';
  315. _fps.setString(oss.str());
  316. }
  317. void Triangles::coreUpdate(sf::Time delta)
  318. {
  319. _current->coreUpdate(delta);
  320. }
  321. void Triangles::loadingRender()
  322. {
  323. _window.setActive(true);
  324. while(!_current->status() and _context.running)
  325. {
  326. _loadingTriangle.rotate(8.f);
  327. coreThink();
  328. _window.clear();
  329. _window.draw(_loadingHint);
  330. _window.draw(_loadingText);
  331. _window.draw(_loadingTriangle);
  332. _window.render();
  333. }
  334. }
  335. void Triangles::coreRender()
  336. {
  337. _window.clear();
  338. _current->coreRender(_variables.shaders);
  339. _window.draw(_fpsRect);
  340. _window.draw(_fps);
  341. _window.render();
  342. }