PlayerMessageProcessor.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. /*
  2. * CGameHandler.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 "PlayerMessageProcessor.h"
  12. #include "TurnOrderProcessor.h"
  13. #include "../CGameHandler.h"
  14. #include "../CVCMIServer.h"
  15. #include "../TurnTimerHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/CPlayerState.h"
  18. #include "../../lib/StartInfo.h"
  19. #include "../../lib/entities/building/CBuilding.h"
  20. #include "../../lib/gameState/CGameState.h"
  21. #include "../../lib/mapObjects/CGTownInstance.h"
  22. #include "../../lib/mapObjects/CGHeroInstance.h"
  23. #include "../../lib/modding/IdentifierStorage.h"
  24. #include "../../lib/modding/ModScope.h"
  25. #include "../../lib/mapping/CMap.h"
  26. #include "../../lib/networkPacks/PacksForClient.h"
  27. #include "../../lib/networkPacks/StackLocation.h"
  28. #include "../../lib/serializer/Connection.h"
  29. #include "../lib/VCMIDirs.h"
  30. PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
  31. :gameHandler(gameHandler)
  32. {
  33. }
  34. void PlayerMessageProcessor::playerMessage(PlayerColor player, const std::string & message, ObjectInstanceID currObj)
  35. {
  36. if(!message.empty() && message[0] == '!')
  37. {
  38. broadcastMessage(player, message);
  39. handleCommand(player, message);
  40. return;
  41. }
  42. if(handleCheatCode(message, player, currObj))
  43. {
  44. if(!gameHandler->getPlayerSettings(player)->isControlledByAI())
  45. {
  46. MetaString txt;
  47. txt.appendLocalString(EMetaText::GENERAL_TXT, 260);
  48. broadcastSystemMessage(txt);
  49. }
  50. if(!player.isSpectator())
  51. gameHandler->checkVictoryLossConditionsForPlayer(player); //Player enter win code or got required art\creature
  52. return;
  53. }
  54. broadcastMessage(player, message);
  55. }
  56. void PlayerMessageProcessor::commandExit(PlayerColor player, const std::vector<std::string> & words)
  57. {
  58. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  59. if(!isHost)
  60. return;
  61. broadcastSystemMessage("game was terminated");
  62. gameHandler->gameLobby()->setState(EServerState::SHUTDOWN);
  63. }
  64. void PlayerMessageProcessor::commandKick(PlayerColor player, const std::vector<std::string> & words)
  65. {
  66. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  67. if(!isHost)
  68. return;
  69. if(words.size() == 2)
  70. {
  71. auto playername = words[1];
  72. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  73. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  74. playerToKick = PlayerColor(std::stoi(playername));
  75. else
  76. {
  77. for(auto & c : gameHandler->connections)
  78. {
  79. if(c.first.toString() == playername)
  80. playerToKick = c.first;
  81. }
  82. }
  83. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  84. {
  85. PlayerCheated pc;
  86. pc.player = playerToKick;
  87. pc.losingCheatCode = true;
  88. gameHandler->sendAndApply(&pc);
  89. gameHandler->checkVictoryLossConditionsForPlayer(playerToKick);
  90. }
  91. }
  92. }
  93. void PlayerMessageProcessor::commandSave(PlayerColor player, const std::vector<std::string> & words)
  94. {
  95. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  96. if(!isHost)
  97. return;
  98. if(words.size() == 2)
  99. {
  100. gameHandler->save("Saves/" + words[1]);
  101. broadcastSystemMessage("game saved as " + words[1]);
  102. }
  103. }
  104. void PlayerMessageProcessor::commandCheaters(PlayerColor player, const std::vector<std::string> & words)
  105. {
  106. int playersCheated = 0;
  107. for(const auto & player : gameHandler->gameState()->players)
  108. {
  109. if(player.second.cheated)
  110. {
  111. broadcastSystemMessage("Player " + player.first.toString() + " is cheater!");
  112. playersCheated++;
  113. }
  114. }
  115. if(!playersCheated)
  116. broadcastSystemMessage("No cheaters registered!");
  117. }
  118. void PlayerMessageProcessor::commandStatistic(PlayerColor player, const std::vector<std::string> & words)
  119. {
  120. bool isHost = gameHandler->gameLobby()->isPlayerHost(player);
  121. if(!isHost)
  122. return;
  123. const boost::filesystem::path outPath = VCMIDirs::get().userCachePath() / "statistic";
  124. boost::filesystem::create_directories(outPath);
  125. const boost::filesystem::path filePath = outPath / (vstd::getDateTimeISO8601Basic(std::time(nullptr)) + ".csv");
  126. std::ofstream file(filePath.c_str());
  127. std::string csv = gameHandler->gameState()->statistic.toCsv();
  128. file << csv;
  129. broadcastSystemMessage("Statistic files can be found in " + outPath.string() + " directory\n");
  130. }
  131. void PlayerMessageProcessor::commandHelp(PlayerColor player, const std::vector<std::string> & words)
  132. {
  133. broadcastSystemMessage("Available commands to host:");
  134. broadcastSystemMessage("'!exit' - immediately ends current game");
  135. broadcastSystemMessage("'!kick <player>' - kick specified player from the game");
  136. broadcastSystemMessage("'!save <filename>' - save game under specified filename");
  137. broadcastSystemMessage("'!statistic' - save game statistics as csv file");
  138. broadcastSystemMessage("Available commands to all players:");
  139. broadcastSystemMessage("'!help' - display this help");
  140. broadcastSystemMessage("'!cheaters' - list players that entered cheat command during game");
  141. broadcastSystemMessage("'!vote' - allows to change some game settings if all players vote for it");
  142. }
  143. void PlayerMessageProcessor::commandVote(PlayerColor player, const std::vector<std::string> & words)
  144. {
  145. if(words.size() < 2)
  146. {
  147. broadcastSystemMessage("'!vote simturns allow X' - allow simultaneous turns for specified number of days, or until contact");
  148. broadcastSystemMessage("'!vote simturns force X' - force simultaneous turns for specified number of days, blocking player contacts");
  149. broadcastSystemMessage("'!vote simturns abort' - abort simultaneous turns once this turn ends");
  150. broadcastSystemMessage("'!vote timer prolong X' - prolong base timer for all players by specified number of seconds");
  151. return;
  152. }
  153. if(words[1] == "yes" || words[1] == "no")
  154. {
  155. if(currentVote == ECurrentChatVote::NONE)
  156. {
  157. broadcastSystemMessage("No active voting!");
  158. return;
  159. }
  160. if(words[1] == "yes")
  161. {
  162. awaitingPlayers.erase(player);
  163. if(awaitingPlayers.empty())
  164. finishVoting();
  165. return;
  166. }
  167. if(words[1] == "no")
  168. {
  169. abortVoting();
  170. return;
  171. }
  172. }
  173. const auto & parseNumber = [](const std::string & input) -> std::optional<int>
  174. {
  175. try
  176. {
  177. return std::stol(input);
  178. }
  179. catch(std::logic_error &)
  180. {
  181. return std::nullopt;
  182. }
  183. };
  184. if(words[1] == "simturns" && words.size() > 2)
  185. {
  186. if(words[2] == "allow" && words.size() > 3)
  187. {
  188. auto daysCount = parseNumber(words[3]);
  189. if(daysCount && daysCount.value() > 0)
  190. startVoting(player, ECurrentChatVote::SIMTURNS_ALLOW, daysCount.value());
  191. return;
  192. }
  193. if(words[2] == "force" && words.size() > 3)
  194. {
  195. auto daysCount = parseNumber(words[3]);
  196. if(daysCount && daysCount.value() > 0)
  197. startVoting(player, ECurrentChatVote::SIMTURNS_FORCE, daysCount.value());
  198. return;
  199. }
  200. if(words[2] == "abort")
  201. {
  202. startVoting(player, ECurrentChatVote::SIMTURNS_ABORT, 0);
  203. return;
  204. }
  205. }
  206. if(words[1] == "timer" && words.size() > 2)
  207. {
  208. if(words[2] == "prolong" && words.size() > 3)
  209. {
  210. auto secondsCount = parseNumber(words[3]);
  211. if(secondsCount && secondsCount.value() > 0)
  212. startVoting(player, ECurrentChatVote::TIMER_PROLONG, secondsCount.value());
  213. return;
  214. }
  215. }
  216. broadcastSystemMessage("Voting command not recognized!");
  217. }
  218. void PlayerMessageProcessor::finishVoting()
  219. {
  220. switch(currentVote)
  221. {
  222. case ECurrentChatVote::SIMTURNS_ALLOW:
  223. broadcastSystemMessage("Voting successful. Simultaneous turns will run for " + std::to_string(currentVoteParameter) + " more days, or until contact");
  224. gameHandler->turnOrder->setMaxSimturnsDuration(currentVoteParameter);
  225. break;
  226. case ECurrentChatVote::SIMTURNS_FORCE:
  227. broadcastSystemMessage("Voting successful. Simultaneous turns will run for " + std::to_string(currentVoteParameter) + " more days. Contacts are blocked");
  228. gameHandler->turnOrder->setMinSimturnsDuration(currentVoteParameter);
  229. break;
  230. case ECurrentChatVote::SIMTURNS_ABORT:
  231. broadcastSystemMessage("Voting successful. Simultaneous turns will end on next day");
  232. gameHandler->turnOrder->setMinSimturnsDuration(0);
  233. gameHandler->turnOrder->setMaxSimturnsDuration(0);
  234. break;
  235. case ECurrentChatVote::TIMER_PROLONG:
  236. broadcastSystemMessage("Voting successful. Timer for all players has been prolonger for " + std::to_string(currentVoteParameter) + " seconds");
  237. gameHandler->turnTimerHandler->prolongTimers(currentVoteParameter * 1000);
  238. break;
  239. }
  240. currentVote = ECurrentChatVote::NONE;
  241. currentVoteParameter = -1;
  242. }
  243. void PlayerMessageProcessor::abortVoting()
  244. {
  245. broadcastSystemMessage("Player voted against change. Voting aborted");
  246. currentVote = ECurrentChatVote::NONE;
  247. }
  248. void PlayerMessageProcessor::startVoting(PlayerColor initiator, ECurrentChatVote what, int parameter)
  249. {
  250. currentVote = what;
  251. currentVoteParameter = parameter;
  252. switch(currentVote)
  253. {
  254. case ECurrentChatVote::SIMTURNS_ALLOW:
  255. broadcastSystemMessage("Started voting to allow simultaneous turns for " + std::to_string(parameter) + " more days");
  256. break;
  257. case ECurrentChatVote::SIMTURNS_FORCE:
  258. broadcastSystemMessage("Started voting to force simultaneous turns for " + std::to_string(parameter) + " more days");
  259. break;
  260. case ECurrentChatVote::SIMTURNS_ABORT:
  261. broadcastSystemMessage("Started voting to end simultaneous turns starting from next day");
  262. break;
  263. case ECurrentChatVote::TIMER_PROLONG:
  264. broadcastSystemMessage("Started voting to prolong timer for all players by " + std::to_string(parameter) + " seconds");
  265. break;
  266. default:
  267. return;
  268. }
  269. broadcastSystemMessage("Type '!vote yes' to agree to this change or '!vote no' to vote against it");
  270. awaitingPlayers.clear();
  271. for(PlayerColor player(0); player < PlayerColor::PLAYER_LIMIT; ++player)
  272. {
  273. auto state = gameHandler->getPlayerState(player, false);
  274. if(state && state->isHuman() && initiator != player)
  275. awaitingPlayers.insert(player);
  276. }
  277. if(awaitingPlayers.empty())
  278. finishVoting();
  279. }
  280. void PlayerMessageProcessor::handleCommand(PlayerColor player, const std::string & message)
  281. {
  282. if(message.empty() || message[0] != '!')
  283. return;
  284. std::vector<std::string> words;
  285. boost::split(words, message, boost::is_any_of(" "));
  286. if(words[0] == "!exit" || words[0] == "!quit")
  287. commandExit(player, words);
  288. if(words[0] == "!help")
  289. commandHelp(player, words);
  290. if(words[0] == "!vote")
  291. commandVote(player, words);
  292. if(words[0] == "!kick")
  293. commandKick(player, words);
  294. if(words[0] == "!save")
  295. commandSave(player, words);
  296. if(words[0] == "!cheaters")
  297. commandCheaters(player, words);
  298. if(words[0] == "!statistic")
  299. commandStatistic(player, words);
  300. }
  301. void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroInstance * hero)
  302. {
  303. if (!hero)
  304. return;
  305. ///Give hero spellbook
  306. if (!hero->hasSpellbook())
  307. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::SPELLBOOK).toArtifact(), ArtifactPosition::SPELLBOOK);
  308. ///Give all spells with bonus (to allow banned spells)
  309. GiveBonus giveBonus(GiveBonus::ETarget::OBJECT);
  310. giveBonus.id = hero->id;
  311. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, BonusSourceID());
  312. //start with level 0 to skip abilities
  313. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  314. {
  315. giveBonus.bonus.subtype = BonusCustomSubtype::spellLevel(level);
  316. gameHandler->sendAndApply(&giveBonus);
  317. }
  318. ///Give mana
  319. SetMana sm;
  320. sm.hid = hero->id;
  321. sm.val = 999;
  322. sm.absolute = true;
  323. gameHandler->sendAndApply(&sm);
  324. }
  325. void PlayerMessageProcessor::cheatBuildTown(PlayerColor player, const CGTownInstance * town)
  326. {
  327. if (!town)
  328. return;
  329. for (auto & build : town->town->buildings)
  330. {
  331. if (!town->hasBuilt(build.first)
  332. && !build.second->getNameTranslated().empty()
  333. && build.first != BuildingID::SHIP)
  334. {
  335. gameHandler->buildStructure(town->id, build.first, true);
  336. }
  337. }
  338. }
  339. void PlayerMessageProcessor::cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  340. {
  341. if (!hero)
  342. return;
  343. std::string creatureIdentifier = words.empty() ? "archangel" : words[0];
  344. std::optional<int> amountPerSlot;
  345. try
  346. {
  347. amountPerSlot = std::stol(words.at(1));
  348. }
  349. catch(std::logic_error&)
  350. {
  351. }
  352. std::optional<int32_t> creatureId = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "creature", creatureIdentifier, false);
  353. if(creatureId.has_value())
  354. {
  355. const auto * creature = CreatureID(creatureId.value()).toCreature();
  356. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  357. {
  358. if (!hero->hasStackAtSlot(SlotID(i)))
  359. {
  360. if (amountPerSlot.has_value())
  361. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, *amountPerSlot);
  362. else
  363. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, 5 * std::pow(10, i));
  364. }
  365. }
  366. }
  367. }
  368. void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero)
  369. {
  370. if (!hero)
  371. return;
  372. if (!hero->getArt(ArtifactPosition::MACH1))
  373. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::BALLISTA).toArtifact(), ArtifactPosition::MACH1);
  374. if (!hero->getArt(ArtifactPosition::MACH2))
  375. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::AMMO_CART).toArtifact(), ArtifactPosition::MACH2);
  376. if (!hero->getArt(ArtifactPosition::MACH3))
  377. gameHandler->giveHeroNewArtifact(hero, ArtifactID(ArtifactID::FIRST_AID_TENT).toArtifact(), ArtifactPosition::MACH3);
  378. }
  379. void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  380. {
  381. if (!hero)
  382. return;
  383. if (!words.empty())
  384. {
  385. for (auto const & word : words)
  386. {
  387. auto artID = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "artifact", word, false);
  388. if(artID && VLC->arth->objects[*artID])
  389. gameHandler->giveHeroNewArtifact(hero, ArtifactID(*artID).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
  390. }
  391. }
  392. else
  393. {
  394. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  395. {
  396. if(VLC->arth->objects[g]->canBePutAt(hero))
  397. gameHandler->giveHeroNewArtifact(hero, ArtifactID(g).toArtifact(), ArtifactPosition::FIRST_AVAILABLE);
  398. }
  399. }
  400. }
  401. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  402. {
  403. if (!hero)
  404. return;
  405. int levelsToGain;
  406. try
  407. {
  408. levelsToGain = std::stol(words.at(0));
  409. }
  410. catch(std::logic_error&)
  411. {
  412. levelsToGain = 1;
  413. }
  414. gameHandler->giveExperience(hero, VLC->heroh->reqExp(hero->level + levelsToGain) - VLC->heroh->reqExp(hero->level));
  415. }
  416. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  417. {
  418. if (!hero)
  419. return;
  420. int expAmountProcessed;
  421. try
  422. {
  423. expAmountProcessed = std::stol(words.at(0));
  424. }
  425. catch(std::logic_error&)
  426. {
  427. expAmountProcessed = 10000;
  428. }
  429. gameHandler->giveExperience(hero, expAmountProcessed);
  430. }
  431. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  432. {
  433. if (!hero)
  434. return;
  435. SetMovePoints smp;
  436. smp.hid = hero->id;
  437. bool unlimited = false;
  438. try
  439. {
  440. smp.val = std::stol(words.at(0));
  441. }
  442. catch(std::logic_error&)
  443. {
  444. smp.val = 1000000;
  445. unlimited = true;
  446. }
  447. gameHandler->sendAndApply(&smp);
  448. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  449. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  450. gb.bonus.duration = unlimited ? BonusDuration::PERMANENT : BonusDuration::ONE_DAY;
  451. gb.bonus.source = BonusSource::OTHER;
  452. gb.id = hero->id;
  453. gameHandler->giveHeroBonus(&gb);
  454. if(unlimited)
  455. {
  456. GiveBonus gb(GiveBonus::ETarget::OBJECT);
  457. gb.bonus.type = BonusType::UNLIMITED_MOVEMENT;
  458. gb.bonus.duration = BonusDuration::PERMANENT;
  459. gb.bonus.source = BonusSource::OTHER;
  460. gb.id = hero->id;
  461. gameHandler->giveHeroBonus(&gb);
  462. }
  463. }
  464. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  465. {
  466. int baseResourceAmount;
  467. try
  468. {
  469. baseResourceAmount = std::stol(words.at(0));
  470. }
  471. catch(std::logic_error&)
  472. {
  473. baseResourceAmount = 100;
  474. }
  475. TResources resources;
  476. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  477. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  478. resources[i] = baseResourceAmount;
  479. gameHandler->giveResources(player, resources);
  480. }
  481. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  482. {
  483. PlayerCheated pc;
  484. pc.player = player;
  485. pc.winningCheatCode = true;
  486. gameHandler->sendAndApply(&pc);
  487. }
  488. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  489. {
  490. PlayerCheated pc;
  491. pc.player = player;
  492. pc.losingCheatCode = true;
  493. gameHandler->sendAndApply(&pc);
  494. }
  495. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  496. {
  497. FoWChange fc;
  498. fc.mode = reveal ? ETileVisibility::REVEALED : ETileVisibility::HIDDEN;
  499. fc.player = player;
  500. const auto & fowMap = gameHandler->gameState()->getPlayerTeam(player)->fogOfWarMap;
  501. const auto & mapSize = gameHandler->gameState()->getMapSize();
  502. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  503. int lastUnc = 0;
  504. for(int z = 0; z < mapSize.z; z++)
  505. for(int x = 0; x < mapSize.x; x++)
  506. for(int y = 0; y < mapSize.y; y++)
  507. if(!fowMap[z][x][y] || fc.mode == ETileVisibility::HIDDEN)
  508. hlp_tab[lastUnc++] = int3(x, y, z);
  509. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  510. delete [] hlp_tab;
  511. gameHandler->sendAndApply(&fc);
  512. }
  513. void PlayerMessageProcessor::cheatPuzzleReveal(PlayerColor player)
  514. {
  515. TeamState *t = gameHandler->gameState()->getPlayerTeam(player);
  516. for(auto & obj : gameHandler->gameState()->map->objects)
  517. {
  518. if(obj && obj->ID == Obj::OBELISK && !obj->wasVisited(player))
  519. {
  520. gameHandler->setObjPropertyID(obj->id, ObjProperty::OBELISK_VISITED, t->id);
  521. for(const auto & color : t->players)
  522. {
  523. gameHandler->setObjPropertyID(obj->id, ObjProperty::VISITED, color);
  524. PlayerCheated pc;
  525. pc.player = color;
  526. gameHandler->sendAndApply(&pc);
  527. }
  528. }
  529. }
  530. }
  531. void PlayerMessageProcessor::cheatMaxLuck(PlayerColor player, const CGHeroInstance * hero)
  532. {
  533. if (!hero)
  534. return;
  535. GiveBonus gb;
  536. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_LUCK, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  537. gb.id = hero->id;
  538. gameHandler->giveHeroBonus(&gb);
  539. }
  540. void PlayerMessageProcessor::cheatFly(PlayerColor player, const CGHeroInstance * hero)
  541. {
  542. if (!hero)
  543. return;
  544. GiveBonus gb;
  545. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::FLYING_MOVEMENT, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  546. gb.id = hero->id;
  547. gameHandler->giveHeroBonus(&gb);
  548. }
  549. void PlayerMessageProcessor::cheatMaxMorale(PlayerColor player, const CGHeroInstance * hero)
  550. {
  551. if (!hero)
  552. return;
  553. GiveBonus gb;
  554. gb.bonus = Bonus(BonusDuration::PERMANENT, BonusType::MAX_MORALE, BonusSource::OTHER, 0, BonusSourceID(Obj(Obj::NO_OBJ)));
  555. gb.id = hero->id;
  556. gameHandler->giveHeroBonus(&gb);
  557. }
  558. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  559. {
  560. std::vector<std::string> words;
  561. boost::split(words, boost::trim_copy(cheat), boost::is_any_of("\t\r\n "));
  562. if (words.empty() || !gameHandler->getStartInfo()->extraOptionsInfo.cheatsAllowed)
  563. return false;
  564. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  565. std::string cheatName = boost::to_lower_copy(words[0]);
  566. words.erase(words.begin());
  567. std::vector<std::string> townTargetedCheats = { "vcmiarmenelos", "vcmibuild", "nwczion" };
  568. std::vector<std::string> playerTargetedCheats = {
  569. "vcmiformenos", "vcmiresources", "nwctheconstruct",
  570. "vcmimelkor", "vcmilose", "nwcbluepill",
  571. "vcmisilmaril", "vcmiwin", "nwcredpill",
  572. "vcmieagles", "vcmimap", "nwcwhatisthematrix",
  573. "vcmiungoliant", "vcmihidemap", "nwcignoranceisbliss",
  574. "vcmiobelisk", "nwcoracle"
  575. };
  576. std::vector<std::string> heroTargetedCheats = {
  577. "vcmiainur", "vcmiarchangel", "nwctrinity",
  578. "vcmiangband", "vcmiblackknight", "nwcagents",
  579. "vcmiglaurung", "vcmicrystal", "vcmiazure",
  580. "vcmifaerie", "vcmiarmy", "vcminissi",
  581. "vcmiistari", "vcmispells", "nwcthereisnospoon",
  582. "vcminoldor", "vcmimachines", "nwclotsofguns",
  583. "vcmiglorfindel", "vcmilevel", "nwcneo",
  584. "vcminahar", "vcmimove", "nwcnebuchadnezzar",
  585. "vcmiforgeofnoldorking", "vcmiartifacts",
  586. "vcmiolorin", "vcmiexp",
  587. "vcmiluck", "nwcfollowthewhiterabbit",
  588. "vcmimorale", "nwcmorpheus",
  589. "vcmigod", "nwctheone"
  590. };
  591. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  592. return false;
  593. bool playerTargetedCheat = false;
  594. for (const auto & i : gameHandler->gameState()->players)
  595. {
  596. if (words.empty())
  597. break;
  598. if (i.first == PlayerColor::NEUTRAL)
  599. continue;
  600. if (words.front() == "ai" && i.second.human)
  601. continue;
  602. if (words.front() != "all" && words.front() != i.first.toString())
  603. continue;
  604. std::vector<std::string> parameters = words;
  605. PlayerCheated pc;
  606. pc.player = i.first;
  607. gameHandler->sendAndApply(&pc);
  608. playerTargetedCheat = true;
  609. parameters.erase(parameters.begin());
  610. if (vstd::contains(playerTargetedCheats, cheatName))
  611. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  612. if (vstd::contains(townTargetedCheats, cheatName))
  613. for (const auto & t : i.second.towns)
  614. executeCheatCode(cheatName, i.first, t->id, parameters);
  615. if (vstd::contains(heroTargetedCheats, cheatName))
  616. for (const auto & h : i.second.heroes)
  617. executeCheatCode(cheatName, i.first, h->id, parameters);
  618. }
  619. PlayerCheated pc;
  620. pc.player = player;
  621. gameHandler->sendAndApply(&pc);
  622. if (!playerTargetedCheat)
  623. executeCheatCode(cheatName, player, currObj, words);
  624. return true;
  625. }
  626. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  627. {
  628. const CGHeroInstance * hero = gameHandler->getHero(currObj);
  629. const CGTownInstance * town = gameHandler->getTown(currObj);
  630. if (!town && hero)
  631. town = hero->visitedTown;
  632. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  633. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  634. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  635. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  636. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  637. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero, words); };
  638. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  639. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  640. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  641. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  642. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  643. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  644. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  645. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  646. const auto & doCheatRevealPuzzle = [&]() { cheatPuzzleReveal(player); };
  647. const auto & doCheatMaxLuck = [&]() { cheatMaxLuck(player, hero); };
  648. const auto & doCheatMaxMorale = [&]() { cheatMaxMorale(player, hero); };
  649. const auto & doCheatTheOne = [&]()
  650. {
  651. if(!hero)
  652. return;
  653. cheatMapReveal(player, true);
  654. cheatGiveArmy(player, hero, { "archangel", "5" });
  655. cheatMovement(player, hero, { });
  656. cheatFly(player, hero);
  657. };
  658. // Unimplemented H3 cheats:
  659. // nwcphisherprice - Changes and brightens the game colors.
  660. std::map<std::string, std::function<void()>> callbacks = {
  661. {"vcmiainur", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  662. {"nwctrinity", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  663. {"vcmiangband", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  664. {"vcmiglaurung", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  665. {"vcmiarchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  666. {"nwcagents", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  667. {"vcmiblackknight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  668. {"vcmicrystal", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  669. {"vcmiazure", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  670. {"vcmifaerie", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  671. {"vcmiarmy", doCheatGiveArmyCustom },
  672. {"vcminissi", doCheatGiveArmyCustom },
  673. {"vcmiistari", doCheatGiveSpells },
  674. {"vcmispells", doCheatGiveSpells },
  675. {"nwcthereisnospoon", doCheatGiveSpells },
  676. {"vcmiarmenelos", doCheatBuildTown },
  677. {"vcmibuild", doCheatBuildTown },
  678. {"nwczion", doCheatBuildTown },
  679. {"vcminoldor", doCheatGiveMachines },
  680. {"vcmimachines", doCheatGiveMachines },
  681. {"nwclotsofguns", doCheatGiveMachines },
  682. {"vcmiforgeofnoldorking", doCheatGiveArtifacts },
  683. {"vcmiartifacts", doCheatGiveArtifacts },
  684. {"vcmiglorfindel", doCheatLevelup },
  685. {"vcmilevel", doCheatLevelup },
  686. {"nwcneo", doCheatLevelup },
  687. {"vcmiolorin", doCheatExperience },
  688. {"vcmiexp", doCheatExperience },
  689. {"vcminahar", doCheatMovement },
  690. {"vcmimove", doCheatMovement },
  691. {"nwcnebuchadnezzar", doCheatMovement },
  692. {"vcmiformenos", doCheatResources },
  693. {"vcmiresources", doCheatResources },
  694. {"nwctheconstruct", doCheatResources },
  695. {"nwcbluepill", doCheatDefeat },
  696. {"vcmimelkor", doCheatDefeat },
  697. {"vcmilose", doCheatDefeat },
  698. {"nwcredpill", doCheatVictory },
  699. {"vcmisilmaril", doCheatVictory },
  700. {"vcmiwin", doCheatVictory },
  701. {"nwcwhatisthematrix", doCheatMapReveal },
  702. {"vcmieagles", doCheatMapReveal },
  703. {"vcmimap", doCheatMapReveal },
  704. {"vcmiungoliant", doCheatMapHide },
  705. {"vcmihidemap", doCheatMapHide },
  706. {"nwcignoranceisbliss", doCheatMapHide },
  707. {"vcmiobelisk", doCheatRevealPuzzle },
  708. {"nwcoracle", doCheatRevealPuzzle },
  709. {"vcmiluck", doCheatMaxLuck },
  710. {"nwcfollowthewhiterabbit", doCheatMaxLuck },
  711. {"vcmimorale", doCheatMaxMorale },
  712. {"nwcmorpheus", doCheatMaxMorale },
  713. {"vcmigod", doCheatTheOne },
  714. {"nwctheone", doCheatTheOne },
  715. };
  716. assert(callbacks.count(cheatName));
  717. if (callbacks.count(cheatName))
  718. callbacks.at(cheatName)();
  719. }
  720. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const MetaString & message)
  721. {
  722. SystemMessage sm;
  723. sm.text = message;
  724. connection->sendPack(&sm);
  725. }
  726. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const std::string & message)
  727. {
  728. MetaString str;
  729. str.appendRawString(message);
  730. sendSystemMessage(connection, str);
  731. }
  732. void PlayerMessageProcessor::broadcastSystemMessage(MetaString message)
  733. {
  734. SystemMessage sm;
  735. sm.text = message;
  736. gameHandler->sendToAllClients(&sm);
  737. }
  738. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  739. {
  740. MetaString str;
  741. str.appendRawString(message);
  742. broadcastSystemMessage(str);
  743. }
  744. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  745. {
  746. PlayerMessageClient temp_message(playerSender, message);
  747. gameHandler->sendAndApply(&temp_message);
  748. }