ClientCommandManager.cpp 14 KB

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