CMapEditManager.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. //logGlobal->debugStream() << boost::format(std::string("Found suitable tile '%s' for main tile '%s': ") +
  567. // "Invalid native tiles '%i', invalid foreign tiles '%i', centerPosValid '%i'") % posToTest % centerPos % testTile.nativeTiles.size() %
  568. // testTile.foreignTiles.size() % testTile.centerPosValid;
  569. }
  570. terrainTile.terType = formerTerType;
  571. }
  572. });
  573. if(suitableTiles.size() == 1)
  574. {
  575. updateTerrainType(*suitableTiles.begin());
  576. }
  577. else
  578. {
  579. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  580. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0)};
  581. for(auto & direction : directions)
  582. {
  583. auto it = suitableTiles.find(centerPos + direction);
  584. if(it != suitableTiles.end())
  585. {
  586. updateTerrainType(*it);
  587. break;
  588. }
  589. }
  590. }
  591. }
  592. else
  593. {
  594. // add invalid native tiles which are not in the positions list
  595. for(const auto & nativeTile : tiles.nativeTiles)
  596. {
  597. if(positions.find(nativeTile) == positions.end())
  598. {
  599. positions.insert(nativeTile);
  600. }
  601. }
  602. positions.erase(centerPos);
  603. }
  604. }
  605. }
  606. void CDrawTerrainOperation::updateTerrainViews()
  607. {
  608. for(const auto & pos : invalidatedTerViews)
  609. {
  610. const auto & patterns = VLC->terviewh->getTerrainViewPatternsForGroup(getTerrainGroup(map->getTile(pos).terType));
  611. // Detect a pattern which fits best
  612. int bestPattern = -1;
  613. ValidationResult valRslt(false);
  614. for(int k = 0; k < patterns.size(); ++k)
  615. {
  616. const auto & pattern = patterns[k];
  617. //(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
  618. valRslt = validateTerrainView(pos, &pattern);
  619. if(valRslt.result)
  620. {
  621. /*logGlobal->debugStream() << boost::format("Pattern detected at pos '%s': Pattern '%s', Flip '%i', Repl. '%s'.") %
  622. pos % pattern.id % valRslt.flip % valRslt.transitionReplacement;*/
  623. bestPattern = k;
  624. break;
  625. }
  626. }
  627. //assert(bestPattern != -1);
  628. if(bestPattern == -1)
  629. {
  630. // This shouldn't be the case
  631. logGlobal->warn("No pattern detected at pos '%s'.", pos);
  632. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  633. continue;
  634. }
  635. // Get mapping
  636. const TerrainViewPattern & pattern = patterns[bestPattern][valRslt.flip];
  637. std::pair<int, int> mapping;
  638. if(valRslt.transitionReplacement.empty())
  639. {
  640. mapping = pattern.mapping[0];
  641. }
  642. else
  643. {
  644. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  645. }
  646. // Set terrain view
  647. auto & tile = map->getTile(pos);
  648. if(!pattern.diffImages)
  649. {
  650. tile.terView = gen->nextInt(mapping.first, mapping.second);
  651. tile.extTileFlags = valRslt.flip;
  652. }
  653. else
  654. {
  655. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  656. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  657. int firstFrame = mapping.first + flip * framesPerRot;
  658. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  659. tile.extTileFlags = 0;
  660. }
  661. }
  662. }
  663. ETerrainGroup::ETerrainGroup CDrawTerrainOperation::getTerrainGroup(ETerrainType terType) const
  664. {
  665. switch(terType)
  666. {
  667. case ETerrainType::DIRT:
  668. return ETerrainGroup::DIRT;
  669. case ETerrainType::SAND:
  670. return ETerrainGroup::SAND;
  671. case ETerrainType::WATER:
  672. return ETerrainGroup::WATER;
  673. case ETerrainType::ROCK:
  674. return ETerrainGroup::ROCK;
  675. default:
  676. return ETerrainGroup::NORMAL;
  677. }
  678. }
  679. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3 & pos, const std::vector<TerrainViewPattern> * pattern, int recDepth) const
  680. {
  681. for(int flip = 0; flip < 4; ++flip)
  682. {
  683. auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
  684. if(valRslt.result)
  685. {
  686. valRslt.flip = flip;
  687. return valRslt;
  688. }
  689. }
  690. return ValidationResult(false);
  691. }
  692. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3 & pos, const TerrainViewPattern & pattern, int recDepth) const
  693. {
  694. auto centerTerType = map->getTile(pos).terType;
  695. auto centerTerGroup = getTerrainGroup(centerTerType);
  696. int totalPoints = 0;
  697. std::string transitionReplacement;
  698. for(int i = 0; i < 9; ++i)
  699. {
  700. // The center, middle cell can be skipped
  701. if(i == 4)
  702. {
  703. continue;
  704. }
  705. // Get terrain group of the current cell
  706. int cx = pos.x + (i % 3) - 1;
  707. int cy = pos.y + (i / 3) - 1;
  708. int3 currentPos(cx, cy, pos.z);
  709. bool isAlien = false;
  710. ETerrainType terType;
  711. if(!map->isInTheMap(currentPos))
  712. {
  713. // position is not in the map, so take the ter type from the neighbor tile
  714. bool widthTooHigh = currentPos.x >= map->width;
  715. bool widthTooLess = currentPos.x < 0;
  716. bool heightTooHigh = currentPos.y >= map->height;
  717. bool heightTooLess = currentPos.y < 0;
  718. if ((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  719. {
  720. terType = centerTerType;
  721. }
  722. else if(widthTooHigh)
  723. {
  724. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  725. }
  726. else if(heightTooHigh)
  727. {
  728. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  729. }
  730. else if (widthTooLess)
  731. {
  732. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  733. }
  734. else if (heightTooLess)
  735. {
  736. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  737. }
  738. }
  739. else
  740. {
  741. terType = map->getTile(currentPos).terType;
  742. if(terType != centerTerType)
  743. {
  744. isAlien = true;
  745. }
  746. }
  747. // Validate all rules per cell
  748. int topPoints = -1;
  749. for(auto & elem : pattern.data[i])
  750. {
  751. TerrainViewPattern::WeightedRule rule = elem;
  752. if(!rule.isStandardRule())
  753. {
  754. if(recDepth == 0 && map->isInTheMap(currentPos))
  755. {
  756. if(terType == centerTerType)
  757. {
  758. const auto & group = getTerrainGroup(centerTerType);
  759. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(group, rule.name);
  760. if(auto p = patternForRule)
  761. {
  762. auto rslt = validateTerrainView(currentPos, &(*p), 1);
  763. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  764. }
  765. }
  766. continue;
  767. }
  768. else
  769. {
  770. rule.setNative();
  771. }
  772. }
  773. auto applyValidationRslt = [&](bool rslt)
  774. {
  775. if(rslt)
  776. {
  777. topPoints = std::max(topPoints, rule.points);
  778. }
  779. };
  780. // Validate cell with the ruleset of the pattern
  781. bool nativeTestOk, nativeTestStrongOk;
  782. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  783. if(centerTerGroup == ETerrainGroup::NORMAL)
  784. {
  785. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  786. && isAlien && !isSandType(terType);
  787. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  788. && isSandType(terType);
  789. if (transitionReplacement.empty() && rule.isTransition()
  790. && (dirtTestOk || sandTestOk))
  791. {
  792. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  793. }
  794. if (rule.isTransition())
  795. {
  796. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  797. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  798. }
  799. else
  800. {
  801. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  802. }
  803. }
  804. else if(centerTerGroup == ETerrainGroup::DIRT)
  805. {
  806. nativeTestOk = rule.isNativeRule() && !isSandType(terType);
  807. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  808. && isSandType(terType);
  809. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  810. }
  811. else if(centerTerGroup == ETerrainGroup::SAND)
  812. {
  813. applyValidationRslt(true);
  814. }
  815. else if(centerTerGroup == ETerrainGroup::WATER || centerTerGroup == ETerrainGroup::ROCK)
  816. {
  817. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  818. && isAlien;
  819. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  820. }
  821. }
  822. if(topPoints == -1)
  823. {
  824. return ValidationResult(false);
  825. }
  826. else
  827. {
  828. totalPoints += topPoints;
  829. }
  830. }
  831. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  832. {
  833. return ValidationResult(true, transitionReplacement);
  834. }
  835. else
  836. {
  837. return ValidationResult(false);
  838. }
  839. }
  840. bool CDrawTerrainOperation::isSandType(ETerrainType terType) const
  841. {
  842. switch(terType)
  843. {
  844. case ETerrainType::WATER:
  845. case ETerrainType::SAND:
  846. case ETerrainType::ROCK:
  847. return true;
  848. default:
  849. return false;
  850. }
  851. }
  852. void CDrawTerrainOperation::invalidateTerrainViews(const int3 & centerPos)
  853. {
  854. auto rect = extendTileAroundSafely(centerPos);
  855. rect.forEach([&](const int3 & pos)
  856. {
  857. invalidatedTerViews.insert(pos);
  858. });
  859. }
  860. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3 & centerPos) const
  861. {
  862. //TODO: this is very expensive function for RMG, needs optimization
  863. InvalidTiles tiles;
  864. auto centerTerType = map->getTile(centerPos).terType;
  865. auto rect = extendTileAround(centerPos);
  866. rect.forEach([&](const int3 & pos)
  867. {
  868. if(map->isInTheMap(pos))
  869. {
  870. auto ptrConfig = VLC->terviewh;
  871. auto terType = map->getTile(pos).terType;
  872. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  873. // Special validity check for rock & water
  874. if(valid && (terType == ETerrainType::WATER || terType == ETerrainType::ROCK))
  875. {
  876. static const std::string patternIds[] = { "s1", "s2" };
  877. for(auto & patternId : patternIds)
  878. {
  879. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  880. if(!valid) break;
  881. }
  882. }
  883. // Additional validity check for non rock OR water
  884. else if(!valid && (terType != ETerrainType::WATER && terType != ETerrainType::ROCK))
  885. {
  886. static const std::string patternIds[] = { "n2", "n3" };
  887. for(auto & patternId : patternIds)
  888. {
  889. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  890. if(valid) break;
  891. }
  892. }
  893. if(!valid)
  894. {
  895. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  896. else tiles.foreignTiles.insert(pos);
  897. }
  898. else if(centerPos == pos)
  899. {
  900. tiles.centerPosValid = true;
  901. }
  902. }
  903. });
  904. return tiles;
  905. }
  906. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string & transitionReplacement)
  907. : result(result), transitionReplacement(transitionReplacement), flip(0)
  908. {
  909. }
  910. void CTerrainViewPatternUtils::printDebuggingInfoAboutTile(const CMap * map, int3 pos)
  911. {
  912. logGlobal->debugStream() << "Printing detailed info about nearby map tiles of pos '" << pos << "'";
  913. for(int y = pos.y - 2; y <= pos.y + 2; ++y)
  914. {
  915. std::string line;
  916. const int PADDED_LENGTH = 10;
  917. for(int x = pos.x - 2; x <= pos.x + 2; ++x)
  918. {
  919. auto debugPos = int3(x, y, pos.z);
  920. if(map->isInTheMap(debugPos))
  921. {
  922. auto debugTile = map->getTile(debugPos);
  923. std::string terType = debugTile.terType.toString().substr(0, 6);
  924. line += terType;
  925. line.insert(line.end(), PADDED_LENGTH - terType.size(), ' ');
  926. }
  927. else
  928. {
  929. line += "X";
  930. line.insert(line.end(), PADDED_LENGTH - 1, ' ');
  931. }
  932. }
  933. logGlobal->debugStream() << line;
  934. }
  935. }
  936. CClearTerrainOperation::CClearTerrainOperation(CMap * map, CRandomGenerator * gen) : CComposedOperation(map)
  937. {
  938. CTerrainSelection terrainSel(map);
  939. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  940. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::WATER, gen));
  941. if(map->twoLevel)
  942. {
  943. terrainSel.clearSelection();
  944. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  945. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, ETerrainType::ROCK, gen));
  946. }
  947. }
  948. std::string CClearTerrainOperation::getLabel() const
  949. {
  950. return "Clear Terrain";
  951. }
  952. CInsertObjectOperation::CInsertObjectOperation(CMap * map, CGObjectInstance * obj)
  953. : CMapOperation(map), obj(obj)
  954. {
  955. }
  956. void CInsertObjectOperation::execute()
  957. {
  958. obj->id = ObjectInstanceID(map->objects.size());
  959. boost::format fmt("%s_%d");
  960. fmt % obj->typeName % obj->id.getNum();
  961. obj->instanceName = fmt.str();
  962. map->addNewObject(obj);
  963. }
  964. void CInsertObjectOperation::undo()
  965. {
  966. //TODO
  967. }
  968. void CInsertObjectOperation::redo()
  969. {
  970. execute();
  971. }
  972. std::string CInsertObjectOperation::getLabel() const
  973. {
  974. return "Insert Object";
  975. }