PlayerMessageProcessor.cpp 35 KB

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