2
0

ClientCommandManager.cpp 18 KB

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