CMapEditManager.cpp 29 KB

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