PlayerMessageProcessor.cpp 31 KB

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