CMapEditManager.cpp 27 KB

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