PlayerMessageProcessor.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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::logic_error&)
  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, std::vector<std::string> words)
  181. {
  182. if (!hero)
  183. return;
  184. if (!words.empty())
  185. {
  186. for (auto const & word : words)
  187. {
  188. auto artID = VLC->modh->identifiers.getIdentifier(CModHandler::scopeGame(), "artifact", word, false);
  189. if(artID && VLC->arth->objects[*artID])
  190. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[*artID], ArtifactPosition::FIRST_AVAILABLE);
  191. }
  192. }
  193. else
  194. {
  195. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  196. {
  197. if(VLC->arth->objects[g]->canBePutAt(hero))
  198. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[g], ArtifactPosition::FIRST_AVAILABLE);
  199. }
  200. }
  201. }
  202. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  203. {
  204. if (!hero)
  205. return;
  206. int levelsToGain;
  207. try
  208. {
  209. levelsToGain = std::stol(words.at(0));
  210. }
  211. catch(std::logic_error&)
  212. {
  213. levelsToGain = 1;
  214. }
  215. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, VLC->heroh->reqExp(hero->level + levelsToGain) - VLC->heroh->reqExp(hero->level));
  216. }
  217. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  218. {
  219. if (!hero)
  220. return;
  221. int expAmountProcessed;
  222. try
  223. {
  224. expAmountProcessed = std::stol(words.at(0));
  225. }
  226. catch(std::logic_error&)
  227. {
  228. expAmountProcessed = 10000;
  229. }
  230. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, expAmountProcessed);
  231. }
  232. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  233. {
  234. if (!hero)
  235. return;
  236. SetMovePoints smp;
  237. smp.hid = hero->id;
  238. try
  239. {
  240. smp.val = std::stol(words.at(0));;
  241. }
  242. catch(std::logic_error&)
  243. {
  244. smp.val = 1000000;
  245. }
  246. gameHandler->sendAndApply(&smp);
  247. GiveBonus gb(GiveBonus::ETarget::HERO);
  248. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  249. gb.bonus.duration = BonusDuration::ONE_DAY;
  250. gb.bonus.source = BonusSource::OTHER;
  251. gb.id = hero->id.getNum();
  252. gameHandler->giveHeroBonus(&gb);
  253. }
  254. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  255. {
  256. int baseResourceAmount;
  257. try
  258. {
  259. baseResourceAmount = std::stol(words.at(0));;
  260. }
  261. catch(std::logic_error&)
  262. {
  263. baseResourceAmount = 100;
  264. }
  265. TResources resources;
  266. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  267. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  268. resources[i] = baseResourceAmount;
  269. gameHandler->giveResources(player, resources);
  270. }
  271. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  272. {
  273. PlayerCheated pc;
  274. pc.player = player;
  275. pc.winningCheatCode = true;
  276. gameHandler->sendAndApply(&pc);
  277. }
  278. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  279. {
  280. PlayerCheated pc;
  281. pc.player = player;
  282. pc.losingCheatCode = true;
  283. gameHandler->sendAndApply(&pc);
  284. }
  285. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  286. {
  287. FoWChange fc;
  288. fc.mode = reveal;
  289. fc.player = player;
  290. const auto & fowMap = gameHandler->gameState()->getPlayerTeam(player)->fogOfWarMap;
  291. const auto & mapSize = gameHandler->gameState()->getMapSize();
  292. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  293. int lastUnc = 0;
  294. for(int z = 0; z < mapSize.z; z++)
  295. for(int x = 0; x < mapSize.x; x++)
  296. for(int y = 0; y < mapSize.y; y++)
  297. if(!(*fowMap)[z][x][y] || !fc.mode)
  298. hlp_tab[lastUnc++] = int3(x, y, z);
  299. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  300. delete [] hlp_tab;
  301. gameHandler->sendAndApply(&fc);
  302. }
  303. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  304. {
  305. std::vector<std::string> words;
  306. boost::split(words, cheat, boost::is_any_of("\t\r\n "));
  307. if (words.empty())
  308. return false;
  309. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  310. std::string cheatName = boost::to_lower_copy(words[0]);
  311. words.erase(words.begin());
  312. std::vector<std::string> townTargetedCheats = { "vcmiarmenelos", "vcmibuild", "nwczion" };
  313. std::vector<std::string> playerTargetedCheats = {
  314. "vcmiformenos", "vcmiresources", "nwctheconstruct",
  315. "vcmimelkor", "vcmilose", "nwcbluepill",
  316. "vcmisilmaril", "vcmiwin", "nwcredpill",
  317. "vcmieagles", "vcmimap", "nwcwhatisthematrix",
  318. "vcmiungoliant", "vcmihidemap", "nwcignoranceisbliss"
  319. };
  320. std::vector<std::string> heroTargetedCheats = {
  321. "vcmiainur", "vcmiarchangel", "nwctrinity",
  322. "vcmiangband", "vcmiblackknight", "nwcagents",
  323. "vcmiglaurung", "vcmicrystal", "vcmiazure",
  324. "vcmifaerie", "vcmiarmy", "vcminissi",
  325. "vcmiistari", "vcmispells", "nwcthereisnospoon",
  326. "vcminoldor", "vcmimachines", "nwclotsofguns",
  327. "vcmiglorfindel", "vcmilevel", "nwcneo",
  328. "vcminahar", "vcmimove", "nwcnebuchadnezzar",
  329. "vcmiforgeofnoldorking", "vcmiartifacts",
  330. "vcmiolorin", "vcmiexp",
  331. };
  332. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  333. return false;
  334. bool playerTargetedCheat = false;
  335. for (const auto & i : gameHandler->gameState()->players)
  336. {
  337. if (words.empty())
  338. break;
  339. if (i.first == PlayerColor::NEUTRAL)
  340. continue;
  341. if (words.front() == "ai" && i.second.human)
  342. continue;
  343. if (words.front() != "all" && words.front() != i.first.getStr())
  344. continue;
  345. std::vector<std::string> parameters = words;
  346. cheaters.insert(i.first);
  347. playerTargetedCheat = true;
  348. parameters.erase(parameters.begin());
  349. if (vstd::contains(playerTargetedCheats, cheatName))
  350. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  351. if (vstd::contains(townTargetedCheats, cheatName))
  352. for (const auto & t : i.second.towns)
  353. executeCheatCode(cheatName, i.first, t->id, parameters);
  354. if (vstd::contains(heroTargetedCheats, cheatName))
  355. for (const auto & h : i.second.heroes)
  356. executeCheatCode(cheatName, i.first, h->id, parameters);
  357. }
  358. if (!playerTargetedCheat)
  359. executeCheatCode(cheatName, player, currObj, words);
  360. cheaters.insert(player);
  361. return true;
  362. }
  363. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  364. {
  365. const CGHeroInstance * hero = gameHandler->getHero(currObj);
  366. const CGTownInstance * town = gameHandler->getTown(currObj);
  367. if (!town && hero)
  368. town = hero->visitedTown;
  369. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  370. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  371. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  372. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  373. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  374. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero, words); };
  375. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  376. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  377. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  378. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  379. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  380. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  381. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  382. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  383. // Unimplemented H3 cheats:
  384. // nwcfollowthewhiterabbit - The currently selected hero permanently gains maximum luck.
  385. // nwcmorpheus - The currently selected hero permanently gains maximum morale.
  386. // nwcoracle - The puzzle map is permanently revealed.
  387. // nwcphisherprice - Changes and brightens the game colors.
  388. std::map<std::string, std::function<void()>> callbacks = {
  389. {"vcmiainur", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  390. {"nwctrinity", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  391. {"vcmiangband", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  392. {"vcmiglaurung", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  393. {"vcmiarchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  394. {"nwcagents", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  395. {"vcmiblackknight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  396. {"vcmicrystal", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  397. {"vcmiazure", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  398. {"vcmifaerie", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  399. {"vcmiarmy", doCheatGiveArmyCustom },
  400. {"vcminissi", doCheatGiveArmyCustom },
  401. {"vcmiistari", doCheatGiveSpells },
  402. {"vcmispells", doCheatGiveSpells },
  403. {"nwcthereisnospoon", doCheatGiveSpells },
  404. {"vcmiarmenelos", doCheatBuildTown },
  405. {"vcmibuild", doCheatBuildTown },
  406. {"nwczion", doCheatBuildTown },
  407. {"vcminoldor", doCheatGiveMachines },
  408. {"vcmimachines", doCheatGiveMachines },
  409. {"nwclotsofguns", doCheatGiveMachines },
  410. {"vcmiforgeofnoldorking", doCheatGiveArtifacts },
  411. {"vcmiartifacts", doCheatGiveArtifacts },
  412. {"vcmiglorfindel", doCheatLevelup },
  413. {"vcmilevel", doCheatLevelup },
  414. {"nwcneo", doCheatLevelup },
  415. {"vcmiolorin", doCheatExperience },
  416. {"vcmiexp", doCheatExperience },
  417. {"vcminahar", doCheatMovement },
  418. {"vcmimove", doCheatMovement },
  419. {"nwcnebuchadnezzar", doCheatMovement },
  420. {"vcmiformenos", doCheatResources },
  421. {"vcmiresources", doCheatResources },
  422. {"nwctheconstruct", doCheatResources },
  423. {"nwcbluepill", doCheatDefeat },
  424. {"vcmimelkor", doCheatDefeat },
  425. {"vcmilose", doCheatDefeat },
  426. {"nwcredpill", doCheatVictory },
  427. {"vcmisilmaril", doCheatVictory },
  428. {"vcmiwin", doCheatVictory },
  429. {"nwcwhatisthematrix", doCheatMapReveal },
  430. {"vcmieagles", doCheatMapReveal },
  431. {"vcmimap", doCheatMapReveal },
  432. {"vcmiungoliant", doCheatMapHide },
  433. {"vcmihidemap", doCheatMapHide },
  434. {"nwcignoranceisbliss", doCheatMapHide },
  435. };
  436. assert(callbacks.count(cheatName));
  437. if (callbacks.count(cheatName))
  438. callbacks.at(cheatName)();
  439. }
  440. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const std::string & message)
  441. {
  442. SystemMessage sm;
  443. sm.text = message;
  444. connection->sendPack(&sm);
  445. }
  446. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  447. {
  448. SystemMessage sm;
  449. sm.text = message;
  450. gameHandler->sendToAllClients(&sm);
  451. }
  452. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  453. {
  454. PlayerMessageClient temp_message(playerSender, message);
  455. gameHandler->sendAndApply(&temp_message);
  456. }