CMapEditManager.cpp 28 KB

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