ClientCommandManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /*
  2. * ClientCommandManager.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 "ClientCommandManager.h"
  12. #include "Client.h"
  13. #include "adventureMap/CInGameConsole.h"
  14. #include "CPlayerInterface.h"
  15. #include "PlayerLocalState.h"
  16. #include "CServerHandler.h"
  17. #include "gui/CGuiHandler.h"
  18. #include "gui/WindowHandler.h"
  19. #include "render/IRenderHandler.h"
  20. #include "ClientNetPackVisitors.h"
  21. #include "../lib/CConfigHandler.h"
  22. #include "../lib/gameState/CGameState.h"
  23. #include "../lib/CPlayerState.h"
  24. #include "../lib/constants/StringConstants.h"
  25. #include "../lib/campaign/CampaignHandler.h"
  26. #include "../lib/mapping/CMapService.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "windows/CCastleInterface.h"
  29. #include "../lib/mapObjects/CGHeroInstance.h"
  30. #include "render/CAnimation.h"
  31. #include "../CCallback.h"
  32. #include "../lib/CGeneralTextHandler.h"
  33. #include "../lib/filesystem/Filesystem.h"
  34. #include "../lib/modding/CModHandler.h"
  35. #include "../lib/modding/ContentTypeHandler.h"
  36. #include "../lib/modding/ModUtility.h"
  37. #include "../lib/CHeroHandler.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/logging/VisualLogger.h"
  40. #include "CMT.h"
  41. #include "../lib/serializer/Connection.h"
  42. #ifdef SCRIPTING_ENABLED
  43. #include "../lib/ScriptHandler.h"
  44. #endif
  45. void ClientCommandManager::handleQuitCommand()
  46. {
  47. exit(EXIT_SUCCESS);
  48. }
  49. void ClientCommandManager::handleSaveCommand(std::istringstream & singleWordBuffer)
  50. {
  51. if(!CSH->client)
  52. {
  53. printCommandMessage("Game is not in playing state");
  54. return;
  55. }
  56. std::string saveFilename;
  57. singleWordBuffer >> saveFilename;
  58. CSH->client->save(saveFilename);
  59. printCommandMessage("Game saved as: " + saveFilename);
  60. }
  61. void ClientCommandManager::handleLoadCommand(std::istringstream& singleWordBuffer)
  62. {
  63. // TODO: this code should end the running game and manage to call startGame instead
  64. //std::string fname;
  65. //singleWordBuffer >> fname;
  66. //CSH->client->loadGame(fname);
  67. }
  68. void ClientCommandManager::handleGoSoloCommand()
  69. {
  70. Settings session = settings.write["session"];
  71. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  72. if(!CSH->client)
  73. {
  74. printCommandMessage("Game is not in playing state");
  75. return;
  76. }
  77. if(session["aiSolo"].Bool())
  78. {
  79. // unlikely it will work but just in case to be consistent
  80. for(auto & color : CSH->getAllClientPlayers(CSH->logicConnection->connectionID))
  81. {
  82. if(color.isValidPlayer() && CSH->client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  83. {
  84. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  85. }
  86. }
  87. }
  88. else
  89. {
  90. PlayerColor currentColor = LOCPLINT->playerID;
  91. CSH->client->removeGUI();
  92. for(auto & color : CSH->getAllClientPlayers(CSH->logicConnection->connectionID))
  93. {
  94. if(color.isValidPlayer() && CSH->client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  95. {
  96. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(color), false, false);
  97. printCommandMessage("Player " + color.toString() + " will be lead by " + AiToGive, ELogLevel::INFO);
  98. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  99. }
  100. }
  101. GH.windows().totalRedraw();
  102. giveTurn(currentColor);
  103. }
  104. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  105. }
  106. void ClientCommandManager::handleAutoskipCommand()
  107. {
  108. Settings session = settings.write["session"];
  109. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  110. }
  111. void ClientCommandManager::handleControlaiCommand(std::istringstream& singleWordBuffer)
  112. {
  113. std::string colorName;
  114. singleWordBuffer >> colorName;
  115. boost::to_lower(colorName);
  116. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  117. if(!CSH->client)
  118. {
  119. printCommandMessage("Game is not in playing state");
  120. return;
  121. }
  122. PlayerColor color;
  123. if(LOCPLINT)
  124. color = LOCPLINT->playerID;
  125. for(auto & elem : CSH->client->gameState()->players)
  126. {
  127. if(!elem.first.isValidPlayer()
  128. || elem.second.human
  129. || (colorName.length() && elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  130. {
  131. continue;
  132. }
  133. CSH->client->removeGUI();
  134. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  135. }
  136. GH.windows().totalRedraw();
  137. if(color != PlayerColor::NEUTRAL)
  138. giveTurn(color);
  139. }
  140. void ClientCommandManager::handleSetBattleAICommand(std::istringstream& singleWordBuffer)
  141. {
  142. std::string aiName;
  143. singleWordBuffer >> aiName;
  144. printCommandMessage("Will try loading that AI to see if it is correct name...\n");
  145. try
  146. {
  147. if(auto ai = CDynLibHandler::getNewBattleAI(aiName)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  148. {
  149. Settings neutralAI = settings.write["server"]["neutralAI"];
  150. neutralAI->String() = aiName;
  151. printCommandMessage("Setting changed, from now the battle ai will be " + aiName + "!\n");
  152. }
  153. }
  154. catch(std::exception &e)
  155. {
  156. printCommandMessage("Failed opening " + aiName + ": " + e.what(), ELogLevel::WARN);
  157. printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN);
  158. }
  159. }
  160. void ClientCommandManager::handleRedrawCommand()
  161. {
  162. GH.windows().totalRedraw();
  163. }
  164. void ClientCommandManager::handleTranslateGameCommand()
  165. {
  166. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  167. VLC->generaltexth->exportAllTexts(textsByMod);
  168. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "translation";
  169. boost::filesystem::create_directories(outPath);
  170. for(const auto & modEntry : textsByMod)
  171. {
  172. JsonNode output;
  173. for(const auto & stringEntry : modEntry.second)
  174. {
  175. if(boost::algorithm::starts_with(stringEntry.first, "map."))
  176. continue;
  177. if(boost::algorithm::starts_with(stringEntry.first, "campaign."))
  178. continue;
  179. output[stringEntry.first].String() = stringEntry.second;
  180. }
  181. if (!output.isNull())
  182. {
  183. const boost::filesystem::path filePath = outPath / (modEntry.first + ".json");
  184. std::ofstream file(filePath.c_str());
  185. file << output.toString();
  186. }
  187. }
  188. printCommandMessage("Translation export complete");
  189. }
  190. void ClientCommandManager::handleTranslateMapsCommand()
  191. {
  192. CMapService mapService;
  193. printCommandMessage("Searching for available maps");
  194. std::unordered_set<ResourcePath> mapList = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  195. {
  196. return ident.getType() == EResType::MAP;
  197. });
  198. std::vector<std::unique_ptr<CMap>> loadedMaps;
  199. std::vector<std::shared_ptr<CampaignState>> loadedCampaigns;
  200. printCommandMessage("Loading maps for export");
  201. for (auto const & mapName : mapList)
  202. {
  203. try
  204. {
  205. // load and drop loaded map - we only need loader to run over all maps
  206. loadedMaps.push_back(mapService.loadMap(mapName, nullptr));
  207. }
  208. catch(std::exception & e)
  209. {
  210. logGlobal->warn("Map %s is invalid. Message: %s", mapName.getName(), e.what());
  211. }
  212. }
  213. printCommandMessage("Searching for available campaigns");
  214. std::unordered_set<ResourcePath> campaignList = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  215. {
  216. return ident.getType() == EResType::CAMPAIGN;
  217. });
  218. logGlobal->info("Loading campaigns for export");
  219. for (auto const & campaignName : campaignList)
  220. {
  221. loadedCampaigns.push_back(CampaignHandler::getCampaign(campaignName.getName()));
  222. for (auto const & part : loadedCampaigns.back()->allScenarios())
  223. loadedCampaigns.back()->getMap(part, nullptr);
  224. }
  225. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  226. VLC->generaltexth->exportAllTexts(textsByMod);
  227. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "translation";
  228. boost::filesystem::create_directories(outPath);
  229. for(const auto & modEntry : textsByMod)
  230. {
  231. JsonNode output;
  232. for(const auto & stringEntry : modEntry.second)
  233. {
  234. if(boost::algorithm::starts_with(stringEntry.first, "map."))
  235. output[stringEntry.first].String() = stringEntry.second;
  236. if(boost::algorithm::starts_with(stringEntry.first, "campaign."))
  237. output[stringEntry.first].String() = stringEntry.second;
  238. }
  239. if (!output.isNull())
  240. {
  241. const boost::filesystem::path filePath = outPath / (modEntry.first + ".json");
  242. std::ofstream file(filePath.c_str());
  243. file << output.toString();
  244. }
  245. }
  246. printCommandMessage("Translation export complete");
  247. }
  248. void ClientCommandManager::handleGetConfigCommand()
  249. {
  250. printCommandMessage("Command accepted.\t");
  251. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "configuration";
  252. boost::filesystem::create_directories(outPath);
  253. const std::vector<std::string> contentNames = { "heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills" };
  254. for(auto contentName : contentNames)
  255. {
  256. auto const & handler = *VLC->modh->content;
  257. auto const & content = handler[contentName];
  258. auto contentOutPath = outPath / contentName;
  259. boost::filesystem::create_directories(contentOutPath);
  260. for(auto& iter : content.modData)
  261. {
  262. const JsonNode& modData = iter.second.modData;
  263. for(auto& nameAndObject : modData.Struct())
  264. {
  265. const JsonNode& object = nameAndObject.second;
  266. std::string name = ModUtility::makeFullIdentifier(object.getModScope(), contentName, nameAndObject.first);
  267. boost::algorithm::replace_all(name, ":", "_");
  268. const boost::filesystem::path filePath = contentOutPath / (name + ".json");
  269. std::ofstream file(filePath.c_str());
  270. file << object.toString();
  271. }
  272. }
  273. }
  274. printCommandMessage("\rExtracting done :)\n");
  275. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  276. }
  277. void ClientCommandManager::handleGetScriptsCommand()
  278. {
  279. #if SCRIPTING_ENABLED
  280. printCommandMessage("Command accepted.\t");
  281. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "scripts";
  282. boost::filesystem::create_directories(outPath);
  283. for(const auto & kv : VLC->scriptHandler->objects)
  284. {
  285. std::string name = kv.first;
  286. boost::algorithm::replace_all(name,":","_");
  287. const scripting::ScriptImpl * script = kv.second.get();
  288. boost::filesystem::path filePath = outPath / (name + ".lua");
  289. std::ofstream file(filePath.c_str());
  290. file << script->getSource();
  291. }
  292. printCommandMessage("\rExtracting done :)\n");
  293. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  294. #endif
  295. }
  296. void ClientCommandManager::handleGetTextCommand()
  297. {
  298. printCommandMessage("Command accepted.\t");
  299. const boost::filesystem::path outPath =
  300. VCMIDirs::get().userExtractedPath();
  301. auto list =
  302. CResourceHandler::get()->getFilteredFiles([](const ResourcePath & ident)
  303. {
  304. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  305. });
  306. for (auto & filename : list)
  307. {
  308. const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT");
  309. boost::filesystem::create_directories(filePath.parent_path());
  310. std::ofstream file(filePath.c_str());
  311. auto text = CResourceHandler::get()->load(filename)->readAll();
  312. file.write((char*)text.first.get(), text.second);
  313. }
  314. printCommandMessage("\rExtracting done :)\n");
  315. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  316. }
  317. void ClientCommandManager::handleDef2bmpCommand(std::istringstream& singleWordBuffer)
  318. {
  319. std::string URI;
  320. singleWordBuffer >> URI;
  321. auto anim = GH.renderHandler().loadAnimation(AnimationPath::builtin(URI), EImageBlitMode::ALPHA);
  322. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  323. }
  324. void ClientCommandManager::handleExtractCommand(std::istringstream& singleWordBuffer)
  325. {
  326. std::string URI;
  327. singleWordBuffer >> URI;
  328. if(CResourceHandler::get()->existsResource(ResourcePath(URI)))
  329. {
  330. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  331. auto data = CResourceHandler::get()->load(ResourcePath(URI))->readAll();
  332. boost::filesystem::create_directories(outPath.parent_path());
  333. std::ofstream outFile(outPath.c_str(), std::ofstream::binary);
  334. outFile.write((char*)data.first.get(), data.second);
  335. }
  336. else
  337. printCommandMessage("File not found!", ELogLevel::ERROR);
  338. }
  339. void ClientCommandManager::handleBonusesCommand(std::istringstream & singleWordBuffer)
  340. {
  341. if(currentCallFromIngameConsole)
  342. {
  343. printCommandMessage("Output for this command is too large for ingame chat! Please run it from client console.\n");
  344. return;
  345. }
  346. std::string outputFormat;
  347. singleWordBuffer >> outputFormat;
  348. auto format = [outputFormat](const BonusList & b) -> std::string
  349. {
  350. if(outputFormat == "json")
  351. return b.toJsonNode().toCompactString();
  352. std::ostringstream ss;
  353. ss << b;
  354. return ss.str();
  355. };
  356. printCommandMessage("Bonuses of " + LOCPLINT->localState->getCurrentArmy()->getObjectName() + "\n");
  357. printCommandMessage(format(*LOCPLINT->localState->getCurrentArmy()->getAllBonuses(Selector::all, Selector::all)) + "\n");
  358. printCommandMessage("\nInherited bonuses:\n");
  359. TCNodes parents;
  360. LOCPLINT->localState->getCurrentArmy()->getParents(parents);
  361. for(const CBonusSystemNode *parent : parents)
  362. {
  363. printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n");
  364. }
  365. }
  366. void ClientCommandManager::handleTellCommand(std::istringstream& singleWordBuffer)
  367. {
  368. std::string what;
  369. int id1;
  370. int id2;
  371. singleWordBuffer >> what >> id1 >> id2;
  372. if(what == "hs")
  373. {
  374. for(const CGHeroInstance* h : LOCPLINT->cb->getHeroesInfo())
  375. if(h->type->getIndex() == id1)
  376. if(const CArtifactInstance* a = h->getArt(ArtifactPosition(id2)))
  377. printCommandMessage(a->nodeName());
  378. }
  379. }
  380. void ClientCommandManager::handleMpCommand()
  381. {
  382. if(const CGHeroInstance* h = LOCPLINT->localState->getCurrentHero())
  383. printCommandMessage(std::to_string(h->movementPointsRemaining()) + "; max: " + std::to_string(h->movementPointsLimit(true)) + "/" + std::to_string(h->movementPointsLimit(false)) + "\n");
  384. }
  385. void ClientCommandManager::handleSetCommand(std::istringstream& singleWordBuffer)
  386. {
  387. std::string what;
  388. std::string value;
  389. singleWordBuffer >> what;
  390. Settings config = settings.write["session"][what];
  391. singleWordBuffer >> value;
  392. if(value == "on")
  393. {
  394. config->Bool() = true;
  395. printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO);
  396. }
  397. else if(value == "off")
  398. {
  399. config->Bool() = false;
  400. printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO);
  401. }
  402. }
  403. void ClientCommandManager::handleCrashCommand()
  404. {
  405. int* ptr = nullptr;
  406. *ptr = 666;
  407. //disaster!
  408. }
  409. void ClientCommandManager::handleVsLog(std::istringstream & singleWordBuffer)
  410. {
  411. std::string key;
  412. singleWordBuffer >> key;
  413. logVisual->setKey(key);
  414. }
  415. void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
  416. {
  417. switch(messageType)
  418. {
  419. case ELogLevel::NOT_SET:
  420. std::cout << commandMessage;
  421. break;
  422. case ELogLevel::TRACE:
  423. logGlobal->trace(commandMessage);
  424. break;
  425. case ELogLevel::DEBUG:
  426. logGlobal->debug(commandMessage);
  427. break;
  428. case ELogLevel::INFO:
  429. logGlobal->info(commandMessage);
  430. break;
  431. case ELogLevel::WARN:
  432. logGlobal->warn(commandMessage);
  433. break;
  434. case ELogLevel::ERROR:
  435. logGlobal->error(commandMessage);
  436. break;
  437. default:
  438. std::cout << commandMessage;
  439. break;
  440. }
  441. if(currentCallFromIngameConsole)
  442. {
  443. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  444. if(LOCPLINT && LOCPLINT->cingconsole)
  445. {
  446. LOCPLINT->cingconsole->addMessage("", "System", commandMessage);
  447. }
  448. }
  449. }
  450. void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier)
  451. {
  452. PlayerStartsTurn yt;
  453. yt.player = colorIdentifier;
  454. yt.queryID = QueryID::NONE;
  455. ApplyClientNetPackVisitor visitor(*CSH->client, *CSH->client->gameState());
  456. yt.visit(visitor);
  457. }
  458. void ClientCommandManager::processCommand(const std::string & message, bool calledFromIngameConsole)
  459. {
  460. // split the message into individual words
  461. std::istringstream singleWordBuffer;
  462. singleWordBuffer.str(message);
  463. // get command name, to be used for single word commands
  464. std::string commandName;
  465. singleWordBuffer >> commandName;
  466. currentCallFromIngameConsole = calledFromIngameConsole;
  467. if(message == std::string("die, fool"))
  468. handleQuitCommand();
  469. else if(commandName == "save")
  470. handleSaveCommand(singleWordBuffer);
  471. else if(commandName=="load")
  472. handleLoadCommand(singleWordBuffer); // not implemented
  473. else if(commandName == "gosolo")
  474. handleGoSoloCommand();
  475. else if(commandName == "autoskip")
  476. handleAutoskipCommand();
  477. else if(commandName == "controlai")
  478. handleControlaiCommand(singleWordBuffer);
  479. else if(commandName == "setBattleAI")
  480. handleSetBattleAICommand(singleWordBuffer);
  481. else if(commandName == "redraw")
  482. handleRedrawCommand();
  483. else if(message=="translate" || message=="translate game")
  484. handleTranslateGameCommand();
  485. else if(message=="translate maps")
  486. handleTranslateMapsCommand();
  487. else if(message=="get config")
  488. handleGetConfigCommand();
  489. else if(message=="get scripts")
  490. handleGetScriptsCommand();
  491. else if(message=="get txt")
  492. handleGetTextCommand();
  493. else if(commandName == "def2bmp")
  494. handleDef2bmpCommand(singleWordBuffer);
  495. else if(commandName == "extract")
  496. handleExtractCommand(singleWordBuffer);
  497. else if(commandName == "bonuses")
  498. handleBonusesCommand(singleWordBuffer);
  499. else if(commandName == "tell")
  500. handleTellCommand(singleWordBuffer);
  501. else if(commandName == "mp" && LOCPLINT)
  502. handleMpCommand();
  503. else if (commandName == "set")
  504. handleSetCommand(singleWordBuffer);
  505. else if(commandName == "crash")
  506. handleCrashCommand();
  507. else if(commandName == "vslog")
  508. handleVsLog(singleWordBuffer);
  509. else
  510. {
  511. if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise
  512. printCommandMessage("Command not found :(", ELogLevel::ERROR);
  513. }
  514. }