CMainMenu.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. * CMainMenu.cpp, 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. #include "StdInc.h"
  11. #include "CMainMenu.h"
  12. #include "CCampaignScreen.h"
  13. #include "CreditsScreen.h"
  14. #include "../lobby/CBonusSelection.h"
  15. #include "../lobby/CSelectionBase.h"
  16. #include "../lobby/CLobbyScreen.h"
  17. #include "../../lib/filesystem/Filesystem.h"
  18. #include "../../lib/filesystem/CCompressedStream.h"
  19. #include "../gui/SDL_Extensions.h"
  20. #include "../gui/CCursorHandler.h"
  21. #include "../CGameInfo.h"
  22. #include "../../lib/CGeneralTextHandler.h"
  23. #include "../../lib/JsonNode.h"
  24. #include "../CMusicHandler.h"
  25. #include "../CVideoHandler.h"
  26. #include "../Graphics.h"
  27. #include "../../lib/serializer/Connection.h"
  28. #include "../../lib/serializer/CTypeList.h"
  29. #include "../../lib/VCMIDirs.h"
  30. #include "../../lib/mapping/CMap.h"
  31. #include "../windows/GUIClasses.h"
  32. #include "../CPlayerInterface.h"
  33. #include "../../CCallback.h"
  34. #include "../CMessage.h"
  35. #include "../CBitmapHandler.h"
  36. #include "../Client.h"
  37. #include "../gui/CGuiHandler.h"
  38. #include "../gui/CAnimation.h"
  39. #include "../widgets/CComponent.h"
  40. #include "../widgets/Buttons.h"
  41. #include "../widgets/MiscWidgets.h"
  42. #include "../widgets/ObjectLists.h"
  43. #include "../widgets/TextControls.h"
  44. #include "../windows/InfoWindows.h"
  45. #include "../CServerHandler.h"
  46. #include "../../lib/CStopWatch.h"
  47. #include "../../lib/NetPacksLobby.h"
  48. #include "../../lib/CThreadHelper.h"
  49. #include "../../lib/CConfigHandler.h"
  50. #include "../../lib/GameConstants.h"
  51. #include "../../lib/CRandomGenerator.h"
  52. #include "../../lib/CondSh.h"
  53. #include "../../lib/mapping/CCampaignHandler.h"
  54. namespace fs = boost::filesystem;
  55. CMainMenu * CMM = nullptr;
  56. ISelectionScreenInfo * SEL;
  57. static void do_quit()
  58. {
  59. SDL_Event event;
  60. event.quit.type = SDL_QUIT;
  61. SDL_PushEvent(&event);
  62. }
  63. CMenuScreen::CMenuScreen(const JsonNode & configNode)
  64. : CWindowObject(BORDERED), config(configNode)
  65. {
  66. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  67. background = std::make_shared<CPicture>(config["background"].String());
  68. if(config["scalable"].Bool())
  69. {
  70. if(background->bg->format->palette)
  71. background->convertToScreenBPP();
  72. background->scaleTo(Point(screen->w, screen->h));
  73. }
  74. pos = background->center();
  75. for(const JsonNode & node : config["items"].Vector())
  76. menuNameToEntry.push_back(node["name"].String());
  77. for(const JsonNode & node : config["images"].Vector())
  78. images.push_back(CMainMenu::createPicture(node));
  79. //Hardcoded entry
  80. menuNameToEntry.push_back("credits");
  81. tabs = std::make_shared<CTabbedInt>(std::bind(&CMenuScreen::createTab, this, _1));
  82. tabs->type |= REDRAW_PARENT;
  83. }
  84. std::shared_ptr<CIntObject> CMenuScreen::createTab(size_t index)
  85. {
  86. if(config["items"].Vector().size() == index)
  87. return std::make_shared<CreditsScreen>(this->pos);
  88. else
  89. return std::make_shared<CMenuEntry>(this, config["items"].Vector()[index]);
  90. }
  91. void CMenuScreen::show(SDL_Surface * to)
  92. {
  93. if(!config["video"].isNull())
  94. CCS->videoh->update(config["video"]["x"].Float() + pos.x, config["video"]["y"].Float() + pos.y, to, true, false);
  95. CIntObject::show(to);
  96. }
  97. void CMenuScreen::activate()
  98. {
  99. CCS->musich->playMusic("Music/MainMenu", true);
  100. if(!config["video"].isNull())
  101. CCS->videoh->open(config["video"]["name"].String());
  102. CIntObject::activate();
  103. }
  104. void CMenuScreen::deactivate()
  105. {
  106. if(!config["video"].isNull())
  107. CCS->videoh->close();
  108. CIntObject::deactivate();
  109. }
  110. void CMenuScreen::switchToTab(size_t index)
  111. {
  112. tabs->setActive(index);
  113. }
  114. void CMenuScreen::switchToTab(std::string name)
  115. {
  116. switchToTab(vstd::find_pos(menuNameToEntry, name));
  117. }
  118. //funciton for std::string -> std::function conversion for main menu
  119. static std::function<void()> genCommand(CMenuScreen * menu, std::vector<std::string> menuType, const std::string & string)
  120. {
  121. static const std::vector<std::string> commandType = {"to", "campaigns", "start", "load", "exit", "highscores"};
  122. static const std::vector<std::string> gameType = {"single", "multi", "campaign", "tutorial"};
  123. std::list<std::string> commands;
  124. boost::split(commands, string, boost::is_any_of("\t "));
  125. if(!commands.empty())
  126. {
  127. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  128. commands.pop_front();
  129. if(index > 3 || !commands.empty())
  130. {
  131. switch(index)
  132. {
  133. case 0: //to - switch to another tab, if such tab exists
  134. {
  135. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  136. if(index2 != menuType.size())
  137. return std::bind((void(CMenuScreen::*)(size_t))&CMenuScreen::switchToTab, menu, index2);
  138. break;
  139. }
  140. case 1: //open campaign selection window
  141. {
  142. return std::bind(&CMainMenu::openCampaignScreen, CMM, commands.front());
  143. break;
  144. }
  145. case 2: //start
  146. {
  147. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  148. {
  149. case 0:
  150. return std::bind(CMainMenu::openLobby, ESelectionScreen::newGame, true, nullptr, ELoadMode::NONE);
  151. case 1:
  152. return []() { GH.pushInt(new CMultiMode(ESelectionScreen::newGame)); };
  153. case 2:
  154. return std::bind(CMainMenu::openLobby, ESelectionScreen::campaignList, true, nullptr, ELoadMode::NONE);
  155. case 3:
  156. return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  157. }
  158. break;
  159. }
  160. case 3: //load
  161. {
  162. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  163. {
  164. case 0:
  165. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::SINGLE);
  166. case 1:
  167. return []() { GH.pushInt(new CMultiMode(ESelectionScreen::loadGame)); };
  168. case 2:
  169. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::CAMPAIGN);
  170. case 3:
  171. return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  172. }
  173. }
  174. break;
  175. case 4: //exit
  176. {
  177. return std::bind(CInfoWindow::showYesNoDialog, std::ref(CGI->generaltexth->allTexts[69]), std::vector<std::shared_ptr<CComponent>>(), do_quit, 0, PlayerColor(1));
  178. }
  179. break;
  180. case 5: //highscores
  181. {
  182. return std::bind(CInfoWindow::showInfoDialog, "Sorry, high scores menu is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  183. }
  184. }
  185. }
  186. }
  187. logGlobal->error("Failed to parse command: %s", string);
  188. return std::function<void()>();
  189. }
  190. std::shared_ptr<CButton> CMenuEntry::createButton(CMenuScreen * parent, const JsonNode & button)
  191. {
  192. std::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  193. std::pair<std::string, std::string> help;
  194. if(!button["help"].isNull() && button["help"].Float() > 0)
  195. help = CGI->generaltexth->zelp[button["help"].Float()];
  196. int posx = button["x"].Float();
  197. if(posx < 0)
  198. posx = pos.w + posx;
  199. int posy = button["y"].Float();
  200. if(posy < 0)
  201. posy = pos.h + posy;
  202. return std::make_shared<CButton>(Point(posx, posy), button["name"].String(), help, command, button["hotkey"].Float());
  203. }
  204. CMenuEntry::CMenuEntry(CMenuScreen * parent, const JsonNode & config)
  205. {
  206. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  207. type |= REDRAW_PARENT;
  208. pos = parent->pos;
  209. for(const JsonNode & node : config["images"].Vector())
  210. images.push_back(CMainMenu::createPicture(node));
  211. for(const JsonNode & node : config["buttons"].Vector())
  212. {
  213. buttons.push_back(createButton(parent, node));
  214. buttons.back()->hoverable = true;
  215. buttons.back()->type |= REDRAW_PARENT;
  216. }
  217. }
  218. CMainMenuConfig::CMainMenuConfig()
  219. : campaignSets(JsonNode(ResourceID("config/campaignSets.json"))), config(JsonNode(ResourceID("config/mainmenu.json")))
  220. {
  221. }
  222. CMainMenuConfig & CMainMenuConfig::get()
  223. {
  224. static CMainMenuConfig config;
  225. return config;
  226. }
  227. const JsonNode & CMainMenuConfig::getConfig() const
  228. {
  229. return config;
  230. }
  231. const JsonNode & CMainMenuConfig::getCampaigns() const
  232. {
  233. return campaignSets;
  234. }
  235. CMainMenu::CMainMenu()
  236. {
  237. pos.w = screen->w;
  238. pos.h = screen->h;
  239. GH.defActionsDef = 63;
  240. CMM = this;
  241. menu = new CMenuScreen(CMainMenuConfig::get().getConfig()["window"]);
  242. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  243. backgroundAroundMenu = std::make_shared<CFilledTexture>("DIBOXBCK", pos);
  244. }
  245. CMainMenu::~CMainMenu()
  246. {
  247. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  248. if(CMM == this)
  249. CMM = nullptr;
  250. if(GH.curInt == this)
  251. GH.curInt = nullptr;
  252. }
  253. void CMainMenu::update()
  254. {
  255. if(CMM != this) //don't update if you are not a main interface
  256. return;
  257. if(GH.listInt.empty())
  258. {
  259. GH.pushInt(this);
  260. GH.pushInt(menu);
  261. menu->switchToTab(0);
  262. }
  263. // Handles mouse and key input
  264. GH.updateTime();
  265. GH.handleEvents();
  266. // check for null othervice crash on finishing a campaign
  267. // /FIXME: find out why GH.listInt is empty to begin with
  268. if(GH.topInt() != nullptr)
  269. GH.topInt()->show(screen);
  270. }
  271. void CMainMenu::openLobby(ESelectionScreen screenType, bool host, const std::vector<std::string> * names, ELoadMode loadMode)
  272. {
  273. CSH->resetStateForLobby(screenType == ESelectionScreen::newGame ? StartInfo::NEW_GAME : StartInfo::LOAD_GAME, names);
  274. CSH->screenType = screenType;
  275. CSH->loadMode = loadMode;
  276. GH.pushInt(new CSimpleJoinScreen(host));
  277. }
  278. void CMainMenu::openCampaignLobby(const std::string & campaignFileName)
  279. {
  280. auto ourCampaign = std::make_shared<CCampaignState>(CCampaignHandler::getCampaign(campaignFileName));
  281. openCampaignLobby(ourCampaign);
  282. }
  283. void CMainMenu::openCampaignLobby(std::shared_ptr<CCampaignState> campaign)
  284. {
  285. CSH->resetStateForLobby(StartInfo::CAMPAIGN);
  286. CSH->screenType = ESelectionScreen::campaignList;
  287. CSH->campaignStateToSend = campaign;
  288. GH.pushInt(new CSimpleJoinScreen());
  289. }
  290. void CMainMenu::openCampaignScreen(std::string name)
  291. {
  292. if(vstd::contains(CMainMenuConfig::get().getCampaigns().Struct(), name))
  293. {
  294. GH.pushInt(new CCampaignScreen(CMainMenuConfig::get().getCampaigns()[name]));
  295. return;
  296. }
  297. logGlobal->error("Unknown campaign set: %s", name);
  298. }
  299. CMainMenu * CMainMenu::create()
  300. {
  301. if(!CMM)
  302. CMM = new CMainMenu();
  303. GH.terminate_cond->set(false);
  304. return CMM;
  305. }
  306. std::shared_ptr<CPicture> CMainMenu::createPicture(const JsonNode & config)
  307. {
  308. return std::make_shared<CPicture>(config["name"].String(), config["x"].Float(), config["y"].Float());
  309. }
  310. CMultiMode::CMultiMode(ESelectionScreen ScreenType)
  311. : screenType(ScreenType)
  312. {
  313. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  314. background = std::make_shared<CPicture>("MUPOPUP.bmp");
  315. background->convertToScreenBPP(); //so we could draw without problems
  316. blitAt(CPicture("MUMAP.bmp"), 16, 77, *background);
  317. pos = background->center(); //center, window has size of bg graphic
  318. statusBar = std::make_shared<CGStatusBar>(std::make_shared<CPicture>(Rect(7, 465, 440, 18), 0)); //226, 472
  319. playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), *background);
  320. playerName->setText(settings["general"]["playerName"].String());
  321. playerName->cb += std::bind(&CMultiMode::onNameChange, this, _1);
  322. buttonHotseat = std::make_shared<CButton>(Point(373, 78), "MUBHOT.DEF", CGI->generaltexth->zelp[266], std::bind(&CMultiMode::hostTCP, this));
  323. buttonHost = std::make_shared<CButton>(Point(373, 78 + 57 * 1), "MUBHOST.DEF", CButton::tooltip("Host TCP/IP game", ""), std::bind(&CMultiMode::hostTCP, this));
  324. buttonJoin = std::make_shared<CButton>(Point(373, 78 + 57 * 2), "MUBJOIN.DEF", CButton::tooltip("Join TCP/IP game", ""), std::bind(&CMultiMode::joinTCP, this));
  325. buttonCancel = std::make_shared<CButton>(Point(373, 424), "MUBCANC.DEF", CGI->generaltexth->zelp[288], [&]() { GH.popIntTotally(this);}, SDLK_ESCAPE);
  326. }
  327. void CMultiMode::hostTCP()
  328. {
  329. GH.popIntTotally(this);
  330. GH.pushInt(new CMultiPlayers(settings["general"]["playerName"].String(), screenType, true, ELoadMode::MULTI));
  331. }
  332. void CMultiMode::joinTCP()
  333. {
  334. GH.popIntTotally(this);
  335. GH.pushInt(new CMultiPlayers(settings["general"]["playerName"].String(), screenType, false, ELoadMode::MULTI));
  336. }
  337. void CMultiMode::onNameChange(std::string newText)
  338. {
  339. Settings name = settings.write["general"]["playerName"];
  340. name->String() = newText;
  341. }
  342. CMultiPlayers::CMultiPlayers(const std::string & firstPlayer, ESelectionScreen ScreenType, bool Host, ELoadMode LoadMode)
  343. : loadMode(LoadMode), screenType(ScreenType), host(Host)
  344. {
  345. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  346. background = std::make_shared<CPicture>("MUHOTSEA.bmp");
  347. pos = background->center(); //center, window has size of bg graphic
  348. std::string text = CGI->generaltexth->allTexts[446];
  349. boost::replace_all(text, "\t", "\n");
  350. textTitle = std::make_shared<CTextBox>(text, Rect(25, 20, 315, 50), 0, FONT_BIG, CENTER, Colors::WHITE); //HOTSEAT Please enter names
  351. for(int i = 0; i < inputNames.size(); i++)
  352. {
  353. inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), *background);
  354. inputNames[i]->cb += std::bind(&CMultiPlayers::onChange, this, _1);
  355. }
  356. buttonOk = std::make_shared<CButton>(Point(95, 338), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CMultiPlayers::enterSelectionScreen, this), SDLK_RETURN);
  357. buttonCancel = std::make_shared<CButton>(Point(205, 338), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CGuiHandler::popIntTotally, std::ref(GH), this), SDLK_ESCAPE);
  358. statusBar = std::make_shared<CGStatusBar>(std::make_shared<CPicture>(Rect(7, 381, 348, 18), 0)); //226, 472
  359. inputNames[0]->setText(firstPlayer, true);
  360. inputNames[0]->giveFocus();
  361. }
  362. void CMultiPlayers::onChange(std::string newText)
  363. {
  364. size_t namesCount = 0;
  365. for(auto & elem : inputNames)
  366. if(!elem->text.empty())
  367. namesCount++;
  368. }
  369. void CMultiPlayers::enterSelectionScreen()
  370. {
  371. std::vector<std::string> names;
  372. for(auto name : inputNames)
  373. {
  374. if(name->text.length())
  375. names.push_back(name->text);
  376. }
  377. Settings name = settings.write["general"]["playerName"];
  378. name->String() = names[0];
  379. CMainMenu::openLobby(screenType, host, &names, loadMode);
  380. }
  381. CSimpleJoinScreen::CSimpleJoinScreen(bool host)
  382. {
  383. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  384. background = std::make_shared<CPicture>("MUDIALOG.bmp"); // address background
  385. pos = background->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
  386. textTitle = std::make_shared<CTextBox>("", Rect(20, 20, 205, 50), 0, FONT_BIG, CENTER, Colors::WHITE);
  387. inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), *background.get());
  388. inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), *background.get());
  389. if(host && !settings["session"]["donotstartserver"].Bool())
  390. {
  391. textTitle->setText("Connecting...");
  392. boost::thread(&CSimpleJoinScreen::connectThread, this, "", 0);
  393. }
  394. else
  395. {
  396. textTitle->setText("Enter address:");
  397. inputAddress->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  398. inputPort->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  399. inputPort->filters += std::bind(&CTextInput::numberFilter, _1, _2, 0, 65535);
  400. buttonOk = std::make_shared<CButton>(Point(26, 142), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CSimpleJoinScreen::connectToServer, this), SDLK_RETURN);
  401. inputAddress->giveFocus();
  402. }
  403. inputAddress->setText(settings["server"]["server"].String(), true);
  404. inputPort->setText(CServerHandler::getDefaultPortStr(), true);
  405. buttonCancel = std::make_shared<CButton>(Point(142, 142), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), SDLK_ESCAPE);
  406. statusBar = std::make_shared<CGStatusBar>(std::make_shared<CPicture>(Rect(7, 186, 218, 18), 0));
  407. }
  408. void CSimpleJoinScreen::connectToServer()
  409. {
  410. textTitle->setText("Connecting...");
  411. buttonOk->block(true);
  412. boost::thread(&CSimpleJoinScreen::connectThread, this, inputAddress->text, boost::lexical_cast<ui16>(inputPort->text));
  413. }
  414. void CSimpleJoinScreen::leaveScreen()
  415. {
  416. if(CSH->state == EClientState::CONNECTING)
  417. {
  418. textTitle->setText("Closing...");
  419. CSH->state = EClientState::CONNECTION_CANCELLED;
  420. }
  421. else if(GH.listInt.size() && GH.listInt.front() == this)
  422. {
  423. GH.popIntTotally(this);
  424. }
  425. }
  426. void CSimpleJoinScreen::onChange(const std::string & newText)
  427. {
  428. buttonOk->block(inputAddress->text.empty() || inputPort->text.empty());
  429. }
  430. void CSimpleJoinScreen::connectThread(const std::string addr, const ui16 port)
  431. {
  432. setThreadName("CSimpleJoinScreen::connectThread");
  433. if(!addr.length())
  434. CSH->startLocalServerAndConnect();
  435. else
  436. CSH->justConnectToServer(addr, port);
  437. if(GH.listInt.size() && GH.listInt.front() == this)
  438. {
  439. GH.popIntTotally(this);
  440. }
  441. }
  442. CLoadingScreen::CLoadingScreen(std::function<void()> loader)
  443. : CWindowObject(BORDERED, getBackground()), loadingThread(loader)
  444. {
  445. CCS->musich->stopMusic(5000);
  446. }
  447. CLoadingScreen::~CLoadingScreen()
  448. {
  449. loadingThread.join();
  450. }
  451. void CLoadingScreen::showAll(SDL_Surface * to)
  452. {
  453. Rect rect(0, 0, to->w, to->h);
  454. SDL_FillRect(to, &rect, 0);
  455. CWindowObject::showAll(to);
  456. }
  457. std::string CLoadingScreen::getBackground()
  458. {
  459. const auto & conf = CMainMenuConfig::get().getConfig()["loading"].Vector();
  460. if(conf.empty())
  461. {
  462. return "loadbar";
  463. }
  464. else
  465. {
  466. return RandomGeneratorUtil::nextItem(conf, CRandomGenerator::getDefault())->String();
  467. }
  468. }