CMapEditManager.cpp 28 KB

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