ClientCommandManager.cpp 14 KB

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