CMapEditManager.cpp 27 KB

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