CMapEditManager.cpp 25 KB

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