CMapEditManager.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. #include "StdInc.h"
  2. #include "CMapEditManager.h"
  3. #include "../JsonNode.h"
  4. #include "../filesystem/Filesystem.h"
  5. #include "../mapObjects/CObjectClassesHandler.h"
  6. #include "../mapObjects/CGHeroInstance.h"
  7. #include "../VCMI_Lib.h"
  8. #include "CDrawRoadsOperation.h"
  9. MapRect::MapRect() : x(0), y(0), z(0), width(0), height(0)
  10. {
  11. }
  12. MapRect::MapRect(int3 pos, si32 width, si32 height) : x(pos.x), y(pos.y), z(pos.z), width(width), height(height)
  13. {
  14. }
  15. MapRect MapRect::operator&(const MapRect & rect) const
  16. {
  17. bool intersect = right() > rect.left() && rect.right() > left() &&
  18. bottom() > rect.top() && rect.bottom() > top() &&
  19. z == rect.z;
  20. if(intersect)
  21. {
  22. MapRect ret;
  23. ret.x = std::max(left(), rect.left());
  24. ret.y = std::max(top(), rect.top());
  25. ret.z = rect.z;
  26. ret.width = std::min(right(), rect.right()) - ret.x;
  27. ret.height = std::min(bottom(), rect.bottom()) - ret.y;
  28. return ret;
  29. }
  30. else
  31. {
  32. return MapRect();
  33. }
  34. }
  35. si32 MapRect::left() const
  36. {
  37. return x;
  38. }
  39. si32 MapRect::right() const
  40. {
  41. return x + width;
  42. }
  43. si32 MapRect::top() const
  44. {
  45. return y;
  46. }
  47. si32 MapRect::bottom() const
  48. {
  49. return y + height;
  50. }
  51. int3 MapRect::topLeft() const
  52. {
  53. return int3(x, y, z);
  54. }
  55. int3 MapRect::topRight() const
  56. {
  57. return int3(right(), y, z);
  58. }
  59. int3 MapRect::bottomLeft() const
  60. {
  61. return int3(x, bottom(), z);
  62. }
  63. int3 MapRect::bottomRight() const
  64. {
  65. return int3(right(), bottom(), z);
  66. }
  67. CTerrainSelection::CTerrainSelection(CMap * map) : CMapSelection(map)
  68. {
  69. }
  70. void CTerrainSelection::selectRange(const MapRect & rect)
  71. {
  72. rect.forEach([this](const int3 pos)
  73. {
  74. this->select(pos);
  75. });
  76. }
  77. void CTerrainSelection::deselectRange(const MapRect & rect)
  78. {
  79. rect.forEach([this](const int3 pos)
  80. {
  81. this->deselect(pos);
  82. });
  83. }
  84. void CTerrainSelection::setSelection(std::vector<int3> & vec)
  85. {
  86. for (auto pos : vec)
  87. this->select(pos);
  88. }
  89. void CTerrainSelection::selectAll()
  90. {
  91. selectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
  92. selectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
  93. }
  94. void CTerrainSelection::clearSelection()
  95. {
  96. deselectRange(MapRect(int3(0, 0, 0), getMap()->width, getMap()->height));
  97. deselectRange(MapRect(int3(0, 0, 1), getMap()->width, getMap()->height));
  98. }
  99. CObjectSelection::CObjectSelection(CMap * map) : CMapSelection(map)
  100. {
  101. }
  102. CMapOperation::CMapOperation(CMap * map) : map(map)
  103. {
  104. }
  105. std::string CMapOperation::getLabel() const
  106. {
  107. return "";
  108. }
  109. MapRect CMapOperation::extendTileAround(const int3 & centerPos) const
  110. {
  111. return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
  112. }
  113. MapRect CMapOperation::extendTileAroundSafely(const int3 & centerPos) const
  114. {
  115. return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
  116. }
  117. CMapUndoManager::CMapUndoManager() : undoRedoLimit(10)
  118. {
  119. }
  120. void CMapUndoManager::undo()
  121. {
  122. doOperation(undoStack, redoStack, true);
  123. }
  124. void CMapUndoManager::redo()
  125. {
  126. doOperation(redoStack, undoStack, false);
  127. }
  128. void CMapUndoManager::clearAll()
  129. {
  130. undoStack.clear();
  131. redoStack.clear();
  132. }
  133. int CMapUndoManager::getUndoRedoLimit() const
  134. {
  135. return undoRedoLimit;
  136. }
  137. void CMapUndoManager::setUndoRedoLimit(int value)
  138. {
  139. assert(value >= 0);
  140. undoStack.resize(std::min(undoStack.size(), static_cast<TStack::size_type>(value)));
  141. redoStack.resize(std::min(redoStack.size(), static_cast<TStack::size_type>(value)));
  142. }
  143. const CMapOperation * CMapUndoManager::peekRedo() const
  144. {
  145. return peek(redoStack);
  146. }
  147. const CMapOperation * CMapUndoManager::peekUndo() const
  148. {
  149. return peek(undoStack);
  150. }
  151. void CMapUndoManager::addOperation(unique_ptr<CMapOperation> && operation)
  152. {
  153. undoStack.push_front(std::move(operation));
  154. if(undoStack.size() > undoRedoLimit) undoStack.pop_back();
  155. redoStack.clear();
  156. }
  157. void CMapUndoManager::doOperation(TStack & fromStack, TStack & toStack, bool doUndo)
  158. {
  159. if(fromStack.empty()) return;
  160. auto & operation = fromStack.front();
  161. if(doUndo)
  162. {
  163. operation->undo();
  164. }
  165. else
  166. {
  167. operation->redo();
  168. }
  169. toStack.push_front(std::move(operation));
  170. fromStack.pop_front();
  171. }
  172. const CMapOperation * CMapUndoManager::peek(const TStack & stack) const
  173. {
  174. if(stack.empty()) return nullptr;
  175. return stack.front().get();
  176. }
  177. CMapEditManager::CMapEditManager(CMap * map)
  178. : map(map), terrainSel(map), objectSel(map)
  179. {
  180. }
  181. CMap * CMapEditManager::getMap()
  182. {
  183. return map;
  184. }
  185. void CMapEditManager::clearTerrain(CRandomGenerator * gen/* = nullptr*/)
  186. {
  187. execute(make_unique<CClearTerrainOperation>(map, gen ? gen : &(this->gen)));
  188. }
  189. void CMapEditManager::drawTerrain(ETerrainType terType, CRandomGenerator * gen/* = nullptr*/)
  190. {
  191. execute(make_unique<CDrawTerrainOperation>(map, terrainSel, terType, gen ? gen : &(this->gen)));
  192. terrainSel.clearSelection();
  193. }
  194. void CMapEditManager::drawRoad(ERoadType::ERoadType roadType, CRandomGenerator* gen)
  195. {
  196. execute(make_unique<CDrawRoadsOperation>(map, terrainSel, roadType, gen ? gen : &(this->gen)));
  197. terrainSel.clearSelection();
  198. }
  199. void CMapEditManager::insertObject(CGObjectInstance * obj, const int3 & pos)
  200. {
  201. execute(make_unique<CInsertObjectOperation>(map, obj, pos));
  202. }
  203. void CMapEditManager::execute(unique_ptr<CMapOperation> && operation)
  204. {
  205. operation->execute();
  206. undoManager.addOperation(std::move(operation));
  207. }
  208. CTerrainSelection & CMapEditManager::getTerrainSelection()
  209. {
  210. return terrainSel;
  211. }
  212. CObjectSelection & CMapEditManager::getObjectSelection()
  213. {
  214. return objectSel;
  215. }
  216. CMapUndoManager & CMapEditManager::getUndoManager()
  217. {
  218. return undoManager;
  219. }
  220. CComposedOperation::CComposedOperation(CMap * map) : CMapOperation(map)
  221. {
  222. }
  223. void CComposedOperation::execute()
  224. {
  225. for(auto & operation : operations)
  226. {
  227. operation->execute();
  228. }
  229. }
  230. void CComposedOperation::undo()
  231. {
  232. for(auto & operation : operations)
  233. {
  234. operation->undo();
  235. }
  236. }
  237. void CComposedOperation::redo()
  238. {
  239. for(auto & operation : operations)
  240. {
  241. operation->redo();
  242. }
  243. }
  244. void CComposedOperation::addOperation(unique_ptr<CMapOperation> && operation)
  245. {
  246. operations.push_back(std::move(operation));
  247. }
  248. const std::string TerrainViewPattern::FLIP_MODE_DIFF_IMAGES = "D";
  249. const std::string TerrainViewPattern::RULE_DIRT = "D";
  250. const std::string TerrainViewPattern::RULE_SAND = "S";
  251. const std::string TerrainViewPattern::RULE_TRANSITION = "T";
  252. const std::string TerrainViewPattern::RULE_NATIVE = "N";
  253. const std::string TerrainViewPattern::RULE_NATIVE_STRONG = "N!";
  254. const std::string TerrainViewPattern::RULE_ANY = "?";
  255. TerrainViewPattern::TerrainViewPattern() : diffImages(false), rotationTypesCount(0), minPoints(0)
  256. {
  257. maxPoints = std::numeric_limits<int>::max();
  258. }
  259. TerrainViewPattern::WeightedRule::WeightedRule() : points(0)
  260. {
  261. }
  262. bool TerrainViewPattern::WeightedRule::isStandardRule() const
  263. {
  264. return TerrainViewPattern::RULE_ANY == name || TerrainViewPattern::RULE_DIRT == name
  265. || TerrainViewPattern::RULE_NATIVE == name || TerrainViewPattern::RULE_SAND == name
  266. || TerrainViewPattern::RULE_TRANSITION == name || TerrainViewPattern::RULE_NATIVE_STRONG == name;
  267. }
  268. CTerrainViewPatternConfig::CTerrainViewPatternConfig()
  269. {
  270. const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
  271. static const std::string patternTypes[] = { "terrainView", "terrainType" };
  272. for(int i = 0; i < ARRAY_COUNT(patternTypes); ++i)
  273. {
  274. const auto & patternsVec = config[patternTypes[i]].Vector();
  275. for(const auto & ptrnNode : patternsVec)
  276. {
  277. TerrainViewPattern pattern;
  278. // Read pattern data
  279. const JsonVector & data = ptrnNode["data"].Vector();
  280. assert(data.size() == 9);
  281. for(int j = 0; j < data.size(); ++j)
  282. {
  283. std::string cell = data[j].String();
  284. boost::algorithm::erase_all(cell, " ");
  285. std::vector<std::string> rules;
  286. boost::split(rules, cell, boost::is_any_of(","));
  287. for(std::string ruleStr : rules)
  288. {
  289. std::vector<std::string> ruleParts;
  290. boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
  291. TerrainViewPattern::WeightedRule rule;
  292. rule.name = ruleParts[0];
  293. assert(!rule.name.empty());
  294. if(ruleParts.size() > 1)
  295. {
  296. rule.points = boost::lexical_cast<int>(ruleParts[1]);
  297. }
  298. pattern.data[j].push_back(rule);
  299. }
  300. }
  301. // Read various properties
  302. pattern.id = ptrnNode["id"].String();
  303. assert(!pattern.id.empty());
  304. pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
  305. pattern.maxPoints = static_cast<int>(ptrnNode["maxPoints"].Float());
  306. if(pattern.maxPoints == 0) pattern.maxPoints = std::numeric_limits<int>::max();
  307. // Read mapping
  308. if(i == 0)
  309. {
  310. const auto & mappingStruct = ptrnNode["mapping"].Struct();
  311. for(const auto & mappingPair : mappingStruct)
  312. {
  313. TerrainViewPattern terGroupPattern = pattern;
  314. auto mappingStr = mappingPair.second.String();
  315. boost::algorithm::erase_all(mappingStr, " ");
  316. auto colonIndex = mappingStr.find_first_of(":");
  317. const auto & flipMode = mappingStr.substr(0, colonIndex);
  318. terGroupPattern.diffImages = TerrainViewPattern::FLIP_MODE_DIFF_IMAGES == &(flipMode[flipMode.length() - 1]);
  319. if(terGroupPattern.diffImages)
  320. {
  321. terGroupPattern.rotationTypesCount = boost::lexical_cast<int>(flipMode.substr(0, flipMode.length() - 1));
  322. assert(terGroupPattern.rotationTypesCount == 2 || terGroupPattern.rotationTypesCount == 4);
  323. }
  324. mappingStr = mappingStr.substr(colonIndex + 1);
  325. std::vector<std::string> mappings;
  326. boost::split(mappings, mappingStr, boost::is_any_of(","));
  327. for(std::string mapping : mappings)
  328. {
  329. std::vector<std::string> range;
  330. boost::split(range, mapping, boost::is_any_of("-"));
  331. terGroupPattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
  332. boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
  333. }
  334. // Add pattern to the patterns map
  335. const auto & terGroup = getTerrainGroup(mappingPair.first);
  336. terrainViewPatterns[terGroup].push_back(terGroupPattern);
  337. }
  338. }
  339. else if(i == 1)
  340. {
  341. terrainTypePatterns[pattern.id] = pattern;
  342. }
  343. }
  344. }
  345. }
  346. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  347. {
  348. }
  349. ETerrainGroup::ETerrainGroup CTerrainViewPatternConfig::getTerrainGroup(const std::string & terGroup) const
  350. {
  351. static const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups =
  352. {
  353. {"normal", ETerrainGroup::NORMAL},
  354. {"dirt", ETerrainGroup::DIRT},
  355. {"sand", ETerrainGroup::SAND},
  356. {"water", ETerrainGroup::WATER},
  357. {"rock", ETerrainGroup::ROCK},
  358. };
  359. auto it = terGroups.find(terGroup);
  360. if(it == terGroups.end()) throw std::runtime_error(boost::str(boost::format("Terrain group '%s' does not exist.") % terGroup));
  361. return it->second;
  362. }
  363. const std::vector<TerrainViewPattern> & CTerrainViewPatternConfig::getTerrainViewPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
  364. {
  365. return terrainViewPatterns.find(terGroup)->second;
  366. }
  367. boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  368. {
  369. const std::vector<TerrainViewPattern> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
  370. for(const TerrainViewPattern & pattern : groupPatterns)
  371. {
  372. if(id == pattern.id)
  373. {
  374. return boost::optional<const TerrainViewPattern &>(pattern);
  375. }
  376. }
  377. return boost::optional<const TerrainViewPattern &>();
  378. }
  379. const TerrainViewPattern & CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
  380. {
  381. auto it = terrainTypePatterns.find(id);
  382. assert(it != terrainTypePatterns.end());
  383. return it->second;
  384. }
  385. CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, ETerrainType terType, CRandomGenerator * gen)
  386. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  387. {
  388. }
  389. void CDrawTerrainOperation::execute()
  390. {
  391. for(const auto & pos : terrainSel.getSelectedItems())
  392. {
  393. auto & tile = map->getTile(pos);
  394. tile.terType = terType;
  395. invalidateTerrainViews(pos);
  396. }
  397. updateTerrainTypes();
  398. updateTerrainViews();
  399. //TODO add coastal bit to extTileFlags appropriately
  400. }
  401. void CDrawTerrainOperation::undo()
  402. {
  403. //TODO
  404. }
  405. void CDrawTerrainOperation::redo()
  406. {
  407. //TODO
  408. }
  409. std::string CDrawTerrainOperation::getLabel() const
  410. {
  411. return "Draw Terrain";
  412. }
  413. void CDrawTerrainOperation::updateTerrainTypes()
  414. {
  415. auto positions = terrainSel.getSelectedItems();
  416. while(!positions.empty())
  417. {
  418. const auto & centerPos = *(positions.begin());
  419. auto centerTile = map->getTile(centerPos);
  420. //logGlobal->debugStream() << boost::format("Set terrain tile at pos '%s' to type '%s'") % centerPos % centerTile.terType;
  421. auto tiles = getInvalidTiles(centerPos);
  422. auto updateTerrainType = [&](const int3 & pos)
  423. {
  424. map->getTile(pos).terType = centerTile.terType;
  425. positions.insert(pos);
  426. invalidateTerrainViews(pos);
  427. //logGlobal->debugStream() << boost::format("Set additional terrain tile at pos '%s' to type '%s'") % pos % centerTile.terType;
  428. };
  429. // Fill foreign invalid tiles
  430. for(const auto & tile : tiles.foreignTiles)
  431. {
  432. updateTerrainType(tile);
  433. }
  434. tiles = getInvalidTiles(centerPos);
  435. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  436. {
  437. // Blow up
  438. auto rect = extendTileAroundSafely(centerPos);
  439. std::set<int3> suitableTiles;
  440. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  441. bool centerPosValid = false;
  442. rect.forEach([&](const int3 & posToTest)
  443. {
  444. auto & terrainTile = map->getTile(posToTest);
  445. if(centerTile.terType != terrainTile.terType)
  446. {
  447. auto formerTerType = terrainTile.terType;
  448. terrainTile.terType = centerTile.terType;
  449. auto testTile = getInvalidTiles(posToTest);
  450. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : testTile.nativeTiles.size();
  451. bool putSuitableTile = false;
  452. bool addToSuitableTiles = false;
  453. if(testTile.centerPosValid)
  454. {
  455. if (!centerPosValid)
  456. {
  457. centerPosValid = true;
  458. putSuitableTile = true;
  459. }
  460. else
  461. {
  462. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  463. {
  464. putSuitableTile = true;
  465. }
  466. else
  467. {
  468. addToSuitableTiles = true;
  469. }
  470. }
  471. }
  472. else if (!centerPosValid)
  473. {
  474. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  475. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  476. {
  477. putSuitableTile = true;
  478. }
  479. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  480. {
  481. addToSuitableTiles = true;
  482. }
  483. }
  484. if (putSuitableTile)
  485. {
  486. //if(!suitableTiles.empty())
  487. //{
  488. // logGlobal->debugStream() << "Clear suitables tiles.";
  489. //}
  490. invalidNativeTilesCnt = nativeTilesCntNorm;
  491. invalidForeignTilesCnt = testTile.foreignTiles.size();
  492. suitableTiles.clear();
  493. addToSuitableTiles = true;
  494. }
  495. if (addToSuitableTiles)
  496. {
  497. suitableTiles.insert(posToTest);
  498. //logGlobal->debugStream() << boost::format(std::string("Found suitable tile '%s' for main tile '%s': ") +
  499. // "Invalid native tiles '%i', invalid foreign tiles '%i', centerPosValid '%i'") % posToTest % centerPos % testTile.nativeTiles.size() %
  500. // testTile.foreignTiles.size() % testTile.centerPosValid;
  501. }
  502. terrainTile.terType = formerTerType;
  503. }
  504. });
  505. if(suitableTiles.size() == 1)
  506. {
  507. updateTerrainType(*suitableTiles.begin());
  508. }
  509. else
  510. {
  511. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  512. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  513. for(auto & direction : directions)
  514. {
  515. auto it = suitableTiles.find(centerPos + direction);
  516. if(it != suitableTiles.end())
  517. {
  518. updateTerrainType(*it);
  519. break;
  520. }
  521. }
  522. }
  523. }
  524. else
  525. {
  526. // add invalid native tiles which are not in the positions list
  527. for(const auto & nativeTile : tiles.nativeTiles)
  528. {
  529. if(positions.find(nativeTile) == positions.end())
  530. {
  531. positions.insert(nativeTile);
  532. }
  533. }
  534. positions.erase(centerPos);
  535. }
  536. }
  537. }
  538. void CDrawTerrainOperation::updateTerrainViews()
  539. {
  540. for(const auto & pos : invalidatedTerViews)
  541. {
  542. const auto & patterns =
  543. VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));
  544. // Detect a pattern which fits best
  545. int bestPattern = -1;
  546. ValidationResult valRslt(false);
  547. for(int k = 0; k < patterns.size(); ++k)
  548. {
  549. const auto & pattern = patterns[k];
  550. valRslt = validateTerrainView(pos, pattern);
  551. if(valRslt.result)
  552. {
  553. /*logGlobal->debugStream() << boost::format("Pattern detected at pos '%s': Pattern '%s', Flip '%i', Repl. '%s'.") %
  554. pos % pattern.id % valRslt.flip % valRslt.transitionReplacement;*/
  555. bestPattern = k;
  556. break;
  557. }
  558. }
  559. //assert(bestPattern != -1);
  560. if(bestPattern == -1)
  561. {
  562. // This shouldn't be the case
  563. logGlobal->warnStream() << boost::format("No pattern detected at pos '%s'.") % pos;
  564. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  565. continue;
  566. }
  567. // Get mapping
  568. const TerrainViewPattern & pattern = patterns[bestPattern];
  569. std::pair<int, int> mapping;
  570. if(valRslt.transitionReplacement.empty())
  571. {
  572. mapping = pattern.mapping[0];
  573. }
  574. else
  575. {
  576. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  577. }
  578. // Set terrain view
  579. auto & tile = map->getTile(pos);
  580. if(!pattern.diffImages)
  581. {
  582. tile.terView = gen->nextInt(mapping.first, mapping.second);
  583. tile.extTileFlags = valRslt.flip;
  584. }
  585. else
  586. {
  587. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  588. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  589. int firstFrame = mapping.first + flip * framesPerRot;
  590. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  591. tile.extTileFlags = 0;
  592. }
  593. }
  594. }
  595. ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  596. {
  597. switch(terType)
  598. {
  599. case ETerrainType::DIRT:
  600. return ETerrainGroup::DIRT;
  601. case ETerrainType::SAND:
  602. return ETerrainGroup::SAND;
  603. case ETerrainType::WATER:
  604. return ETerrainGroup::WATER;
  605. case ETerrainType::ROCK:
  606. return ETerrainGroup::ROCK;
  607. default:
  608. return ETerrainGroup::NORMAL;
  609. }
  610. }
  611. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  612. {
  613. //constructor for pattern object is very expensive, but we can't manipulate const object :(
  614. auto flippedPattern = pattern;
  615. for(int flip = 0; flip < 4; ++flip)
  616. {
  617. if (flip > 0)
  618. flipPattern (flippedPattern, flip);
  619. auto valRslt = validateTerrainViewInner(pos, flippedPattern, recDepth);
  620. if(valRslt.result)
  621. {
  622. valRslt.flip = flip;
  623. return valRslt;
  624. }
  625. }
  626. return ValidationResult(false);
  627. }
  628. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth /*= 0*/) const
  629. {
  630. auto centerTerType = map->getTile(pos).terType;
  631. auto centerTerGroup = getTerrainGroup(centerTerType);
  632. int totalPoints = 0;
  633. std::string transitionReplacement;
  634. for(int i = 0; i < 9; ++i)
  635. {
  636. // The center, middle cell can be skipped
  637. if(i == 4)
  638. {
  639. continue;
  640. }
  641. // Get terrain group of the current cell
  642. int cx = pos.x + (i % 3) - 1;
  643. int cy = pos.y + (i / 3) - 1;
  644. int3 currentPos(cx, cy, pos.z);
  645. bool isAlien = false;
  646. ETerrainType terType;
  647. if(!map->isInTheMap(currentPos))
  648. {
  649. // position is not in the map, so take the ter type from the neighbor tile
  650. bool widthTooHigh = currentPos.x >= map->width;
  651. bool widthTooLess = currentPos.x < 0;
  652. bool heightTooHigh = currentPos.y >= map->height;
  653. bool heightTooLess = currentPos.y < 0;
  654. if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  655. {
  656. terType = centerTerType;
  657. }
  658. else if(widthTooHigh)
  659. {
  660. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  661. }
  662. else if(heightTooHigh)
  663. {
  664. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  665. }
  666. else if (widthTooLess)
  667. {
  668. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  669. }
  670. else if (heightTooLess)
  671. {
  672. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  673. }
  674. }
  675. else
  676. {
  677. terType = map->getTile(currentPos).terType;
  678. if(terType != centerTerType)
  679. {
  680. isAlien = true;
  681. }
  682. }
  683. // Validate all rules per cell
  684. int topPoints = -1;
  685. for(auto & elem : pattern.data[i])
  686. {
  687. TerrainViewPattern::WeightedRule rule = elem;
  688. if(!rule.isStandardRule())
  689. {
  690. if(recDepth == 0 && map->isInTheMap(currentPos))
  691. {
  692. if(terType == centerTerType)
  693. {
  694. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternById(getTerrainGroup(centerTerType), rule.name);
  695. if(patternForRule)
  696. {
  697. auto rslt = validateTerrainView(currentPos, *patternForRule, 1);
  698. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  699. }
  700. }
  701. continue;
  702. }
  703. else
  704. {
  705. rule.name = TerrainViewPattern::RULE_NATIVE;
  706. }
  707. }
  708. auto applyValidationRslt = [&](bool rslt)
  709. {
  710. if(rslt)
  711. {
  712. topPoints = std::max(topPoints, rule.points);
  713. }
  714. };
  715. // Validate cell with the ruleset of the pattern
  716. bool nativeTestOk, nativeTestStrongOk;
  717. nativeTestOk = nativeTestStrongOk = (rule.name == TerrainViewPattern::RULE_NATIVE_STRONG || rule.name == TerrainViewPattern::RULE_NATIVE) && !isAlien;
  718. if(centerTerGroup == ETerrainGroup::NORMAL)
  719. {
  720. bool dirtTestOk = (rule.name == TerrainViewPattern::RULE_DIRT || rule.name == TerrainViewPattern::RULE_TRANSITION)
  721. && isAlien && !isSandType(terType);
  722. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  723. && isSandType(terType);
  724. if(transitionReplacement.empty() && rule.name == TerrainViewPattern::RULE_TRANSITION
  725. && (dirtTestOk || sandTestOk))
  726. {
  727. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  728. }
  729. if(rule.name == TerrainViewPattern::RULE_TRANSITION)
  730. {
  731. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  732. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  733. }
  734. else
  735. {
  736. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || dirtTestOk || sandTestOk || nativeTestOk);
  737. }
  738. }
  739. else if(centerTerGroup == ETerrainGroup::DIRT)
  740. {
  741. nativeTestOk = rule.name == TerrainViewPattern::RULE_NATIVE && !isSandType(terType);
  742. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  743. && isSandType(terType);
  744. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk || nativeTestStrongOk);
  745. }
  746. else if(centerTerGroup == ETerrainGroup::SAND)
  747. {
  748. applyValidationRslt(true);
  749. }
  750. else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
  751. {
  752. bool sandTestOk = (rule.name == TerrainViewPattern::RULE_SAND || rule.name == TerrainViewPattern::RULE_TRANSITION)
  753. && isAlien;
  754. applyValidationRslt(rule.name == TerrainViewPattern::RULE_ANY || sandTestOk || nativeTestOk);
  755. }
  756. }
  757. if(topPoints == -1)
  758. {
  759. return ValidationResult(false);
  760. }
  761. else
  762. {
  763. totalPoints += topPoints;
  764. }
  765. }
  766. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  767. {
  768. return ValidationResult(true, transitionReplacement);
  769. }
  770. else
  771. {
  772. return ValidationResult(false);
  773. }
  774. }
  775. bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
  776. {
  777. switch(terType)
  778. {
  779. case ETerrainType::WATER:
  780. case ETerrainType::SAND:
  781. case ETerrainType::ROCK:
  782. return true;
  783. default:
  784. return false;
  785. }
  786. }
  787. void CDrawTerrainOperation::flipPattern(TerrainViewPattern & pattern, int flip) const
  788. {
  789. //flip in place to avoid expensive constructor. Seriously.
  790. if(flip == 0)
  791. {
  792. return;
  793. }
  794. //always flip horizontal
  795. for(int i = 0; i < 3; ++i)
  796. {
  797. int y = i * 3;
  798. std::swap(pattern.data[y], pattern.data[y + 2]);
  799. }
  800. //flip vertical only at 2nd step
  801. if(flip == FLIP_PATTERN_VERTICAL)
  802. {
  803. for(int i = 0; i < 3; ++i)
  804. {
  805. std::swap(pattern.data[i], pattern.data[6 + i]);
  806. }
  807. }
  808. }
  809. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  810. {
  811. auto rect = extendTileAroundSafely(centerPos);
  812. rect.forEach([&](const int3 & pos)
  813. {
  814. invalidatedTerViews.insert(pos);
  815. });
  816. }
  817. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  818. {
  819. InvalidTiles tiles;
  820. auto centerTerType = map->getTile(centerPos).terType;
  821. auto rect = extendTileAround(centerPos);
  822. rect.forEach([&](const int3 & pos)
  823. {
  824. if(map->isInTheMap(pos))
  825. {
  826. auto ptrConfig = VLC->terviewh;
  827. auto terType = map->getTile(pos).terType;
  828. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  829. // Special validity check for rock & water
  830. if(valid && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
  831. {
  832. static const std::string patternIds[] = { "s1", "s2" };
  833. for(auto & patternId : patternIds)
  834. {
  835. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  836. if(!valid) break;
  837. }
  838. }
  839. // Additional validity check for non rock OR water
  840. else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
  841. {
  842. static const std::string patternIds[] = { "n2", "n3" };
  843. for(auto & patternId : patternIds)
  844. {
  845. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  846. if(valid) break;
  847. }
  848. }
  849. if(!valid)
  850. {
  851. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  852. else tiles.foreignTiles.insert(pos);
  853. }
  854. else if(centerPos == pos)
  855. {
  856. tiles.centerPosValid = true;
  857. }
  858. }
  859. });
  860. return tiles;
  861. }
  862. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement /*= ""*/)
  863. : result(result), transitionReplacement(transitionReplacement)
  864. {
  865. }
  866. void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
  867. {
  868. logGlobal->debugStream() << "Printing detailed info about nearby map tiles of pos '" << pos << "'";
  869. for(int y = pos.y - 2; y <= pos.y + 2; ++y)
  870. {
  871. std::string line;
  872. const int PADDED_LENGTH = 10;
  873. for(int x = pos.x - 2; x <= pos.x + 2; ++x)
  874. {
  875. auto debugPos = int3(x, y, pos.z);
  876. if(map->isInTheMap(debugPos))
  877. {
  878. auto debugTile = map->getTile(debugPos);
  879. std::string terType = debugTile.terType.toString().substr(0, 6);
  880. line += terType;
  881. line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
  882. }
  883. else
  884. {
  885. line += "X";
  886. line.insert(line.end(), PADDED_LENGTH - 1, ' ');
  887. }
  888. }
  889. logGlobal->debugStream() << line;
  890. }
  891. }
  892. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  893. {
  894. CTerrainSelection terrainSel(map);
  895. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  896. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
  897. if(map->twoLevel)
  898. {
  899. terrainSel.clearSelection();
  900. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  901. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
  902. }
  903. }
  904. std::string CClearTerrainOperation::getLabel() const
  905. {
  906. return "Clear Terrain";
  907. }
  908. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj, const int3 & pos)
  909. : CMapOperation(map), pos(pos), obj(obj)
  910. {
  911. }
  912. void CInsertObjectOperation::execute()
  913. {
  914. obj->pos = pos;
  915. obj->id = ObjectInstanceID(map->objects.size());
  916. map->objects.push_back(obj);
  917. if(obj->ID == Obj::TOWN)
  918. {
  919. map->towns.push_back(static_cast<CGTownInstance *>(obj));
  920. }
  921. if(obj->ID == Obj::HERO)
  922. {
  923. map->heroesOnMap.push_back(static_cast<CGHeroInstance*>(obj));
  924. }
  925. map->addBlockVisTiles(obj);
  926. }
  927. void CInsertObjectOperation::undo()
  928. {
  929. //TODO
  930. }
  931. void CInsertObjectOperation::redo()
  932. {
  933. execute();
  934. }
  935. std::string CInsertObjectOperation::getLabel() const
  936. {
  937. return "Insert Object";
  938. }