ClientCommandManager.cpp 17 KB

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