ClientCommandManager.cpp 15 KB

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