PlayerMessageProcessor.cpp 28 KB

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