PlayerMessageProcessor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 "../CGameHandler.h"
  13. #include "../CVCMIServer.h"
  14. #include "../../lib/serializer/Connection.h"
  15. #include "../../lib/CGeneralTextHandler.h"
  16. #include "../../lib/CHeroHandler.h"
  17. #include "../../lib/bonuses/BonusSubtypes.h"
  18. #include "../../lib/modding/IdentifierStorage.h"
  19. #include "../../lib/CPlayerState.h"
  20. #include "../../lib/GameConstants.h"
  21. #include "../../lib/NetPacks.h"
  22. #include "../../lib/StartInfo.h"
  23. #include "../../lib/gameState/CGameState.h"
  24. #include "../../lib/mapObjects/CGTownInstance.h"
  25. #include "../../lib/modding/IdentifierStorage.h"
  26. #include "../../lib/modding/ModScope.h"
  27. PlayerMessageProcessor::PlayerMessageProcessor()
  28. :gameHandler(nullptr)
  29. {
  30. }
  31. PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
  32. :gameHandler(gameHandler)
  33. {
  34. }
  35. void PlayerMessageProcessor::playerMessage(PlayerColor player, const std::string &message, ObjectInstanceID currObj)
  36. {
  37. if (handleHostCommand(player, message))
  38. return;
  39. if (handleCheatCode(message, player, currObj))
  40. {
  41. if(!gameHandler->getPlayerSettings(player)->isControlledByAI())
  42. broadcastSystemMessage(VLC->generaltexth->allTexts[260]);
  43. if(!player.isSpectator())
  44. gameHandler->checkVictoryLossConditionsForPlayer(player);//Player enter win code or got required art\creature
  45. return;
  46. }
  47. broadcastMessage(player, message);
  48. }
  49. bool PlayerMessageProcessor::handleHostCommand(PlayerColor player, const std::string &message)
  50. {
  51. std::vector<std::string> words;
  52. boost::split(words, message, boost::is_any_of(" "));
  53. bool isHost = false;
  54. for(auto & c : gameHandler->connections[player])
  55. if(gameHandler->gameLobby()->isClientHost(c->connectionID))
  56. isHost = true;
  57. if(!isHost || words.size() < 2 || words[0] != "game")
  58. return false;
  59. if(words[1] == "exit" || words[1] == "quit" || words[1] == "end")
  60. {
  61. broadcastSystemMessage("game was terminated");
  62. gameHandler->gameLobby()->setState(EServerState::SHUTDOWN);
  63. return true;
  64. }
  65. if(words.size() == 3 && words[1] == "save")
  66. {
  67. gameHandler->save("Saves/" + words[2]);
  68. broadcastSystemMessage("game saved as " + words[2]);
  69. return true;
  70. }
  71. if(words.size() == 3 && words[1] == "kick")
  72. {
  73. auto playername = words[2];
  74. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  75. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  76. playerToKick = PlayerColor(std::stoi(playername));
  77. else
  78. {
  79. for(auto & c : gameHandler->connections)
  80. {
  81. if(c.first.toString() == playername)
  82. playerToKick = c.first;
  83. }
  84. }
  85. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  86. {
  87. PlayerCheated pc;
  88. pc.player = playerToKick;
  89. pc.losingCheatCode = true;
  90. gameHandler->sendAndApply(&pc);
  91. gameHandler->checkVictoryLossConditionsForPlayer(playerToKick);
  92. }
  93. return true;
  94. }
  95. if(words.size() == 2 && words[1] == "cheaters")
  96. {
  97. int playersCheated = 0;
  98. for (const auto & player : gameHandler->gameState()->players)
  99. {
  100. if(player.second.cheated)
  101. {
  102. broadcastSystemMessage("Player " + player.first.toString() + " is cheater!");
  103. playersCheated++;
  104. }
  105. }
  106. if (!playersCheated)
  107. broadcastSystemMessage("No cheaters registered!");
  108. return true;
  109. }
  110. return false;
  111. }
  112. void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroInstance * hero)
  113. {
  114. if (!hero)
  115. return;
  116. ///Give hero spellbook
  117. if (!hero->hasSpellbook())
  118. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  119. ///Give all spells with bonus (to allow banned spells)
  120. GiveBonus giveBonus(GiveBonus::ETarget::HERO);
  121. giveBonus.id = hero->id.getNum();
  122. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, 0);
  123. //start with level 0 to skip abilities
  124. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  125. {
  126. giveBonus.bonus.subtype = BonusSubtypes::spellLevel(level);
  127. gameHandler->sendAndApply(&giveBonus);
  128. }
  129. ///Give mana
  130. SetMana sm;
  131. sm.hid = hero->id;
  132. sm.val = 999;
  133. sm.absolute = true;
  134. gameHandler->sendAndApply(&sm);
  135. }
  136. void PlayerMessageProcessor::cheatBuildTown(PlayerColor player, const CGTownInstance * town)
  137. {
  138. if (!town)
  139. return;
  140. for (auto & build : town->town->buildings)
  141. {
  142. if (!town->hasBuilt(build.first)
  143. && !build.second->getNameTranslated().empty()
  144. && build.first != BuildingID::SHIP)
  145. {
  146. gameHandler->buildStructure(town->id, build.first, true);
  147. }
  148. }
  149. }
  150. void PlayerMessageProcessor::cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  151. {
  152. if (!hero)
  153. return;
  154. std::string creatureIdentifier = words.empty() ? "archangel" : words[0];
  155. std::optional<int> amountPerSlot;
  156. try
  157. {
  158. amountPerSlot = std::stol(words.at(1));
  159. }
  160. catch(std::logic_error&)
  161. {
  162. }
  163. std::optional<int32_t> creatureId = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "creature", creatureIdentifier, false);
  164. if(creatureId.has_value())
  165. {
  166. const auto * creature = CreatureID(creatureId.value()).toCreature();
  167. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  168. {
  169. if (!hero->hasStackAtSlot(SlotID(i)))
  170. {
  171. if (amountPerSlot.has_value())
  172. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, *amountPerSlot);
  173. else
  174. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, 5 * std::pow(10, i));
  175. }
  176. }
  177. }
  178. }
  179. void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero)
  180. {
  181. if (!hero)
  182. return;
  183. if (!hero->getArt(ArtifactPosition::MACH1))
  184. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::BALLISTA], ArtifactPosition::MACH1);
  185. if (!hero->getArt(ArtifactPosition::MACH2))
  186. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::AMMO_CART], ArtifactPosition::MACH2);
  187. if (!hero->getArt(ArtifactPosition::MACH3))
  188. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::FIRST_AID_TENT], ArtifactPosition::MACH3);
  189. }
  190. void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  191. {
  192. if (!hero)
  193. return;
  194. if (!words.empty())
  195. {
  196. for (auto const & word : words)
  197. {
  198. auto artID = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "artifact", word, false);
  199. if(artID && VLC->arth->objects[*artID])
  200. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[*artID], ArtifactPosition::FIRST_AVAILABLE);
  201. }
  202. }
  203. else
  204. {
  205. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  206. {
  207. if(VLC->arth->objects[g]->canBePutAt(hero))
  208. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[g], ArtifactPosition::FIRST_AVAILABLE);
  209. }
  210. }
  211. }
  212. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  213. {
  214. if (!hero)
  215. return;
  216. int levelsToGain;
  217. try
  218. {
  219. levelsToGain = std::stol(words.at(0));
  220. }
  221. catch(std::logic_error&)
  222. {
  223. levelsToGain = 1;
  224. }
  225. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, VLC->heroh->reqExp(hero->level + levelsToGain) - VLC->heroh->reqExp(hero->level));
  226. }
  227. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  228. {
  229. if (!hero)
  230. return;
  231. int expAmountProcessed;
  232. try
  233. {
  234. expAmountProcessed = std::stol(words.at(0));
  235. }
  236. catch(std::logic_error&)
  237. {
  238. expAmountProcessed = 10000;
  239. }
  240. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, expAmountProcessed);
  241. }
  242. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  243. {
  244. if (!hero)
  245. return;
  246. SetMovePoints smp;
  247. smp.hid = hero->id;
  248. try
  249. {
  250. smp.val = std::stol(words.at(0));;
  251. }
  252. catch(std::logic_error&)
  253. {
  254. smp.val = 1000000;
  255. }
  256. gameHandler->sendAndApply(&smp);
  257. GiveBonus gb(GiveBonus::ETarget::HERO);
  258. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  259. gb.bonus.duration = BonusDuration::ONE_DAY;
  260. gb.bonus.source = BonusSource::OTHER;
  261. gb.id = hero->id.getNum();
  262. gameHandler->giveHeroBonus(&gb);
  263. }
  264. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  265. {
  266. int baseResourceAmount;
  267. try
  268. {
  269. baseResourceAmount = std::stol(words.at(0));;
  270. }
  271. catch(std::logic_error&)
  272. {
  273. baseResourceAmount = 100;
  274. }
  275. TResources resources;
  276. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  277. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  278. resources[i] = baseResourceAmount;
  279. gameHandler->giveResources(player, resources);
  280. }
  281. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  282. {
  283. PlayerCheated pc;
  284. pc.player = player;
  285. pc.winningCheatCode = true;
  286. gameHandler->sendAndApply(&pc);
  287. }
  288. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  289. {
  290. PlayerCheated pc;
  291. pc.player = player;
  292. pc.losingCheatCode = true;
  293. gameHandler->sendAndApply(&pc);
  294. }
  295. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  296. {
  297. FoWChange fc;
  298. fc.mode = reveal ? ETileVisibility::REVEALED : ETileVisibility::HIDDEN;
  299. fc.player = player;
  300. const auto & fowMap = gameHandler->gameState()->getPlayerTeam(player)->fogOfWarMap;
  301. const auto & mapSize = gameHandler->gameState()->getMapSize();
  302. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  303. int lastUnc = 0;
  304. for(int z = 0; z < mapSize.z; z++)
  305. for(int x = 0; x < mapSize.x; x++)
  306. for(int y = 0; y < mapSize.y; y++)
  307. if(!(*fowMap)[z][x][y] || fc.mode == ETileVisibility::HIDDEN)
  308. hlp_tab[lastUnc++] = int3(x, y, z);
  309. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  310. delete [] hlp_tab;
  311. gameHandler->sendAndApply(&fc);
  312. }
  313. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  314. {
  315. std::vector<std::string> words;
  316. boost::split(words, cheat, boost::is_any_of("\t\r\n "));
  317. if (words.empty())
  318. return false;
  319. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  320. std::string cheatName = boost::to_lower_copy(words[0]);
  321. words.erase(words.begin());
  322. std::vector<std::string> townTargetedCheats = { "vcmiarmenelos", "vcmibuild", "nwczion" };
  323. std::vector<std::string> playerTargetedCheats = {
  324. "vcmiformenos", "vcmiresources", "nwctheconstruct",
  325. "vcmimelkor", "vcmilose", "nwcbluepill",
  326. "vcmisilmaril", "vcmiwin", "nwcredpill",
  327. "vcmieagles", "vcmimap", "nwcwhatisthematrix",
  328. "vcmiungoliant", "vcmihidemap", "nwcignoranceisbliss"
  329. };
  330. std::vector<std::string> heroTargetedCheats = {
  331. "vcmiainur", "vcmiarchangel", "nwctrinity",
  332. "vcmiangband", "vcmiblackknight", "nwcagents",
  333. "vcmiglaurung", "vcmicrystal", "vcmiazure",
  334. "vcmifaerie", "vcmiarmy", "vcminissi",
  335. "vcmiistari", "vcmispells", "nwcthereisnospoon",
  336. "vcminoldor", "vcmimachines", "nwclotsofguns",
  337. "vcmiglorfindel", "vcmilevel", "nwcneo",
  338. "vcminahar", "vcmimove", "nwcnebuchadnezzar",
  339. "vcmiforgeofnoldorking", "vcmiartifacts",
  340. "vcmiolorin", "vcmiexp",
  341. };
  342. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  343. return false;
  344. bool playerTargetedCheat = false;
  345. for (const auto & i : gameHandler->gameState()->players)
  346. {
  347. if (words.empty())
  348. break;
  349. if (i.first == PlayerColor::NEUTRAL)
  350. continue;
  351. if (words.front() == "ai" && i.second.human)
  352. continue;
  353. if (words.front() != "all" && words.front() != i.first.toString())
  354. continue;
  355. std::vector<std::string> parameters = words;
  356. PlayerCheated pc;
  357. pc.player = i.first;
  358. gameHandler->sendAndApply(&pc);
  359. playerTargetedCheat = true;
  360. parameters.erase(parameters.begin());
  361. if (vstd::contains(playerTargetedCheats, cheatName))
  362. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  363. if (vstd::contains(townTargetedCheats, cheatName))
  364. for (const auto & t : i.second.towns)
  365. executeCheatCode(cheatName, i.first, t->id, parameters);
  366. if (vstd::contains(heroTargetedCheats, cheatName))
  367. for (const auto & h : i.second.heroes)
  368. executeCheatCode(cheatName, i.first, h->id, parameters);
  369. }
  370. PlayerCheated pc;
  371. pc.player = player;
  372. gameHandler->sendAndApply(&pc);
  373. if (!playerTargetedCheat)
  374. executeCheatCode(cheatName, player, currObj, words);
  375. return true;
  376. }
  377. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  378. {
  379. const CGHeroInstance * hero = gameHandler->getHero(currObj);
  380. const CGTownInstance * town = gameHandler->getTown(currObj);
  381. if (!town && hero)
  382. town = hero->visitedTown;
  383. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  384. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  385. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  386. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  387. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  388. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero, words); };
  389. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  390. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  391. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  392. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  393. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  394. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  395. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  396. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  397. // Unimplemented H3 cheats:
  398. // nwcfollowthewhiterabbit - The currently selected hero permanently gains maximum luck.
  399. // nwcmorpheus - The currently selected hero permanently gains maximum morale.
  400. // nwcoracle - The puzzle map is permanently revealed.
  401. // nwcphisherprice - Changes and brightens the game colors.
  402. std::map<std::string, std::function<void()>> callbacks = {
  403. {"vcmiainur", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  404. {"nwctrinity", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  405. {"vcmiangband", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  406. {"vcmiglaurung", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  407. {"vcmiarchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  408. {"nwcagents", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  409. {"vcmiblackknight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  410. {"vcmicrystal", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  411. {"vcmiazure", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  412. {"vcmifaerie", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  413. {"vcmiarmy", doCheatGiveArmyCustom },
  414. {"vcminissi", doCheatGiveArmyCustom },
  415. {"vcmiistari", doCheatGiveSpells },
  416. {"vcmispells", doCheatGiveSpells },
  417. {"nwcthereisnospoon", doCheatGiveSpells },
  418. {"vcmiarmenelos", doCheatBuildTown },
  419. {"vcmibuild", doCheatBuildTown },
  420. {"nwczion", doCheatBuildTown },
  421. {"vcminoldor", doCheatGiveMachines },
  422. {"vcmimachines", doCheatGiveMachines },
  423. {"nwclotsofguns", doCheatGiveMachines },
  424. {"vcmiforgeofnoldorking", doCheatGiveArtifacts },
  425. {"vcmiartifacts", doCheatGiveArtifacts },
  426. {"vcmiglorfindel", doCheatLevelup },
  427. {"vcmilevel", doCheatLevelup },
  428. {"nwcneo", doCheatLevelup },
  429. {"vcmiolorin", doCheatExperience },
  430. {"vcmiexp", doCheatExperience },
  431. {"vcminahar", doCheatMovement },
  432. {"vcmimove", doCheatMovement },
  433. {"nwcnebuchadnezzar", doCheatMovement },
  434. {"vcmiformenos", doCheatResources },
  435. {"vcmiresources", doCheatResources },
  436. {"nwctheconstruct", doCheatResources },
  437. {"nwcbluepill", doCheatDefeat },
  438. {"vcmimelkor", doCheatDefeat },
  439. {"vcmilose", doCheatDefeat },
  440. {"nwcredpill", doCheatVictory },
  441. {"vcmisilmaril", doCheatVictory },
  442. {"vcmiwin", doCheatVictory },
  443. {"nwcwhatisthematrix", doCheatMapReveal },
  444. {"vcmieagles", doCheatMapReveal },
  445. {"vcmimap", doCheatMapReveal },
  446. {"vcmiungoliant", doCheatMapHide },
  447. {"vcmihidemap", doCheatMapHide },
  448. {"nwcignoranceisbliss", doCheatMapHide },
  449. };
  450. assert(callbacks.count(cheatName));
  451. if (callbacks.count(cheatName))
  452. callbacks.at(cheatName)();
  453. }
  454. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const std::string & message)
  455. {
  456. SystemMessage sm;
  457. sm.text = message;
  458. connection->sendPack(&sm);
  459. }
  460. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  461. {
  462. SystemMessage sm;
  463. sm.text = message;
  464. gameHandler->sendToAllClients(&sm);
  465. }
  466. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  467. {
  468. PlayerMessageClient temp_message(playerSender, message);
  469. gameHandler->sendAndApply(&temp_message);
  470. }