TownPlacer.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /*
  2. * TownPlacer.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 "TownPlacer.h"
  12. #include "../CMapGenerator.h"
  13. #include "../RmgMap.h"
  14. #include "../../entities/faction/CTownHandler.h"
  15. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  16. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  17. #include "../../mapObjects/CGTownInstance.h"
  18. #include "../../mapping/CMap.h"
  19. #include "../../mapping/CMapEditManager.h"
  20. #include "../../spells/CSpellHandler.h" //for choosing random spells
  21. #include "../RmgPath.h"
  22. #include "../RmgObject.h"
  23. #include "ObjectManager.h"
  24. #include "../Functions.h"
  25. #include "RoadPlacer.h"
  26. #include "MinePlacer.h"
  27. #include "WaterAdopter.h"
  28. #include "../TileInfo.h"
  29. #include <vstd/RNG.h>
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. void TownPlacer::process()
  32. {
  33. auto * manager = zone.getModificator<ObjectManager>();
  34. if(!manager)
  35. {
  36. logGlobal->error("ObjectManager doesn't exist for zone %d, skip modificator %s", zone.getId(), getName());
  37. return;
  38. }
  39. placeTowns(*manager);
  40. }
  41. void TownPlacer::init()
  42. {
  43. // TODO: Depend on other zones
  44. POSTFUNCTION(MinePlacer);
  45. POSTFUNCTION(RoadPlacer);
  46. }
  47. void TownPlacer::placeTowns(ObjectManager & manager)
  48. {
  49. // TODO: Configurew each subseqquent town based on townHints
  50. // TODO: First town should be set to type chosen by player
  51. if(zone.getOwner() && ((zone.getType() == ETemplateZoneType::CPU_START) || (zone.getType() == ETemplateZoneType::PLAYER_START)))
  52. {
  53. //set zone types to player faction, generate main town
  54. logGlobal->info("Preparing playing zone");
  55. int player_id = *zone.getOwner() - 1;
  56. const auto & playerSettings = map.getMapGenOptions().getPlayersSettings();
  57. PlayerColor player;
  58. if (playerSettings.size() > player_id)
  59. {
  60. const auto & currentPlayerSettings = std::next(playerSettings.begin(), player_id);
  61. player = currentPlayerSettings->first;
  62. zone.setTownType(currentPlayerSettings->second.getStartingTown());
  63. if(zone.getTownType() == FactionID::RANDOM)
  64. zone.setTownType(getRandomTownType(true));
  65. }
  66. else //no player - randomize town
  67. {
  68. player = PlayerColor::NEUTRAL;
  69. zone.setTownType(getTownTypeFromHint(0));
  70. }
  71. auto townFactory = LIBRARY->objtypeh->getHandlerFor(Obj::TOWN, zone.getTownType());
  72. CGTownInstance * town = dynamic_cast<CGTownInstance *>(townFactory->create(map.mapInstance->cb, nullptr));
  73. town->tempOwner = player;
  74. town->addBuilding(BuildingID::FORT);
  75. town->addBuilding(BuildingID::DEFAULT);
  76. for(auto spellID : LIBRARY->spellh->getDefaultAllowed()) //add all regular spells to town
  77. town->possibleSpells.push_back(spellID);
  78. auto position = placeMainTown(manager, *town);
  79. totalTowns++;
  80. //register MAIN town of zone only
  81. map.registerZone(town->getFactionID());
  82. if(player.isValidPlayer()) //configure info for owning player
  83. {
  84. logGlobal->trace("Fill player info %d", player_id);
  85. // Update player info
  86. auto & playerInfo = map.getPlayer(player.getNum());
  87. playerInfo.allowedFactions.clear();
  88. playerInfo.allowedFactions.insert(zone.getTownType());
  89. playerInfo.hasMainTown = true;
  90. playerInfo.posOfMainTown = position;
  91. playerInfo.generateHeroAtMainTown = true;
  92. //now create actual towns
  93. addNewTowns(zone.getPlayerTowns().getCastleCount() - 1, true, player, manager);
  94. addNewTowns(zone.getPlayerTowns().getTownCount(), false, player, manager);
  95. }
  96. else
  97. {
  98. addNewTowns(zone.getPlayerTowns().getCastleCount() - 1, true, PlayerColor::NEUTRAL, manager);
  99. addNewTowns(zone.getPlayerTowns().getTownCount(), false, PlayerColor::NEUTRAL, manager);
  100. }
  101. }
  102. else //randomize town types for non-player zones
  103. {
  104. zone.setTownType(getRandomTownType());
  105. }
  106. addNewTowns(zone.getNeutralTowns().getCastleCount(), true, PlayerColor::NEUTRAL, manager);
  107. addNewTowns(zone.getNeutralTowns().getTownCount(), false, PlayerColor::NEUTRAL, manager);
  108. if(!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  109. {
  110. //25% chance for neutral
  111. if (zone.getRand().nextInt(1, 100) <= 25)
  112. {
  113. zone.setTownType(ETownType::NEUTRAL);
  114. }
  115. else
  116. {
  117. if(!zone.getTownTypes().empty())
  118. zone.setTownType(*RandomGeneratorUtil::nextItem(zone.getTownTypes(), zone.getRand()));
  119. else if(!zone.getMonsterTypes().empty())
  120. zone.setTownType(*RandomGeneratorUtil::nextItem(zone.getMonsterTypes(), zone.getRand())); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  121. else //just in any case
  122. zone.setTownType(getRandomTownType());
  123. }
  124. }
  125. }
  126. int3 TownPlacer::placeMainTown(ObjectManager & manager, CGTownInstance & town)
  127. {
  128. //towns are big objects and should be centered around visitable position
  129. rmg::Object rmgObject(town);
  130. rmgObject.setTemplate(zone.getTerrainType(), zone.getRand());
  131. int3 position(-1, -1, -1);
  132. {
  133. Zone::Lock lock(zone.areaMutex);
  134. position = manager.findPlaceForObject(zone.areaPossible().get(), rmgObject, [this](const int3& t)
  135. {
  136. float distance = zone.getPos().dist2dSQ(t);
  137. return 100000.f - distance; //some big number
  138. }, ObjectManager::OptimizeType::WEIGHT);
  139. }
  140. rmgObject.setPosition(position + int3(2, 2, 0)); //place visitable tile in the exact center of a zone
  141. manager.placeObject(rmgObject, false, true, true);
  142. cleanupBoundaries(rmgObject);
  143. zone.setPos(rmgObject.getVisitablePosition()); //roads lead to main town
  144. return position;
  145. }
  146. void TownPlacer::cleanupBoundaries(const rmg::Object & rmgObject)
  147. {
  148. Zone::Lock lock(zone.areaMutex);
  149. for(const auto & t : rmgObject.getArea().getBorderOutside())
  150. {
  151. if (t.y > rmgObject.getVisitablePosition().y) //Line below the town
  152. {
  153. if (map.isOnMap(t))
  154. {
  155. map.setOccupied(t, ETileType::FREE);
  156. zone.areaPossible()->erase(t);
  157. zone.freePaths()->add(t);
  158. }
  159. }
  160. }
  161. }
  162. FactionID TownPlacer::getTownTypeFromHint(size_t hintIndex)
  163. {
  164. const auto & hints = zone.getTownHints();
  165. if(hints.size() <= hintIndex)
  166. return zone.getTownType();
  167. const auto & townHints = hints[hintIndex];
  168. FactionID subType = zone.getTownType();
  169. if(townHints.likeZone != rmg::ZoneOptions::NO_ZONE)
  170. {
  171. // Copy directly from other zone
  172. subType = map.getZones().at(townHints.likeZone)->getTownType();
  173. }
  174. else if(townHints.notLikeZone != rmg::ZoneOptions::NO_ZONE)
  175. {
  176. // Exclude type rolled for other zone
  177. auto townTypes = zone.getTownTypes();
  178. townTypes.erase(map.getZones().at(townHints.notLikeZone)->getTownType());
  179. zone.setTownTypes(townTypes);
  180. if(!townTypes.empty())
  181. subType = *RandomGeneratorUtil::nextItem(townTypes, zone.getRand());
  182. }
  183. else if(townHints.relatedToZoneTerrain != rmg::ZoneOptions::NO_ZONE)
  184. {
  185. auto townTerrain = map.getZones().at(townHints.relatedToZoneTerrain)->getTerrainType();
  186. auto townTypesAllowed = zone.getTownTypes();
  187. vstd::erase_if(townTypesAllowed, [townTerrain](FactionID type)
  188. {
  189. return (*LIBRARY->townh)[type]->getNativeTerrain() != townTerrain;
  190. });
  191. zone.setTownTypes(townTypesAllowed);
  192. if(!townTypesAllowed.empty())
  193. subType = *RandomGeneratorUtil::nextItem(townTypesAllowed, zone.getRand());
  194. }
  195. return subType;
  196. }
  197. void TownPlacer::addNewTowns(int count, bool hasFort, const PlayerColor & player, ObjectManager & manager)
  198. {
  199. for(int i = 0; i < count; i++)
  200. {
  201. FactionID subType = zone.getTownType();
  202. if(totalTowns > 0)
  203. {
  204. if(!zone.areTownsSameType())
  205. {
  206. subType = getTownTypeFromHint(totalTowns);
  207. }
  208. }
  209. auto townFactory = LIBRARY->objtypeh->getHandlerFor(Obj::TOWN, subType);
  210. auto * town = dynamic_cast<CGTownInstance *>(townFactory->create(map.mapInstance->cb, nullptr));
  211. town->ID = Obj::TOWN;
  212. town->tempOwner = player;
  213. if (hasFort)
  214. town->addBuilding(BuildingID::FORT);
  215. town->addBuilding(BuildingID::DEFAULT);
  216. for(auto spellID : LIBRARY->spellh->getDefaultAllowed()) //add all regular spells to town
  217. town->possibleSpells.push_back(spellID);
  218. if(totalTowns <= 0)
  219. {
  220. //FIXME: discovered bug with small zones - getPos is close to map boarder and we have outOfMap exception
  221. //register MAIN town of zone
  222. map.registerZone(town->getFactionID());
  223. //first town in zone goes in the middle
  224. placeMainTown(manager, *town);
  225. }
  226. else
  227. {
  228. manager.addRequiredObject(RequiredObjectInfo(town, 0, true));
  229. }
  230. totalTowns++;
  231. }
  232. }
  233. FactionID TownPlacer::getRandomTownType(bool matchUndergroundType)
  234. {
  235. auto townTypesAllowed = (!zone.getTownTypes().empty() ? zone.getTownTypes() : zone.getDefaultTownTypes());
  236. if(matchUndergroundType)
  237. {
  238. std::set<FactionID> townTypesVerify;
  239. for(auto factionIdx : townTypesAllowed)
  240. {
  241. bool preferUnderground = (*LIBRARY->townh)[factionIdx]->preferUndergroundPlacement;
  242. if(zone.isUnderground() ? preferUnderground : !preferUnderground)
  243. {
  244. townTypesVerify.insert(factionIdx);
  245. }
  246. }
  247. if(!townTypesVerify.empty())
  248. townTypesAllowed = townTypesVerify;
  249. }
  250. return *RandomGeneratorUtil::nextItem(townTypesAllowed, zone.getRand());
  251. }
  252. int TownPlacer::getTotalTowns() const
  253. {
  254. return totalTowns;
  255. }
  256. VCMI_LIB_NAMESPACE_END