2
0

ClientCommandManager.cpp 15 KB

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