CMapEditManager.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  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(ETerrainType terType, CRandomGenerator * gen)
  200. {
  201. execute(make_unique<CDrawTerrainOperation>(map, terrainSel, terType, gen ? gen : &(this->gen)));
  202. terrainSel.clearSelection();
  203. }
  204. void CMapEditManager::drawRoad(ERoadType::ERoadType 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. const auto & terGroup = getTerrainGroup(mappingPair.first);
  355. std::vector<TerrainViewPattern> terrainViewPatternFlips;
  356. terrainViewPatternFlips.push_back(terGroupPattern);
  357. for (int i = 1; i < 4; ++i)
  358. {
  359. //auto p = terGroupPattern;
  360. flipPattern(terGroupPattern, i); //FIXME: we flip in place - doesn't make much sense now, but used to work
  361. terrainViewPatternFlips.push_back(terGroupPattern);
  362. }
  363. terrainViewPatterns[terGroup].push_back(terrainViewPatternFlips);
  364. }
  365. }
  366. else if(i == 1)
  367. {
  368. terrainTypePatterns[pattern.id].push_back(pattern);
  369. for (int i = 1; i < 4; ++i)
  370. {
  371. //auto p = pattern;
  372. flipPattern(pattern, i); ///FIXME: we flip in place - doesn't make much sense now
  373. terrainTypePatterns[pattern.id].push_back(pattern);
  374. }
  375. }
  376. }
  377. }
  378. }
  379. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  380. {
  381. }
  382. ETerrainGroup::ETerrainGroup CTerrainViewPatternConfig::getTerrainGroup(const std::string & terGroup) const
  383. {
  384. static const std::map<std::string, ETerrainGroup::ETerrainGroup> terGroups =
  385. {
  386. {"normal", ETerrainGroup::NORMAL},
  387. {"dirt", ETerrainGroup::DIRT},
  388. {"sand", ETerrainGroup::SAND},
  389. {"water", ETerrainGroup::WATER},
  390. {"rock", ETerrainGroup::ROCK},
  391. };
  392. auto it = terGroups.find(terGroup);
  393. if(it == terGroups.end()) throw std::runtime_error(boost::str(boost::format("Terrain group '%s' does not exist.") % terGroup));
  394. return it->second;
  395. }
  396. const std::vector<CTerrainViewPatternConfig::TVPVector> & CTerrainViewPatternConfig::getTerrainViewPatternsForGroup(ETerrainGroup::ETerrainGroup terGroup) const
  397. {
  398. return terrainViewPatterns.find(terGroup)->second;
  399. }
  400. boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  401. {
  402. const std::vector<TVPVector> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
  403. for (const TVPVector & patternFlips : groupPatterns)
  404. {
  405. const TerrainViewPattern & pattern = patternFlips.front();
  406. if(id == pattern.id)
  407. {
  408. return boost::optional<const TerrainViewPattern &>(pattern);
  409. }
  410. }
  411. return boost::optional<const TerrainViewPattern &>();
  412. }
  413. boost::optional<const CTerrainViewPatternConfig::TVPVector &> CTerrainViewPatternConfig::getTerrainViewPatternsById(ETerrainGroup::ETerrainGroup terGroup, const std::string & id) const
  414. {
  415. const std::vector<TVPVector> & groupPatterns = getTerrainViewPatternsForGroup(terGroup);
  416. for (const TVPVector & patternFlips : groupPatterns)
  417. {
  418. const TerrainViewPattern & pattern = patternFlips.front();
  419. if (id == pattern.id)
  420. {
  421. return boost::optional<const TVPVector &>(patternFlips);
  422. }
  423. }
  424. return boost::optional<const TVPVector &>();
  425. }
  426. const CTerrainViewPatternConfig::TVPVector * CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
  427. {
  428. auto it = terrainTypePatterns.find(id);
  429. assert(it != terrainTypePatterns.end());
  430. return &(it->second);
  431. }
  432. void CTerrainViewPatternConfig::flipPattern(TerrainViewPattern & pattern, int flip) const
  433. {
  434. //flip in place to avoid expensive constructor. Seriously.
  435. if (flip == 0)
  436. {
  437. return;
  438. }
  439. //always flip horizontal
  440. for (int i = 0; i < 3; ++i)
  441. {
  442. int y = i * 3;
  443. std::swap(pattern.data[y], pattern.data[y + 2]);
  444. }
  445. //flip vertical only at 2nd step
  446. if (flip == CMapOperation::FLIP_PATTERN_VERTICAL)
  447. {
  448. for (int i = 0; i < 3; ++i)
  449. {
  450. std::swap(pattern.data[i], pattern.data[6 + i]);
  451. }
  452. }
  453. }
  454. CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, ETerrainType terType, CRandomGenerator * gen)
  455. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  456. {
  457. }
  458. void CDrawTerrainOperation::execute()
  459. {
  460. for(const auto & pos : terrainSel.getSelectedItems())
  461. {
  462. auto & tile = map->getTile(pos);
  463. tile.terType = terType;
  464. invalidateTerrainViews(pos);
  465. }
  466. updateTerrainTypes();
  467. updateTerrainViews();
  468. }
  469. void CDrawTerrainOperation::undo()
  470. {
  471. //TODO
  472. }
  473. void CDrawTerrainOperation::redo()
  474. {
  475. //TODO
  476. }
  477. std::string CDrawTerrainOperation::getLabel() const
  478. {
  479. return "Draw Terrain";
  480. }
  481. void CDrawTerrainOperation::updateTerrainTypes()
  482. {
  483. auto positions = terrainSel.getSelectedItems();
  484. while(!positions.empty())
  485. {
  486. const auto & centerPos = *(positions.begin());
  487. auto centerTile = map->getTile(centerPos);
  488. //logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
  489. auto tiles = getInvalidTiles(centerPos);
  490. auto updateTerrainType = [&](const int3 & pos)
  491. {
  492. map->getTile(pos).terType = centerTile.terType;
  493. positions.insert(pos);
  494. invalidateTerrainViews(pos);
  495. //logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
  496. };
  497. // Fill foreign invalid tiles
  498. for(const auto & tile : tiles.foreignTiles)
  499. {
  500. updateTerrainType(tile);
  501. }
  502. tiles = getInvalidTiles(centerPos);
  503. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  504. {
  505. // Blow up
  506. auto rect = extendTileAroundSafely(centerPos);
  507. std::set<int3> suitableTiles;
  508. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  509. bool centerPosValid = false;
  510. rect.forEach([&](const int3 & posToTest)
  511. {
  512. auto & terrainTile = map->getTile(posToTest);
  513. if(centerTile.terType != terrainTile.terType)
  514. {
  515. auto formerTerType = terrainTile.terType;
  516. terrainTile.terType = centerTile.terType;
  517. auto testTile = getInvalidTiles(posToTest);
  518. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : testTile.nativeTiles.size();
  519. bool putSuitableTile = false;
  520. bool addToSuitableTiles = false;
  521. if(testTile.centerPosValid)
  522. {
  523. if (!centerPosValid)
  524. {
  525. centerPosValid = true;
  526. putSuitableTile = true;
  527. }
  528. else
  529. {
  530. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  531. {
  532. putSuitableTile = true;
  533. }
  534. else
  535. {
  536. addToSuitableTiles = true;
  537. }
  538. }
  539. }
  540. else if (!centerPosValid)
  541. {
  542. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  543. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  544. {
  545. putSuitableTile = true;
  546. }
  547. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  548. {
  549. addToSuitableTiles = true;
  550. }
  551. }
  552. if (putSuitableTile)
  553. {
  554. //if(!suitableTiles.empty())
  555. //{
  556. // logGlobal->debug("Clear suitables tiles.");
  557. //}
  558. invalidNativeTilesCnt = nativeTilesCntNorm;
  559. invalidForeignTilesCnt = testTile.foreignTiles.size();
  560. suitableTiles.clear();
  561. addToSuitableTiles = true;
  562. }
  563. if (addToSuitableTiles)
  564. {
  565. suitableTiles.insert(posToTest);
  566. }
  567. terrainTile.terType = formerTerType;
  568. }
  569. });
  570. if(suitableTiles.size() == 1)
  571. {
  572. updateTerrainType(*suitableTiles.begin());
  573. }
  574. else
  575. {
  576. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  577. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  578. for(auto & direction : directions)
  579. {
  580. auto it = suitableTiles.find(centerPos + direction);
  581. if(it != suitableTiles.end())
  582. {
  583. updateTerrainType(*it);
  584. break;
  585. }
  586. }
  587. }
  588. }
  589. else
  590. {
  591. // add invalid native tiles which are not in the positions list
  592. for(const auto & nativeTile : tiles.nativeTiles)
  593. {
  594. if(positions.find(nativeTile) == positions.end())
  595. {
  596. positions.insert(nativeTile);
  597. }
  598. }
  599. positions.erase(centerPos);
  600. }
  601. }
  602. }
  603. void CDrawTerrainOperation::updateTerrainViews()
  604. {
  605. for(const auto & pos : invalidatedTerViews)
  606. {
  607. const auto & patterns = VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));
  608. // Detect a pattern which fits best
  609. int bestPattern = -1;
  610. ValidationResult valRslt(false);
  611. for(int k = 0; k < patterns.size(); ++k)
  612. {
  613. const auto & pattern = patterns[k];
  614. //(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
  615. valRslt = validateTerrainView(pos, &pattern);
  616. if(valRslt.result)
  617. {
  618. bestPattern = k;
  619. break;
  620. }
  621. }
  622. //assert(bestPattern != -1);
  623. if(bestPattern == -1)
  624. {
  625. // This shouldn't be the case
  626. logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
  627. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  628. continue;
  629. }
  630. // Get mapping
  631. const TerrainViewPattern & pattern = patterns[bestPattern][valRslt.flip];
  632. std::pair<int, int> mapping;
  633. if(valRslt.transitionReplacement.empty())
  634. {
  635. mapping = pattern.mapping[0];
  636. }
  637. else
  638. {
  639. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  640. }
  641. // Set terrain view
  642. auto & tile = map->getTile(pos);
  643. if(!pattern.diffImages)
  644. {
  645. tile.terView = gen->nextInt(mapping.first, mapping.second);
  646. tile.extTileFlags = valRslt.flip;
  647. }
  648. else
  649. {
  650. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  651. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  652. int firstFrame = mapping.first + flip * framesPerRot;
  653. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  654. tile.extTileFlags = 0;
  655. }
  656. }
  657. }
  658. ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  659. {
  660. switch(terType)
  661. {
  662. case ETerrainType::DIRT:
  663. return ETerrainGroup::DIRT;
  664. case ETerrainType::SAND:
  665. return ETerrainGroup::SAND;
  666. case ETerrainType::WATER:
  667. return ETerrainGroup::WATER;
  668. case ETerrainType::ROCK:
  669. return ETerrainGroup::ROCK;
  670. default:
  671. return ETerrainGroup::NORMAL;
  672. }
  673. }
  674. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const std::vector<TerrainViewPattern> * pattern, int recDepth) const
  675. {
  676. for(int flip = 0; flip < 4; ++flip)
  677. {
  678. auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
  679. if(valRslt.result)
  680. {
  681. valRslt.flip = flip;
  682. return valRslt;
  683. }
  684. }
  685. return ValidationResult(false);
  686. }
  687. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth) const
  688. {
  689. auto centerTerType = map->getTile(pos).terType;
  690. auto centerTerGroup = getTerrainGroup(centerTerType);
  691. int totalPoints = 0;
  692. std::string transitionReplacement;
  693. for(int i = 0; i < 9; ++i)
  694. {
  695. // The center, middle cell can be skipped
  696. if(i == 4)
  697. {
  698. continue;
  699. }
  700. // Get terrain group of the current cell
  701. int cx = pos.x + (i % 3) - 1;
  702. int cy = pos.y + (i / 3) - 1;
  703. int3 currentPos(cx, cy, pos.z);
  704. bool isAlien = false;
  705. ETerrainType terType;
  706. if(!map->isInTheMap(currentPos))
  707. {
  708. // position is not in the map, so take the ter type from the neighbor tile
  709. bool widthTooHigh = currentPos.x >= map->width;
  710. bool widthTooLess = currentPos.x < 0;
  711. bool heightTooHigh = currentPos.y >= map->height;
  712. bool heightTooLess = currentPos.y < 0;
  713. if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  714. {
  715. terType = centerTerType;
  716. }
  717. else if(widthTooHigh)
  718. {
  719. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  720. }
  721. else if(heightTooHigh)
  722. {
  723. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  724. }
  725. else if (widthTooLess)
  726. {
  727. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  728. }
  729. else if (heightTooLess)
  730. {
  731. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  732. }
  733. }
  734. else
  735. {
  736. terType = map->getTile(currentPos).terType;
  737. if(terType != centerTerType)
  738. {
  739. isAlien = true;
  740. }
  741. }
  742. // Validate all rules per cell
  743. int topPoints = -1;
  744. for(auto & elem : pattern.data[i])
  745. {
  746. TerrainViewPattern::WeightedRule rule = elem;
  747. if(!rule.isStandardRule())
  748. {
  749. if(recDepth == 0 && map->isInTheMap(currentPos))
  750. {
  751. if(terType == centerTerType)
  752. {
  753. const auto & group = getTerrainGroup(centerTerType);
  754. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(group, rule.name);
  755. if(auto p = patternForRule)
  756. {
  757. auto rslt = validateTerrainView(currentPos, &(*p), 1);
  758. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  759. }
  760. }
  761. continue;
  762. }
  763. else
  764. {
  765. rule.setNative();
  766. }
  767. }
  768. auto applyValidationRslt = [&](bool rslt)
  769. {
  770. if(rslt)
  771. {
  772. topPoints = std::max(topPoints, rule.points);
  773. }
  774. };
  775. // Validate cell with the ruleset of the pattern
  776. bool nativeTestOk, nativeTestStrongOk;
  777. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  778. if(centerTerGroup == ETerrainGroup::NORMAL)
  779. {
  780. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  781. && isAlien && !isSandType(terType);
  782. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  783. && isSandType(terType);
  784. if (transitionReplacement.empty() && rule.isTransition()
  785. && (dirtTestOk || sandTestOk))
  786. {
  787. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  788. }
  789. if (rule.isTransition())
  790. {
  791. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  792. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  793. }
  794. else
  795. {
  796. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  797. }
  798. }
  799. else if(centerTerGroup == ETerrainGroup::DIRT)
  800. {
  801. nativeTestOk = rule.isNativeRule() && !isSandType(terType);
  802. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  803. && isSandType(terType);
  804. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  805. }
  806. else if(centerTerGroup == ETerrainGroup::SAND)
  807. {
  808. applyValidationRslt(true);
  809. }
  810. else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
  811. {
  812. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  813. && isAlien;
  814. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  815. }
  816. }
  817. if(topPoints == -1)
  818. {
  819. return ValidationResult(false);
  820. }
  821. else
  822. {
  823. totalPoints += topPoints;
  824. }
  825. }
  826. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  827. {
  828. return ValidationResult(true, transitionReplacement);
  829. }
  830. else
  831. {
  832. return ValidationResult(false);
  833. }
  834. }
  835. bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
  836. {
  837. switch(terType)
  838. {
  839. case ETerrainType::WATER:
  840. case ETerrainType::SAND:
  841. case ETerrainType::ROCK:
  842. return true;
  843. default:
  844. return false;
  845. }
  846. }
  847. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  848. {
  849. auto rect = extendTileAroundSafely(centerPos);
  850. rect.forEach([&](const int3 & pos)
  851. {
  852. invalidatedTerViews.insert(pos);
  853. });
  854. }
  855. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  856. {
  857. //TODO: this is very expensive function for RMG, needs optimization
  858. InvalidTiles tiles;
  859. auto centerTerType = map->getTile(centerPos).terType;
  860. auto rect = extendTileAround(centerPos);
  861. rect.forEach([&](const int3 & pos)
  862. {
  863. if(map->isInTheMap(pos))
  864. {
  865. auto ptrConfig = VLC->terviewh;
  866. auto terType = map->getTile(pos).terType;
  867. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  868. // Special validity check for rock & water
  869. if(valid && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
  870. {
  871. static const std::string patternIds[] = { "s1", "s2" };
  872. for(auto & patternId : patternIds)
  873. {
  874. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  875. if(!valid) break;
  876. }
  877. }
  878. // Additional validity check for non rock OR water
  879. else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
  880. {
  881. static const std::string patternIds[] = { "n2", "n3" };
  882. for(auto & patternId : patternIds)
  883. {
  884. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  885. if(valid) break;
  886. }
  887. }
  888. if(!valid)
  889. {
  890. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  891. else tiles.foreignTiles.insert(pos);
  892. }
  893. else if(centerPos == pos)
  894. {
  895. tiles.centerPosValid = true;
  896. }
  897. }
  898. });
  899. return tiles;
  900. }
  901. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement)
  902. : result(result), transitionReplacement(transitionReplacement), flip(0)
  903. {
  904. }
  905. void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
  906. {
  907. logGlobal->debug("Printing detailed info about nearby map tiles of pos '%s'", pos.toString());
  908. for(int y = pos.y - 2; y <= pos.y + 2; ++y)
  909. {
  910. std::string line;
  911. const int PADDED_LENGTH = 10;
  912. for(int x = pos.x - 2; x <= pos.x + 2; ++x)
  913. {
  914. auto debugPos = int3(x, y, pos.z);
  915. if(map->isInTheMap(debugPos))
  916. {
  917. auto debugTile = map->getTile(debugPos);
  918. std::string terType = debugTile.terType.toString().substr(0, 6);
  919. line += terType;
  920. line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
  921. }
  922. else
  923. {
  924. line += "X";
  925. line.insert(line.end(), PADDED_LENGTH - 1, ' ');
  926. }
  927. }
  928. logGlobal->debug(line);
  929. }
  930. }
  931. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  932. {
  933. CTerrainSelection terrainSel(map);
  934. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  935. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
  936. if(map->twoLevel)
  937. {
  938. terrainSel.clearSelection();
  939. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  940. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
  941. }
  942. }
  943. std::string CClearTerrainOperation::getLabel() const
  944. {
  945. return "Clear Terrain";
  946. }
  947. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj)
  948. : CMapOperation(map), obj(obj)
  949. {
  950. }
  951. void CInsertObjectOperation::execute()
  952. {
  953. obj->id = ObjectInstanceID(map->objects.size());
  954. boost::format fmt("%s_%d");
  955. fmt % obj->typeName % obj->id.getNum();
  956. obj->instanceName = fmt.str();
  957. map->addNewObject(obj);
  958. }
  959. void CInsertObjectOperation::undo()
  960. {
  961. //TODO
  962. }
  963. void CInsertObjectOperation::redo()
  964. {
  965. execute();
  966. }
  967. std::string CInsertObjectOperation::getLabel() const
  968. {
  969. return "Insert Object";
  970. }