2
0

PlayerMessageProcessor.cpp 29 KB

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