PlayerMessageProcessor.cpp 35 KB

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