PlayerMessageProcessor.cpp 17 KB

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