CMainMenu.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 "CHighScoreScreen.h"
  15. #include "../lobby/CBonusSelection.h"
  16. #include "../lobby/CSelectionBase.h"
  17. #include "../lobby/CLobbyScreen.h"
  18. #include "../media/IMusicPlayer.h"
  19. #include "../media/IVideoPlayer.h"
  20. #include "../gui/CursorHandler.h"
  21. #include "../windows/GUIClasses.h"
  22. #include "../gui/CGuiHandler.h"
  23. #include "../gui/ShortcutHandler.h"
  24. #include "../gui/Shortcut.h"
  25. #include "../gui/WindowHandler.h"
  26. #include "../render/Canvas.h"
  27. #include "../globalLobby/GlobalLobbyLoginWindow.h"
  28. #include "../globalLobby/GlobalLobbyClient.h"
  29. #include "../globalLobby/GlobalLobbyWindow.h"
  30. #include "../widgets/CComponent.h"
  31. #include "../widgets/Buttons.h"
  32. #include "../widgets/CTextInput.h"
  33. #include "../widgets/MiscWidgets.h"
  34. #include "../widgets/ObjectLists.h"
  35. #include "../widgets/TextControls.h"
  36. #include "../widgets/VideoWidget.h"
  37. #include "../windows/InfoWindows.h"
  38. #include "../CServerHandler.h"
  39. #include "../CGameInfo.h"
  40. #include "../CPlayerInterface.h"
  41. #include "../Client.h"
  42. #include "../CMT.h"
  43. #include "../../CCallback.h"
  44. #include "../../lib/texts/CGeneralTextHandler.h"
  45. #include "../../lib/campaign/CampaignHandler.h"
  46. #include "../../lib/filesystem/Filesystem.h"
  47. #include "../../lib/filesystem/CCompressedStream.h"
  48. #include "../../lib/mapping/CMapInfo.h"
  49. #include "../../lib/modding/CModHandler.h"
  50. #include "../../lib/VCMIDirs.h"
  51. #include "../../lib/CStopWatch.h"
  52. #include "../../lib/CThreadHelper.h"
  53. #include "../../lib/CConfigHandler.h"
  54. #include "../../lib/GameConstants.h"
  55. #include "../../lib/CRandomGenerator.h"
  56. std::shared_ptr<CMainMenu> CMM;
  57. ISelectionScreenInfo * SEL = nullptr;
  58. static void do_quit()
  59. {
  60. GH.dispatchMainThread([]()
  61. {
  62. handleQuit(false);
  63. });
  64. }
  65. CMenuScreen::CMenuScreen(const JsonNode & configNode)
  66. : CWindowObject(BORDERED), config(configNode)
  67. {
  68. OBJECT_CONSTRUCTION;
  69. const auto& bgConfig = config["background"];
  70. if (bgConfig.isVector() && !bgConfig.Vector().empty())
  71. background = std::make_shared<CPicture>(ImagePath::fromJson(*RandomGeneratorUtil::nextItem(bgConfig.Vector(), CRandomGenerator::getDefault())));
  72. if (bgConfig.isString())
  73. background = std::make_shared<CPicture>(ImagePath::fromJson(bgConfig));
  74. if(config["scalable"].Bool())
  75. background->scaleTo(GH.screenDimensions());
  76. pos = background->center();
  77. if(!config["video"].isNull())
  78. {
  79. Point videoPosition(config["video"]["x"].Integer(), config["video"]["y"].Integer());
  80. videoPlayer = std::make_shared<VideoWidget>(videoPosition, VideoPath::fromJson(config["video"]["name"]), false);
  81. }
  82. for(const JsonNode & node : config["items"].Vector())
  83. menuNameToEntry.push_back(node["name"].String());
  84. for(const JsonNode & node : config["images"].Vector())
  85. images.push_back(CMainMenu::createPicture(node));
  86. //Hardcoded entry
  87. menuNameToEntry.push_back("credits");
  88. tabs = std::make_shared<CTabbedInt>(std::bind(&CMenuScreen::createTab, this, _1));
  89. if(config["video"].isNull())
  90. tabs->setRedrawParent(true);
  91. }
  92. std::shared_ptr<CIntObject> CMenuScreen::createTab(size_t index)
  93. {
  94. if(config["items"].Vector().size() == index)
  95. return std::make_shared<CreditsScreen>(this->pos);
  96. else
  97. return std::make_shared<CMenuEntry>(this, config["items"].Vector()[index]);
  98. }
  99. void CMenuScreen::show(Canvas & to)
  100. {
  101. // TODO: avoid excessive redraws
  102. CIntObject::showAll(to);
  103. }
  104. void CMenuScreen::activate()
  105. {
  106. CIntObject::activate();
  107. }
  108. void CMenuScreen::switchToTab(size_t index)
  109. {
  110. tabs->setActive(index);
  111. }
  112. void CMenuScreen::switchToTab(std::string name)
  113. {
  114. switchToTab(vstd::find_pos(menuNameToEntry, name));
  115. }
  116. size_t CMenuScreen::getActiveTab() const
  117. {
  118. return tabs->getActive();
  119. }
  120. //function for std::string -> std::function conversion for main menu
  121. static std::function<void()> genCommand(CMenuScreen * menu, std::vector<std::string> menuType, const std::string & string)
  122. {
  123. static const std::vector<std::string> commandType = {"to", "campaigns", "start", "load", "exit", "highscores"};
  124. static const std::vector<std::string> gameType = {"single", "multi", "campaign", "tutorial"};
  125. std::list<std::string> commands;
  126. boost::split(commands, string, boost::is_any_of("\t "));
  127. if(!commands.empty())
  128. {
  129. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  130. commands.pop_front();
  131. if(index > 3 || !commands.empty())
  132. {
  133. switch(index)
  134. {
  135. case 0: //to - switch to another tab, if such tab exists
  136. {
  137. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  138. if(index2 != menuType.size())
  139. return std::bind((void(CMenuScreen::*)(size_t))&CMenuScreen::switchToTab, menu, index2);
  140. break;
  141. }
  142. case 1: //open campaign selection window
  143. {
  144. return std::bind(&CMainMenu::openCampaignScreen, CMM, commands.front());
  145. break;
  146. }
  147. case 2: //start
  148. {
  149. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  150. {
  151. case 0:
  152. return []() { CMainMenu::openLobby(ESelectionScreen::newGame, true, {}, ELoadMode::NONE); };
  153. case 1:
  154. return []() { GH.windows().createAndPushWindow<CMultiMode>(ESelectionScreen::newGame); };
  155. case 2:
  156. return []() { CMainMenu::openLobby(ESelectionScreen::campaignList, true, {}, ELoadMode::NONE); };
  157. case 3:
  158. return []() { CMainMenu::startTutorial(); };
  159. }
  160. break;
  161. }
  162. case 3: //load
  163. {
  164. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  165. {
  166. case 0:
  167. return []() { CMainMenu::openLobby(ESelectionScreen::loadGame, true, {}, ELoadMode::SINGLE); };
  168. case 1:
  169. return []() { GH.windows().createAndPushWindow<CMultiMode>(ESelectionScreen::loadGame); };
  170. case 2:
  171. return []() { CMainMenu::openLobby(ESelectionScreen::loadGame, true, {}, ELoadMode::CAMPAIGN); };
  172. case 3:
  173. return []() { CMainMenu::openLobby(ESelectionScreen::loadGame, true, {}, ELoadMode::TUTORIAL); };
  174. }
  175. }
  176. break;
  177. case 4: //exit
  178. {
  179. return []() { CInfoWindow::showYesNoDialog(CGI->generaltexth->allTexts[69], std::vector<std::shared_ptr<CComponent>>(), do_quit, 0, PlayerColor(1)); };
  180. }
  181. break;
  182. case 5: //highscores
  183. {
  184. return []() { CMainMenu::openHighScoreScreen(); };
  185. }
  186. }
  187. }
  188. }
  189. logGlobal->error("Failed to parse command: %s", string);
  190. return std::function<void()>();
  191. }
  192. std::shared_ptr<CButton> CMenuEntry::createButton(CMenuScreen * parent, const JsonNode & button)
  193. {
  194. std::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  195. std::pair<std::string, std::string> help;
  196. if(!button["help"].isNull() && button["help"].Float() > 0)
  197. help = CGI->generaltexth->zelp[(size_t)button["help"].Float()];
  198. int posx = static_cast<int>(button["x"].Float());
  199. if(posx < 0)
  200. posx = pos.w + posx;
  201. int posy = static_cast<int>(button["y"].Float());
  202. if(posy < 0)
  203. posy = pos.h + posy;
  204. EShortcut shortcut = GH.shortcuts().findShortcut(button["shortcut"].String());
  205. if (shortcut == EShortcut::NONE && !button["shortcut"].String().empty())
  206. {
  207. logGlobal->warn("Unknown shortcut '%s' found when loading main menu config!", button["shortcut"].String());
  208. }
  209. auto result = std::make_shared<CButton>(Point(posx, posy), AnimationPath::fromJson(button["name"]), help, command, shortcut);
  210. if (button["center"].Bool())
  211. result->moveBy(Point(-result->pos.w/2, -result->pos.h/2));
  212. return result;
  213. }
  214. CMenuEntry::CMenuEntry(CMenuScreen * parent, const JsonNode & config)
  215. {
  216. OBJECT_CONSTRUCTION;
  217. setRedrawParent(true);
  218. pos = parent->pos;
  219. for(const JsonNode & node : config["images"].Vector())
  220. images.push_back(CMainMenu::createPicture(node));
  221. for (const JsonNode& node : config["buttons"].Vector()) {
  222. auto tokens = node["command"].String().find(' ');
  223. std::pair<std::string, std::string> commandParts = {
  224. node["command"].String().substr(0, tokens),
  225. (tokens == std::string::npos) ? "" : node["command"].String().substr(tokens + 1)
  226. };
  227. if (commandParts.first == "campaigns") {
  228. const auto& campaign = CMainMenuConfig::get().getCampaigns()[commandParts.second];
  229. if (!campaign.isStruct()) {
  230. logGlobal->warn("Campaign set %s not found", commandParts.second);
  231. continue;
  232. }
  233. bool fileExists = false;
  234. for (const auto& item : campaign["items"].Vector()) {
  235. std::string filename = item["file"].String();
  236. if (CResourceHandler::get()->existsResource(ResourcePath(filename, EResType::CAMPAIGN))) {
  237. fileExists = true;
  238. break;
  239. }
  240. }
  241. if (!fileExists) {
  242. logGlobal->warn("No valid files found for campaign set %s", commandParts.second);
  243. continue;
  244. }
  245. }
  246. buttons.push_back(createButton(parent, node));
  247. buttons.back()->setHoverable(true);
  248. buttons.back()->setRedrawParent(true);
  249. }
  250. }
  251. CMainMenuConfig::CMainMenuConfig()
  252. : campaignSets(JsonPath::builtin("config/campaignSets.json"))
  253. , config(JsonPath::builtin("config/mainmenu.json"))
  254. {
  255. if (config["game-select"].Vector().empty())
  256. handleFatalError("Main menu config is invalid or corrupted. Please disable any mods or reinstall VCMI", false);
  257. }
  258. const CMainMenuConfig & CMainMenuConfig::get()
  259. {
  260. static const CMainMenuConfig config;
  261. return config;
  262. }
  263. const JsonNode & CMainMenuConfig::getConfig() const
  264. {
  265. return config;
  266. }
  267. const JsonNode & CMainMenuConfig::getCampaigns() const
  268. {
  269. return campaignSets;
  270. }
  271. CMainMenu::CMainMenu()
  272. {
  273. pos.w = GH.screenDimensions().x;
  274. pos.h = GH.screenDimensions().y;
  275. menu = std::make_shared<CMenuScreen>(CMainMenuConfig::get().getConfig()["window"]);
  276. OBJECT_CONSTRUCTION;
  277. backgroundAroundMenu = std::make_shared<CFilledTexture>(ImagePath::builtin("DIBOXBCK"), pos);
  278. }
  279. CMainMenu::~CMainMenu()
  280. {
  281. if(GH.curInt == this)
  282. GH.curInt = nullptr;
  283. }
  284. void CMainMenu::playIntroVideos()
  285. {
  286. auto playVideo = [](std::string video, bool rim, float scaleFactor, std::function<void(bool)> cb){
  287. if(CCS->videoh->open(VideoPath::builtin(video), scaleFactor))
  288. GH.windows().createAndPushWindow<VideoWindow>(VideoPath::builtin(video), rim ? ImagePath::builtin("INTRORIM") : ImagePath::builtin(""), true, scaleFactor, [cb](bool skipped){ cb(skipped); });
  289. else
  290. cb(true);
  291. };
  292. playVideo("3DOLOGO.SMK", false, 1.25, [playVideo, this](bool skipped){
  293. if(!skipped)
  294. playVideo("NWCLOGO.SMK", false, 2, [playVideo, this](bool skipped){
  295. if(!skipped)
  296. playVideo("H3INTRO.SMK", true, 1, [this](bool skipped){
  297. playMusic();
  298. });
  299. else
  300. playMusic();
  301. });
  302. else
  303. playMusic();
  304. });
  305. }
  306. void CMainMenu::playMusic()
  307. {
  308. CCS->musich->playMusic(AudioPath::builtin("Music/MainMenu"), true, true);
  309. }
  310. void CMainMenu::activate()
  311. {
  312. // check if screen was resized while main menu was inactive - e.g. in gameplay mode
  313. if (pos.dimensions() != GH.screenDimensions())
  314. onScreenResize();
  315. CIntObject::activate();
  316. }
  317. void CMainMenu::onScreenResize()
  318. {
  319. pos.w = GH.screenDimensions().x;
  320. pos.h = GH.screenDimensions().y;
  321. menu = nullptr;
  322. menu = std::make_shared<CMenuScreen>(CMainMenuConfig::get().getConfig()["window"]);
  323. backgroundAroundMenu->pos = pos;
  324. }
  325. void CMainMenu::update()
  326. {
  327. if(CMM != this->shared_from_this()) //don't update if you are not a main interface
  328. return;
  329. if(GH.windows().count() == 0)
  330. {
  331. GH.windows().pushWindow(CMM);
  332. GH.windows().pushWindow(menu);
  333. menu->switchToTab(menu->getActiveTab());
  334. }
  335. // Handles mouse and key input
  336. GH.handleEvents();
  337. GH.windows().simpleRedraw();
  338. }
  339. void CMainMenu::openLobby(ESelectionScreen screenType, bool host, const std::vector<std::string> & names, ELoadMode loadMode)
  340. {
  341. CSH->resetStateForLobby(screenType == ESelectionScreen::newGame ? EStartMode::NEW_GAME : EStartMode::LOAD_GAME, screenType, EServerMode::LOCAL, names);
  342. CSH->loadMode = loadMode;
  343. GH.windows().createAndPushWindow<CSimpleJoinScreen>(host);
  344. }
  345. void CMainMenu::openCampaignLobby(const std::string & campaignFileName, std::string campaignSet)
  346. {
  347. auto ourCampaign = CampaignHandler::getCampaign(campaignFileName);
  348. ourCampaign->campaignSet = campaignSet;
  349. openCampaignLobby(ourCampaign);
  350. }
  351. void CMainMenu::openCampaignLobby(std::shared_ptr<CampaignState> campaign)
  352. {
  353. CSH->resetStateForLobby(EStartMode::CAMPAIGN, ESelectionScreen::campaignList, EServerMode::LOCAL, {});
  354. CSH->campaignStateToSend = campaign;
  355. GH.windows().createAndPushWindow<CSimpleJoinScreen>();
  356. }
  357. void CMainMenu::openCampaignScreen(std::string name)
  358. {
  359. auto const & config = CMainMenuConfig::get().getCampaigns();
  360. if(!vstd::contains(config.Struct(), name))
  361. {
  362. logGlobal->error("Unknown campaign set: %s", name);
  363. return;
  364. }
  365. bool campaignsFound = true;
  366. for (auto const & entry : config[name]["items"].Vector())
  367. {
  368. ResourcePath resourceID(entry["file"].String(), EResType::CAMPAIGN);
  369. if(entry["optional"].Bool())
  370. continue;
  371. if(!CResourceHandler::get()->existsResource(resourceID))
  372. campaignsFound = false;
  373. }
  374. if (!campaignsFound)
  375. {
  376. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.client.errors.missingCampaigns"), std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  377. return;
  378. }
  379. GH.windows().createAndPushWindow<CCampaignScreen>(config, name);
  380. }
  381. void CMainMenu::startTutorial()
  382. {
  383. ResourcePath tutorialMap("Maps/Tutorial.tut", EResType::MAP);
  384. if(!CResourceHandler::get()->existsResource(tutorialMap))
  385. {
  386. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("core.genrltxt.742"), std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  387. return;
  388. }
  389. auto mapInfo = std::make_shared<CMapInfo>();
  390. mapInfo->mapInit(tutorialMap.getName());
  391. CMainMenu::openLobby(ESelectionScreen::newGame, true, {}, ELoadMode::NONE);
  392. CSH->startMapAfterConnection(mapInfo);
  393. }
  394. void CMainMenu::openHighScoreScreen()
  395. {
  396. GH.windows().createAndPushWindow<CHighScoreScreen>(CHighScoreScreen::HighScorePage::SCENARIO);
  397. return;
  398. }
  399. std::shared_ptr<CMainMenu> CMainMenu::create()
  400. {
  401. if(!CMM)
  402. CMM = std::shared_ptr<CMainMenu>(new CMainMenu());
  403. return CMM;
  404. }
  405. std::shared_ptr<CPicture> CMainMenu::createPicture(const JsonNode & config)
  406. {
  407. return std::make_shared<CPicture>(ImagePath::fromJson(config["name"]), (int)config["x"].Float(), (int)config["y"].Float());
  408. }
  409. CMultiMode::CMultiMode(ESelectionScreen ScreenType)
  410. : screenType(ScreenType)
  411. {
  412. OBJECT_CONSTRUCTION;
  413. background = std::make_shared<CPicture>(ImagePath::builtin("MUPOPUP.bmp"));
  414. pos = background->center(); //center, window has size of bg graphic
  415. const auto& multiplayerConfig = CMainMenuConfig::get().getConfig()["multiplayer"];
  416. if (multiplayerConfig.isVector() && !multiplayerConfig.Vector().empty())
  417. picture = std::make_shared<CPicture>(ImagePath::fromJson(*RandomGeneratorUtil::nextItem(multiplayerConfig.Vector(), CRandomGenerator::getDefault())), 16, 77);
  418. if (multiplayerConfig.isString())
  419. picture = std::make_shared<CPicture>(ImagePath::fromJson(multiplayerConfig), 16, 77);
  420. if (!picture)
  421. {
  422. picture = std::make_shared<CPicture>(ImagePath::builtin("MUMAP.bmp"), 16, 77);
  423. logGlobal->error("Failed to load multiplayer picture");
  424. }
  425. textTitle = std::make_shared<CTextBox>("", Rect(7, 18, 440, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
  426. textTitle->setText(CGI->generaltexth->zelp[263].second);
  427. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 465, 440, 18), 7, 465));
  428. playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), background->getSurface());
  429. playerName->setText(getPlayersNames()[0]);
  430. playerName->setCallback(std::bind(&CMultiMode::onNameChange, this, _1));
  431. buttonHotseat = std::make_shared<CButton>(Point(373, 78 + 57 * 0), AnimationPath::builtin("MUBHOT.DEF"), CGI->generaltexth->zelp[266], std::bind(&CMultiMode::hostTCP, this, EShortcut::MAIN_MENU_HOTSEAT), EShortcut::MAIN_MENU_HOTSEAT);
  432. buttonLobby = std::make_shared<CButton>(Point(373, 78 + 57 * 1), AnimationPath::builtin("MUBONL.DEF"), CGI->generaltexth->zelp[265], std::bind(&CMultiMode::openLobby, this), EShortcut::MAIN_MENU_LOBBY);
  433. buttonHost = std::make_shared<CButton>(Point(373, 78 + 57 * 3), AnimationPath::builtin("MUBHOST.DEF"), CButton::tooltip(CGI->generaltexth->translate("vcmi.mainMenu.hostTCP"), ""), std::bind(&CMultiMode::hostTCP, this, EShortcut::MAIN_MENU_HOST_GAME), EShortcut::MAIN_MENU_HOST_GAME);
  434. buttonJoin = std::make_shared<CButton>(Point(373, 78 + 57 * 4), AnimationPath::builtin("MUBJOIN.DEF"), CButton::tooltip(CGI->generaltexth->translate("vcmi.mainMenu.joinTCP"), ""), std::bind(&CMultiMode::joinTCP, this, EShortcut::MAIN_MENU_JOIN_GAME), EShortcut::MAIN_MENU_JOIN_GAME);
  435. buttonCancel = std::make_shared<CButton>(Point(373, 424), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[288], [=](){ close();}, EShortcut::GLOBAL_CANCEL);
  436. }
  437. void CMultiMode::openLobby()
  438. {
  439. close();
  440. CSH->getGlobalLobby().activateInterface();
  441. }
  442. void CMultiMode::hostTCP(EShortcut shortcut)
  443. {
  444. auto savedScreenType = screenType;
  445. close();
  446. GH.windows().createAndPushWindow<CMultiPlayers>(getPlayersNames(), savedScreenType, true, ELoadMode::MULTI, shortcut);
  447. }
  448. void CMultiMode::joinTCP(EShortcut shortcut)
  449. {
  450. auto savedScreenType = screenType;
  451. close();
  452. GH.windows().createAndPushWindow<CMultiPlayers>(getPlayersNames(), savedScreenType, false, ELoadMode::MULTI, shortcut);
  453. }
  454. std::vector<std::string> CMultiMode::getPlayersNames()
  455. {
  456. std::vector<std::string> playerNames;
  457. std::string playerNameStr = settings["general"]["playerName"].String();
  458. if (playerNameStr == "Player")
  459. playerNameStr = CGI->generaltexth->translate("core.genrltxt.434");
  460. playerNames.push_back(playerNameStr);
  461. for (const auto & playerName : settings["general"]["multiPlayerNames"].Vector())
  462. {
  463. const std::string &nameStr = playerName.String();
  464. if (!nameStr.empty())
  465. {
  466. playerNames.push_back(nameStr);
  467. }
  468. }
  469. return playerNames;
  470. }
  471. void CMultiMode::onNameChange(std::string newText)
  472. {
  473. Settings name = settings.write["general"]["playerName"];
  474. name->String() = newText;
  475. }
  476. CMultiPlayers::CMultiPlayers(const std::vector<std::string>& playerNames, ESelectionScreen ScreenType, bool Host, ELoadMode LoadMode, EShortcut shortcut)
  477. : loadMode(LoadMode), screenType(ScreenType), host(Host)
  478. {
  479. OBJECT_CONSTRUCTION;
  480. background = std::make_shared<CPicture>(ImagePath::builtin("MUHOTSEA.bmp"));
  481. pos = background->center(); //center, window has size of bg graphic
  482. std::string text;
  483. switch (shortcut)
  484. {
  485. case EShortcut::MAIN_MENU_HOTSEAT:
  486. text = CGI->generaltexth->allTexts[446];
  487. boost::replace_all(text, "\t", "\n");
  488. break;
  489. case EShortcut::MAIN_MENU_HOST_GAME:
  490. text = CGI->generaltexth->translate("vcmi.mainMenu.hostTCP");
  491. break;
  492. case EShortcut::MAIN_MENU_JOIN_GAME:
  493. text = CGI->generaltexth->translate("vcmi.mainMenu.joinTCP");
  494. break;
  495. }
  496. textTitle = std::make_shared<CTextBox>(text, Rect(25, 10, 315, 60), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
  497. for(int i = 0; i < inputNames.size(); i++)
  498. {
  499. inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), background->getSurface());
  500. inputNames[i]->setCallback(std::bind(&CMultiPlayers::onChange, this, _1));
  501. }
  502. buttonOk = std::make_shared<CButton>(Point(95, 338), AnimationPath::builtin("MUBCHCK.DEF"), CGI->generaltexth->zelp[560], std::bind(&CMultiPlayers::enterSelectionScreen, this), EShortcut::GLOBAL_ACCEPT);
  503. buttonCancel = std::make_shared<CButton>(Point(205, 338), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[561], [=](){ close();}, EShortcut::GLOBAL_CANCEL);
  504. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 381, 348, 18), 7, 381));
  505. for(int i = 0; i < playerNames.size(); i++)
  506. {
  507. inputNames[i]->setText(playerNames[i]);
  508. }
  509. #ifndef VCMI_MOBILE
  510. inputNames[0]->giveFocus();
  511. #endif
  512. }
  513. void CMultiPlayers::onChange(std::string newText)
  514. {
  515. }
  516. void CMultiPlayers::enterSelectionScreen()
  517. {
  518. std::vector<std::string> playerNames;
  519. for(auto playerName : inputNames)
  520. {
  521. if (playerName->getText().length())
  522. playerNames.push_back(playerName->getText());
  523. }
  524. Settings playerName = settings.write["general"]["playerName"];
  525. Settings multiPlayerNames = settings.write["general"]["multiPlayerNames"];
  526. multiPlayerNames->Vector().clear();
  527. if (!playerNames.empty())
  528. {
  529. playerName->String() = playerNames.front();
  530. for (auto playerNameIt = playerNames.begin()+1; playerNameIt != playerNames.end(); playerNameIt++)
  531. {
  532. multiPlayerNames->Vector().push_back(JsonNode(*playerNameIt));
  533. }
  534. }
  535. else
  536. {
  537. // Without the check the saving crashes directly.
  538. // When empty reset the player's name. This would translate to it being
  539. // the default for the next run. But enables deleting players, by just
  540. // deleting the names, otherwise some UI element should have been added.
  541. playerName->clear();
  542. }
  543. CMainMenu::openLobby(screenType, host, playerNames, loadMode);
  544. }
  545. CSimpleJoinScreen::CSimpleJoinScreen(bool host)
  546. {
  547. OBJECT_CONSTRUCTION;
  548. background = std::make_shared<CPicture>(ImagePath::builtin("MUDIALOG.bmp")); // address background
  549. pos = background->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
  550. textTitle = std::make_shared<CTextBox>("", Rect(20, 10, 205, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
  551. inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), background->getSurface());
  552. inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), background->getSurface());
  553. buttonOk = std::make_shared<CButton>(Point(26, 142), AnimationPath::builtin("MUBCHCK.DEF"), CGI->generaltexth->zelp[560], std::bind(&CSimpleJoinScreen::connectToServer, this), EShortcut::GLOBAL_ACCEPT);
  554. if(host && !settings["session"]["donotstartserver"].Bool())
  555. {
  556. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverConnecting"));
  557. buttonOk->block(true);
  558. startConnection();
  559. }
  560. else
  561. {
  562. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverAddressEnter"));
  563. inputAddress->setCallback(std::bind(&CSimpleJoinScreen::onChange, this, _1));
  564. inputPort->setCallback(std::bind(&CSimpleJoinScreen::onChange, this, _1));
  565. inputPort->setFilterNumber(0, 65535);
  566. inputAddress->giveFocus();
  567. }
  568. inputAddress->setText(host ? CSH->getLocalHostname() : CSH->getRemoteHostname());
  569. inputPort->setText(std::to_string(host ? CSH->getLocalPort() : CSH->getRemotePort()));
  570. buttonOk->block(inputAddress->getText().empty() || inputPort->getText().empty());
  571. buttonCancel = std::make_shared<CButton>(Point(142, 142), AnimationPath::builtin("MUBCANC.DEF"), CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), EShortcut::GLOBAL_CANCEL);
  572. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
  573. }
  574. void CSimpleJoinScreen::connectToServer()
  575. {
  576. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverConnecting"));
  577. buttonOk->block(true);
  578. GH.stopTextInput();
  579. startConnection(inputAddress->getText(), boost::lexical_cast<ui16>(inputPort->getText()));
  580. }
  581. void CSimpleJoinScreen::leaveScreen()
  582. {
  583. textTitle->setText(CGI->generaltexth->translate("vcmi.mainMenu.serverClosing"));
  584. CSH->setState(EClientState::CONNECTION_CANCELLED);
  585. }
  586. void CSimpleJoinScreen::onChange(const std::string & newText)
  587. {
  588. buttonOk->block(inputAddress->getText().empty() || inputPort->getText().empty());
  589. }
  590. void CSimpleJoinScreen::startConnection(const std::string & addr, ui16 port)
  591. {
  592. if(addr.empty())
  593. CSH->startLocalServerAndConnect(false);
  594. else
  595. CSH->connectToServer(addr, port);
  596. }
  597. CLoadingScreen::CLoadingScreen()
  598. : CLoadingScreen(getBackground())
  599. {
  600. }
  601. CLoadingScreen::CLoadingScreen(ImagePath background)
  602. : CWindowObject(BORDERED, background)
  603. {
  604. OBJECT_CONSTRUCTION;
  605. addUsedEvents(TIME);
  606. CCS->musich->stopMusic(5000);
  607. const auto& conf = CMainMenuConfig::get().getConfig()["loading"];
  608. const auto& nameConfig = conf["name"];
  609. AnimationPath animationPath;
  610. if (nameConfig.isVector() && !nameConfig.Vector().empty())
  611. animationPath = AnimationPath::fromJson(*RandomGeneratorUtil::nextItem(nameConfig.Vector(), CRandomGenerator::getDefault()));
  612. if (nameConfig.isString())
  613. animationPath = AnimationPath::fromJson(nameConfig);
  614. if (conf.isStruct())
  615. {
  616. const int posx = conf["x"].Integer();
  617. const int posy = conf["y"].Integer();
  618. const int blockSize = conf["size"].Integer();
  619. const int blocksAmount = conf["amount"].Integer();
  620. for (int i = 0; i < blocksAmount; ++i)
  621. {
  622. progressBlocks.push_back(std::make_shared<CAnimImage>(animationPath, i, 0, posx + i * blockSize, posy));
  623. progressBlocks.back()->deactivate();
  624. progressBlocks.back()->visible = false;
  625. }
  626. }
  627. }
  628. CLoadingScreen::~CLoadingScreen()
  629. {
  630. }
  631. void CLoadingScreen::tick(uint32_t msPassed)
  632. {
  633. if(!progressBlocks.empty())
  634. {
  635. int status = float(get()) / 255.f * progressBlocks.size();
  636. for(int i = 0; i < status; ++i)
  637. {
  638. progressBlocks.at(i)->activate();
  639. progressBlocks.at(i)->visible = true;
  640. }
  641. }
  642. }
  643. ImagePath CLoadingScreen::getBackground()
  644. {
  645. ImagePath fname = ImagePath::builtin("loadbar");
  646. const auto & conf = CMainMenuConfig::get().getConfig()["loading"];
  647. if(conf.isStruct())
  648. {
  649. if(conf["background"].isVector())
  650. return ImagePath::fromJson(*RandomGeneratorUtil::nextItem(conf["background"].Vector(), CRandomGenerator::getDefault()));
  651. if(conf["background"].isString())
  652. return ImagePath::fromJson(conf["background"]);
  653. return fname;
  654. }
  655. if(conf.isVector() && !conf.Vector().empty())
  656. return ImagePath::fromJson(*RandomGeneratorUtil::nextItem(conf.Vector(), CRandomGenerator::getDefault()));
  657. return fname;
  658. }