CMapEditManager.cpp 25 KB

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