CMapEditManager.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  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(const 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::drawRiver(const std::string & riverType, CRandomGenerator* gen)
  210. {
  211. execute(make_unique<CDrawRiversOperation>(map, terrainSel, riverType, gen ? gen : &(this->gen)));
  212. terrainSel.clearSelection();
  213. }
  214. void CMapEditManager::insertObject(CGObjectInstance * obj)
  215. {
  216. execute(make_unique<CInsertObjectOperation>(map, obj));
  217. }
  218. void CMapEditManager::execute(std::unique_ptr<CMapOperation> && operation)
  219. {
  220. operation->execute();
  221. undoManager.addOperation(std::move(operation));
  222. }
  223. CTerrainSelection & CMapEditManager::getTerrainSelection()
  224. {
  225. return terrainSel;
  226. }
  227. CObjectSelection & CMapEditManager::getObjectSelection()
  228. {
  229. return objectSel;
  230. }
  231. CMapUndoManager & CMapEditManager::getUndoManager()
  232. {
  233. return undoManager;
  234. }
  235. CComposedOperation::CComposedOperation(CMap * map) : CMapOperation(map)
  236. {
  237. }
  238. void CComposedOperation::execute()
  239. {
  240. for(auto & operation : operations)
  241. {
  242. operation->execute();
  243. }
  244. }
  245. void CComposedOperation::undo()
  246. {
  247. for(auto & operation : operations)
  248. {
  249. operation->undo();
  250. }
  251. }
  252. void CComposedOperation::redo()
  253. {
  254. for(auto & operation : operations)
  255. {
  256. operation->redo();
  257. }
  258. }
  259. void CComposedOperation::addOperation(std::unique_ptr<CMapOperation> && operation)
  260. {
  261. operations.push_back(std::move(operation));
  262. }
  263. const std::string TerrainViewPattern::FLIP_MODE_DIFF_IMAGES = "D";
  264. const std::string TerrainViewPattern::RULE_DIRT = "D";
  265. const std::string TerrainViewPattern::RULE_SAND = "S";
  266. const std::string TerrainViewPattern::RULE_TRANSITION = "T";
  267. const std::string TerrainViewPattern::RULE_NATIVE = "N";
  268. const std::string TerrainViewPattern::RULE_NATIVE_STRONG = "N!";
  269. const std::string TerrainViewPattern::RULE_ANY = "?";
  270. TerrainViewPattern::TerrainViewPattern() : diffImages(false), rotationTypesCount(0), minPoints(0)
  271. {
  272. maxPoints = std::numeric_limits<int>::max();
  273. }
  274. TerrainViewPattern::WeightedRule::WeightedRule(std::string &Name) : points(0), name(Name)
  275. {
  276. standardRule = (TerrainViewPattern::RULE_ANY == Name || TerrainViewPattern::RULE_DIRT == Name
  277. || TerrainViewPattern::RULE_NATIVE == Name || TerrainViewPattern::RULE_SAND == Name
  278. || TerrainViewPattern::RULE_TRANSITION == Name || TerrainViewPattern::RULE_NATIVE_STRONG == Name);
  279. anyRule = (Name == TerrainViewPattern::RULE_ANY);
  280. dirtRule = (Name == TerrainViewPattern::RULE_DIRT);
  281. sandRule = (Name == TerrainViewPattern::RULE_SAND);
  282. transitionRule = (Name == TerrainViewPattern::RULE_TRANSITION);
  283. nativeStrongRule = (Name == TerrainViewPattern::RULE_NATIVE_STRONG);
  284. nativeRule = (Name == TerrainViewPattern::RULE_NATIVE);
  285. }
  286. void TerrainViewPattern::WeightedRule::setNative()
  287. {
  288. nativeRule = true;
  289. standardRule = true;
  290. //TODO: would look better as a bitfield
  291. dirtRule = sandRule = transitionRule = nativeStrongRule = anyRule = false; //no idea what they mean, but look mutually exclusive
  292. }
  293. CTerrainViewPatternConfig::CTerrainViewPatternConfig()
  294. {
  295. const JsonNode config(ResourceID("config/terrainViewPatterns.json"));
  296. static const std::string patternTypes[] = { "terrainView", "terrainType" };
  297. for(int i = 0; i < ARRAY_COUNT(patternTypes); ++i)
  298. {
  299. const auto & patternsVec = config[patternTypes[i]].Vector();
  300. for(const auto & ptrnNode : patternsVec)
  301. {
  302. TerrainViewPattern pattern;
  303. // Read pattern data
  304. const JsonVector & data = ptrnNode["data"].Vector();
  305. assert(data.size() == 9);
  306. for(int j = 0; j < data.size(); ++j)
  307. {
  308. std::string cell = data[j].String();
  309. boost::algorithm::erase_all(cell, " ");
  310. std::vector<std::string> rules;
  311. boost::split(rules, cell, boost::is_any_of(","));
  312. for(std::string ruleStr : rules)
  313. {
  314. std::vector<std::string> ruleParts;
  315. boost::split(ruleParts, ruleStr, boost::is_any_of("-"));
  316. TerrainViewPattern::WeightedRule rule(ruleParts[0]);
  317. assert(!rule.name.empty());
  318. if(ruleParts.size() > 1)
  319. {
  320. rule.points = boost::lexical_cast<int>(ruleParts[1]);
  321. }
  322. pattern.data[j].push_back(rule);
  323. }
  324. }
  325. // Read various properties
  326. pattern.id = ptrnNode["id"].String();
  327. assert(!pattern.id.empty());
  328. pattern.minPoints = static_cast<int>(ptrnNode["minPoints"].Float());
  329. pattern.maxPoints = static_cast<int>(ptrnNode["maxPoints"].Float());
  330. if(pattern.maxPoints == 0) pattern.maxPoints = std::numeric_limits<int>::max();
  331. // Read mapping
  332. if(i == 0)
  333. {
  334. const auto & mappingStruct = ptrnNode["mapping"].Struct();
  335. for(const auto & mappingPair : mappingStruct)
  336. {
  337. TerrainViewPattern terGroupPattern = pattern;
  338. auto mappingStr = mappingPair.second.String();
  339. boost::algorithm::erase_all(mappingStr, " ");
  340. auto colonIndex = mappingStr.find_first_of(":");
  341. const auto & flipMode = mappingStr.substr(0, colonIndex);
  342. terGroupPattern.diffImages = TerrainViewPattern::FLIP_MODE_DIFF_IMAGES == &(flipMode[flipMode.length() - 1]);
  343. if(terGroupPattern.diffImages)
  344. {
  345. terGroupPattern.rotationTypesCount = boost::lexical_cast<int>(flipMode.substr(0, flipMode.length() - 1));
  346. assert(terGroupPattern.rotationTypesCount == 2 || terGroupPattern.rotationTypesCount == 4);
  347. }
  348. mappingStr = mappingStr.substr(colonIndex + 1);
  349. std::vector<std::string> mappings;
  350. boost::split(mappings, mappingStr, boost::is_any_of(","));
  351. for(std::string mapping : mappings)
  352. {
  353. std::vector<std::string> range;
  354. boost::split(range, mapping, boost::is_any_of("-"));
  355. terGroupPattern.mapping.push_back(std::make_pair(boost::lexical_cast<int>(range[0]),
  356. boost::lexical_cast<int>(range.size() > 1 ? range[1] : range[0])));
  357. }
  358. // Add pattern to the patterns map
  359. std::vector<TerrainViewPattern> terrainViewPatternFlips;
  360. terrainViewPatternFlips.push_back(terGroupPattern);
  361. for (int i = 1; i < 4; ++i)
  362. {
  363. //auto p = terGroupPattern;
  364. flipPattern(terGroupPattern, i); //FIXME: we flip in place - doesn't make much sense now, but used to work
  365. terrainViewPatternFlips.push_back(terGroupPattern);
  366. }
  367. terrainViewPatterns[mappingPair.first].push_back(terrainViewPatternFlips);
  368. }
  369. }
  370. else if(i == 1)
  371. {
  372. terrainTypePatterns[pattern.id].push_back(pattern);
  373. for (int i = 1; i < 4; ++i)
  374. {
  375. //auto p = pattern;
  376. flipPattern(pattern, i); ///FIXME: we flip in place - doesn't make much sense now
  377. terrainTypePatterns[pattern.id].push_back(pattern);
  378. }
  379. }
  380. }
  381. }
  382. }
  383. CTerrainViewPatternConfig::~CTerrainViewPatternConfig()
  384. {
  385. }
  386. const std::vector<CTerrainViewPatternConfig::TVPVector> & CTerrainViewPatternConfig::getTerrainViewPatterns(const Terrain & terrain) const
  387. {
  388. auto iter = terrainViewPatterns.find(Terrain::Manager::getInfo(terrain).terrainViewPatterns);
  389. if(iter == terrainViewPatterns.end())
  390. return terrainViewPatterns.at("normal");
  391. return iter->second;
  392. }
  393. boost::optional<const TerrainViewPattern &> CTerrainViewPatternConfig::getTerrainViewPatternById(std::string patternId, const std::string & id) const
  394. {
  395. auto iter = terrainViewPatterns.find(patternId);
  396. const std::vector<TVPVector> & groupPatterns = (iter == terrainViewPatterns.end()) ? terrainViewPatterns.at("normal") : iter->second;
  397. for (const TVPVector & patternFlips : groupPatterns)
  398. {
  399. const TerrainViewPattern & pattern = patternFlips.front();
  400. if(id == pattern.id)
  401. {
  402. return boost::optional<const TerrainViewPattern &>(pattern);
  403. }
  404. }
  405. return boost::optional<const TerrainViewPattern &>();
  406. }
  407. boost::optional<const CTerrainViewPatternConfig::TVPVector &> CTerrainViewPatternConfig::getTerrainViewPatternsById(const Terrain & terrain, const std::string & id) const
  408. {
  409. const std::vector<TVPVector> & groupPatterns = getTerrainViewPatterns(terrain);
  410. for (const TVPVector & patternFlips : groupPatterns)
  411. {
  412. const TerrainViewPattern & pattern = patternFlips.front();
  413. if (id == pattern.id)
  414. {
  415. return boost::optional<const TVPVector &>(patternFlips);
  416. }
  417. }
  418. return boost::optional<const TVPVector &>();
  419. }
  420. const CTerrainViewPatternConfig::TVPVector * CTerrainViewPatternConfig::getTerrainTypePatternById(const std::string & id) const
  421. {
  422. auto it = terrainTypePatterns.find(id);
  423. assert(it != terrainTypePatterns.end());
  424. return &(it->second);
  425. }
  426. void CTerrainViewPatternConfig::flipPattern(TerrainViewPattern & pattern, int flip) const
  427. {
  428. //flip in place to avoid expensive constructor. Seriously.
  429. if (flip == 0)
  430. {
  431. return;
  432. }
  433. //always flip horizontal
  434. for (int i = 0; i < 3; ++i)
  435. {
  436. int y = i * 3;
  437. std::swap(pattern.data[y], pattern.data[y + 2]);
  438. }
  439. //flip vertical only at 2nd step
  440. if (flip == CMapOperation::FLIP_PATTERN_VERTICAL)
  441. {
  442. for (int i = 0; i < 3; ++i)
  443. {
  444. std::swap(pattern.data[i], pattern.data[6 + i]);
  445. }
  446. }
  447. }
  448. CDrawTerrainOperation::CDrawTerrainOperation(CMap * map, const CTerrainSelection & terrainSel, Terrain terType, CRandomGenerator * gen)
  449. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  450. {
  451. }
  452. void CDrawTerrainOperation::execute()
  453. {
  454. for(const auto & pos : terrainSel.getSelectedItems())
  455. {
  456. auto & tile = map->getTile(pos);
  457. tile.terType = terType;
  458. invalidateTerrainViews(pos);
  459. }
  460. updateTerrainTypes();
  461. updateTerrainViews();
  462. }
  463. void CDrawTerrainOperation::undo()
  464. {
  465. //TODO
  466. }
  467. void CDrawTerrainOperation::redo()
  468. {
  469. //TODO
  470. }
  471. std::string CDrawTerrainOperation::getLabel() const
  472. {
  473. return "Draw Terrain";
  474. }
  475. void CDrawTerrainOperation::updateTerrainTypes()
  476. {
  477. auto positions = terrainSel.getSelectedItems();
  478. while(!positions.empty())
  479. {
  480. const auto & centerPos = *(positions.begin());
  481. auto centerTile = map->getTile(centerPos);
  482. //logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
  483. auto tiles = getInvalidTiles(centerPos);
  484. auto updateTerrainType = [&](const int3 & pos)
  485. {
  486. map->getTile(pos).terType = centerTile.terType;
  487. positions.insert(pos);
  488. invalidateTerrainViews(pos);
  489. //logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
  490. };
  491. // Fill foreign invalid tiles
  492. for(const auto & tile : tiles.foreignTiles)
  493. {
  494. updateTerrainType(tile);
  495. }
  496. tiles = getInvalidTiles(centerPos);
  497. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  498. {
  499. // Blow up
  500. auto rect = extendTileAroundSafely(centerPos);
  501. std::set<int3> suitableTiles;
  502. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  503. bool centerPosValid = false;
  504. rect.forEach([&](const int3 & posToTest)
  505. {
  506. auto & terrainTile = map->getTile(posToTest);
  507. if(centerTile.terType != terrainTile.terType)
  508. {
  509. auto formerTerType = terrainTile.terType;
  510. terrainTile.terType = centerTile.terType;
  511. auto testTile = getInvalidTiles(posToTest);
  512. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : (int)testTile.nativeTiles.size();
  513. bool putSuitableTile = false;
  514. bool addToSuitableTiles = false;
  515. if(testTile.centerPosValid)
  516. {
  517. if (!centerPosValid)
  518. {
  519. centerPosValid = true;
  520. putSuitableTile = true;
  521. }
  522. else
  523. {
  524. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  525. {
  526. putSuitableTile = true;
  527. }
  528. else
  529. {
  530. addToSuitableTiles = true;
  531. }
  532. }
  533. }
  534. else if (!centerPosValid)
  535. {
  536. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  537. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  538. {
  539. putSuitableTile = true;
  540. }
  541. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  542. {
  543. addToSuitableTiles = true;
  544. }
  545. }
  546. if (putSuitableTile)
  547. {
  548. //if(!suitableTiles.empty())
  549. //{
  550. // logGlobal->debug("Clear suitables tiles.");
  551. //}
  552. invalidNativeTilesCnt = nativeTilesCntNorm;
  553. invalidForeignTilesCnt = static_cast<int>(testTile.foreignTiles.size());
  554. suitableTiles.clear();
  555. addToSuitableTiles = true;
  556. }
  557. if (addToSuitableTiles)
  558. {
  559. suitableTiles.insert(posToTest);
  560. }
  561. terrainTile.terType = formerTerType;
  562. }
  563. });
  564. if(suitableTiles.size() == 1)
  565. {
  566. updateTerrainType(*suitableTiles.begin());
  567. }
  568. else
  569. {
  570. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  571. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  572. for(auto & direction : directions)
  573. {
  574. auto it = suitableTiles.find(centerPos + direction);
  575. if(it != suitableTiles.end())
  576. {
  577. updateTerrainType(*it);
  578. break;
  579. }
  580. }
  581. }
  582. }
  583. else
  584. {
  585. // add invalid native tiles which are not in the positions list
  586. for(const auto & nativeTile : tiles.nativeTiles)
  587. {
  588. if(positions.find(nativeTile) == positions.end())
  589. {
  590. positions.insert(nativeTile);
  591. }
  592. }
  593. positions.erase(centerPos);
  594. }
  595. }
  596. }
  597. void CDrawTerrainOperation::updateTerrainViews()
  598. {
  599. for(const auto & pos : invalidatedTerViews)
  600. {
  601. const auto & patterns = VLC->terviewh->getTerrainViewPatterns(map->getTile(pos).terType);
  602. // Detect a pattern which fits best
  603. int bestPattern = -1;
  604. ValidationResult valRslt(false);
  605. for(int k = 0; k < patterns.size(); ++k)
  606. {
  607. const auto & pattern = patterns[k];
  608. //(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
  609. valRslt = validateTerrainView(pos, &pattern);
  610. if(valRslt.result)
  611. {
  612. bestPattern = k;
  613. break;
  614. }
  615. }
  616. //assert(bestPattern != -1);
  617. if(bestPattern == -1)
  618. {
  619. // This shouldn't be the case
  620. logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
  621. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  622. continue;
  623. }
  624. // Get mapping
  625. const TerrainViewPattern & pattern = patterns[bestPattern][valRslt.flip];
  626. std::pair<int, int> mapping;
  627. if(valRslt.transitionReplacement.empty())
  628. {
  629. mapping = pattern.mapping[0];
  630. }
  631. else
  632. {
  633. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  634. }
  635. // Set terrain view
  636. auto & tile = map->getTile(pos);
  637. if(!pattern.diffImages)
  638. {
  639. tile.terView = gen->nextInt(mapping.first, mapping.second);
  640. tile.extTileFlags = valRslt.flip;
  641. }
  642. else
  643. {
  644. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  645. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  646. int firstFrame = mapping.first + flip * framesPerRot;
  647. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  648. tile.extTileFlags = 0;
  649. }
  650. }
  651. }
  652. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const std::vector<TerrainViewPattern> * pattern, int recDepth) const
  653. {
  654. for(int flip = 0; flip < 4; ++flip)
  655. {
  656. auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
  657. if(valRslt.result)
  658. {
  659. valRslt.flip = flip;
  660. return valRslt;
  661. }
  662. }
  663. return ValidationResult(false);
  664. }
  665. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth) const
  666. {
  667. auto centerTerType = map->getTile(pos).terType;
  668. int totalPoints = 0;
  669. std::string transitionReplacement;
  670. for(int i = 0; i < 9; ++i)
  671. {
  672. // The center, middle cell can be skipped
  673. if(i == 4)
  674. {
  675. continue;
  676. }
  677. // Get terrain group of the current cell
  678. int cx = pos.x + (i % 3) - 1;
  679. int cy = pos.y + (i / 3) - 1;
  680. int3 currentPos(cx, cy, pos.z);
  681. bool isAlien = false;
  682. Terrain terType;
  683. if(!map->isInTheMap(currentPos))
  684. {
  685. // position is not in the map, so take the ter type from the neighbor tile
  686. bool widthTooHigh = currentPos.x >= map->width;
  687. bool widthTooLess = currentPos.x < 0;
  688. bool heightTooHigh = currentPos.y >= map->height;
  689. bool heightTooLess = currentPos.y < 0;
  690. if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  691. {
  692. terType = centerTerType;
  693. }
  694. else if(widthTooHigh)
  695. {
  696. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  697. }
  698. else if(heightTooHigh)
  699. {
  700. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  701. }
  702. else if (widthTooLess)
  703. {
  704. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  705. }
  706. else if (heightTooLess)
  707. {
  708. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  709. }
  710. }
  711. else
  712. {
  713. terType = map->getTile(currentPos).terType;
  714. if(terType != centerTerType && (terType.isPassable() || centerTerType.isPassable()))
  715. {
  716. isAlien = true;
  717. }
  718. }
  719. // Validate all rules per cell
  720. int topPoints = -1;
  721. for(auto & elem : pattern.data[i])
  722. {
  723. TerrainViewPattern::WeightedRule rule = elem;
  724. if(!rule.isStandardRule())
  725. {
  726. if(recDepth == 0 && map->isInTheMap(currentPos))
  727. {
  728. if(terType == centerTerType)
  729. {
  730. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType, rule.name);
  731. if(auto p = patternForRule)
  732. {
  733. auto rslt = validateTerrainView(currentPos, &(*p), 1);
  734. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  735. }
  736. }
  737. continue;
  738. }
  739. else
  740. {
  741. rule.setNative();
  742. }
  743. }
  744. auto applyValidationRslt = [&](bool rslt)
  745. {
  746. if(rslt)
  747. {
  748. topPoints = std::max(topPoints, rule.points);
  749. }
  750. };
  751. // Validate cell with the ruleset of the pattern
  752. bool nativeTestOk, nativeTestStrongOk;
  753. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  754. if(centerTerType == Terrain("dirt"))
  755. {
  756. nativeTestOk = rule.isNativeRule() && !terType.isTransitionRequired();
  757. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  758. && terType.isTransitionRequired();
  759. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  760. }
  761. else if(centerTerType == Terrain("sand"))
  762. {
  763. applyValidationRslt(true);
  764. }
  765. else if(centerTerType.isTransitionRequired()) //water, rock and some special terrains require sand transition
  766. {
  767. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  768. && isAlien;
  769. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  770. }
  771. else
  772. {
  773. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  774. && isAlien && !terType.isTransitionRequired();
  775. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  776. && terType.isTransitionRequired();
  777. if (transitionReplacement.empty() && rule.isTransition()
  778. && (dirtTestOk || sandTestOk))
  779. {
  780. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  781. }
  782. if (rule.isTransition())
  783. {
  784. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  785. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  786. }
  787. else
  788. {
  789. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  790. }
  791. }
  792. }
  793. if(topPoints == -1)
  794. {
  795. return ValidationResult(false);
  796. }
  797. else
  798. {
  799. totalPoints += topPoints;
  800. }
  801. }
  802. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  803. {
  804. return ValidationResult(true, transitionReplacement);
  805. }
  806. else
  807. {
  808. return ValidationResult(false);
  809. }
  810. }
  811. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  812. {
  813. auto rect = extendTileAroundSafely(centerPos);
  814. rect.forEach([&](const int3 & pos)
  815. {
  816. invalidatedTerViews.insert(pos);
  817. });
  818. }
  819. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  820. {
  821. //TODO: this is very expensive function for RMG, needs optimization
  822. InvalidTiles tiles;
  823. auto centerTerType = map->getTile(centerPos).terType;
  824. auto rect = extendTileAround(centerPos);
  825. rect.forEach([&](const int3 & pos)
  826. {
  827. if(map->isInTheMap(pos))
  828. {
  829. auto ptrConfig = VLC->terviewh;
  830. auto terType = map->getTile(pos).terType;
  831. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  832. // Special validity check for rock & water
  833. if(valid && (terType.isWater() || !terType.isPassable()))
  834. {
  835. static const std::string patternIds[] = { "s1", "s2" };
  836. for(auto & patternId : patternIds)
  837. {
  838. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  839. if(!valid) break;
  840. }
  841. }
  842. // Additional validity check for non rock OR water
  843. else if(!valid && (terType.isLand() && terType.isPassable()))
  844. {
  845. static const std::string patternIds[] = { "n2", "n3" };
  846. for(auto & patternId : patternIds)
  847. {
  848. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  849. if(valid) break;
  850. }
  851. }
  852. if(!valid)
  853. {
  854. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  855. else tiles.foreignTiles.insert(pos);
  856. }
  857. else if(centerPos == pos)
  858. {
  859. tiles.centerPosValid = true;
  860. }
  861. }
  862. });
  863. return tiles;
  864. }
  865. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement)
  866. : result(result), transitionReplacement(transitionReplacement), flip(0)
  867. {
  868. }
  869. void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
  870. {
  871. logGlobal->debug("Printing detailed info about nearby map tiles of pos '%s'", pos.toString());
  872. for(int y = pos.y - 2; y <= pos.y + 2; ++y)
  873. {
  874. std::string line;
  875. const int PADDED_LENGTH = 10;
  876. for(int x = pos.x - 2; x <= pos.x + 2; ++x)
  877. {
  878. auto debugPos = int3(x, y, pos.z);
  879. if(map->isInTheMap(debugPos))
  880. {
  881. auto debugTile = map->getTile(debugPos);
  882. std::string terType = static_cast<std::string>(debugTile.terType).substr(0, 6);
  883. line += terType;
  884. line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
  885. }
  886. else
  887. {
  888. line += "X";
  889. line.insert(line.end(), PADDED_LENGTH - 1, ' ');
  890. }
  891. }
  892. logGlobal->debug(line);
  893. }
  894. }
  895. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  896. {
  897. CTerrainSelection terrainSel(map);
  898. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  899. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain("water"), gen));
  900. if(map->twoLevel)
  901. {
  902. terrainSel.clearSelection();
  903. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  904. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain("rock"), gen));
  905. }
  906. }
  907. std::string CClearTerrainOperation::getLabel() const
  908. {
  909. return "Clear Terrain";
  910. }
  911. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj)
  912. : CMapOperation(map), obj(obj)
  913. {
  914. }
  915. void CInsertObjectOperation::execute()
  916. {
  917. obj->id = ObjectInstanceID((si32)map->objects.size());
  918. boost::format fmt("%s_%d");
  919. fmt % obj->typeName % obj->id.getNum();
  920. obj->instanceName = fmt.str();
  921. map->addNewObject(obj);
  922. }
  923. void CInsertObjectOperation::undo()
  924. {
  925. //TODO
  926. }
  927. void CInsertObjectOperation::redo()
  928. {
  929. execute();
  930. }
  931. std::string CInsertObjectOperation::getLabel() const
  932. {
  933. return "Insert Object";
  934. }