ClientCommandManager.cpp 14 KB

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