CMapEditManager.cpp 28 KB

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