PlayerMessageProcessor.cpp 17 KB

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