CMapOperation.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. /*
  2. * CMapOperation.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 "CMapOperation.h"
  12. #include "../VCMI_Lib.h"
  13. #include "CMap.h"
  14. #include "MapEditUtils.h"
  15. CMapOperation::CMapOperation(CMap* map) : map(map)
  16. {
  17. }
  18. std::string CMapOperation::getLabel() const
  19. {
  20. return "";
  21. }
  22. MapRect CMapOperation::extendTileAround(const int3& centerPos) const
  23. {
  24. return MapRect(int3(centerPos.x - 1, centerPos.y - 1, centerPos.z), 3, 3);
  25. }
  26. MapRect CMapOperation::extendTileAroundSafely(const int3& centerPos) const
  27. {
  28. return extendTileAround(centerPos) & MapRect(int3(0, 0, centerPos.z), map->width, map->height);
  29. }
  30. CComposedOperation::CComposedOperation(CMap* map) : CMapOperation(map)
  31. {
  32. }
  33. void CComposedOperation::execute()
  34. {
  35. for(auto & operation : operations)
  36. {
  37. operation->execute();
  38. }
  39. }
  40. void CComposedOperation::undo()
  41. {
  42. //reverse order
  43. for(auto operation = operations.rbegin(); operation != operations.rend(); operation++)
  44. {
  45. operation->get()->undo();
  46. }
  47. }
  48. void CComposedOperation::redo()
  49. {
  50. for(auto & operation : operations)
  51. {
  52. operation->redo();
  53. }
  54. }
  55. std::string CComposedOperation::getLabel() const
  56. {
  57. std::string ret = "Composed operation: ";
  58. for(auto & operation : operations)
  59. {
  60. ret.append(operation->getLabel() + ";");
  61. }
  62. return ret;
  63. }
  64. void CComposedOperation::addOperation(std::unique_ptr<CMapOperation>&& operation)
  65. {
  66. operations.push_back(std::move(operation));
  67. }
  68. CDrawTerrainOperation::CDrawTerrainOperation(CMap* map, const CTerrainSelection& terrainSel, Terrain terType, CRandomGenerator* gen)
  69. : CMapOperation(map), terrainSel(terrainSel), terType(terType), gen(gen)
  70. {
  71. }
  72. void CDrawTerrainOperation::execute()
  73. {
  74. for(const auto & pos : terrainSel.getSelectedItems())
  75. {
  76. auto & tile = map->getTile(pos);
  77. tile.terType = terType;
  78. invalidateTerrainViews(pos);
  79. }
  80. updateTerrainTypes();
  81. updateTerrainViews();
  82. }
  83. void CDrawTerrainOperation::undo()
  84. {
  85. //TODO
  86. }
  87. void CDrawTerrainOperation::redo()
  88. {
  89. //TODO
  90. }
  91. std::string CDrawTerrainOperation::getLabel() const
  92. {
  93. return "Draw Terrain";
  94. }
  95. void CDrawTerrainOperation::updateTerrainTypes()
  96. {
  97. auto positions = terrainSel.getSelectedItems();
  98. while(!positions.empty())
  99. {
  100. const auto & centerPos = *(positions.begin());
  101. auto centerTile = map->getTile(centerPos);
  102. //logGlobal->debug("Set terrain tile at pos '%s' to type '%s'", centerPos, centerTile.terType);
  103. auto tiles = getInvalidTiles(centerPos);
  104. auto updateTerrainType = [&](const int3& pos)
  105. {
  106. map->getTile(pos).terType = centerTile.terType;
  107. positions.insert(pos);
  108. invalidateTerrainViews(pos);
  109. //logGlobal->debug("Set additional terrain tile at pos '%s' to type '%s'", pos, centerTile.terType);
  110. };
  111. // Fill foreign invalid tiles
  112. for(const auto & tile : tiles.foreignTiles)
  113. {
  114. updateTerrainType(tile);
  115. }
  116. tiles = getInvalidTiles(centerPos);
  117. if(tiles.nativeTiles.find(centerPos) != tiles.nativeTiles.end())
  118. {
  119. // Blow up
  120. auto rect = extendTileAroundSafely(centerPos);
  121. std::set<int3> suitableTiles;
  122. int invalidForeignTilesCnt = std::numeric_limits<int>::max(), invalidNativeTilesCnt = 0;
  123. bool centerPosValid = false;
  124. rect.forEach([&](const int3& posToTest)
  125. {
  126. auto & terrainTile = map->getTile(posToTest);
  127. if(centerTile.terType != terrainTile.terType)
  128. {
  129. auto formerTerType = terrainTile.terType;
  130. terrainTile.terType = centerTile.terType;
  131. auto testTile = getInvalidTiles(posToTest);
  132. int nativeTilesCntNorm = testTile.nativeTiles.empty() ? std::numeric_limits<int>::max() : (int)testTile.nativeTiles.size();
  133. bool putSuitableTile = false;
  134. bool addToSuitableTiles = false;
  135. if(testTile.centerPosValid)
  136. {
  137. if(!centerPosValid)
  138. {
  139. centerPosValid = true;
  140. putSuitableTile = true;
  141. }
  142. else
  143. {
  144. if(testTile.foreignTiles.size() < invalidForeignTilesCnt)
  145. {
  146. putSuitableTile = true;
  147. }
  148. else
  149. {
  150. addToSuitableTiles = true;
  151. }
  152. }
  153. }
  154. else if(!centerPosValid)
  155. {
  156. if((nativeTilesCntNorm > invalidNativeTilesCnt) ||
  157. (nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() < invalidForeignTilesCnt))
  158. {
  159. putSuitableTile = true;
  160. }
  161. else if(nativeTilesCntNorm == invalidNativeTilesCnt && testTile.foreignTiles.size() == invalidForeignTilesCnt)
  162. {
  163. addToSuitableTiles = true;
  164. }
  165. }
  166. if(putSuitableTile)
  167. {
  168. //if(!suitableTiles.empty())
  169. //{
  170. // logGlobal->debug("Clear suitables tiles.");
  171. //}
  172. invalidNativeTilesCnt = nativeTilesCntNorm;
  173. invalidForeignTilesCnt = static_cast<int>(testTile.foreignTiles.size());
  174. suitableTiles.clear();
  175. addToSuitableTiles = true;
  176. }
  177. if(addToSuitableTiles)
  178. {
  179. suitableTiles.insert(posToTest);
  180. }
  181. terrainTile.terType = formerTerType;
  182. }
  183. });
  184. if(suitableTiles.size() == 1)
  185. {
  186. updateTerrainType(*suitableTiles.begin());
  187. }
  188. else
  189. {
  190. static const int3 directions[] = { int3(0, -1, 0), int3(-1, 0, 0), int3(0, 1, 0), int3(1, 0, 0),
  191. int3(-1, -1, 0), int3(-1, 1, 0), int3(1, 1, 0), int3(1, -1, 0) };
  192. for(auto & direction : directions)
  193. {
  194. auto it = suitableTiles.find(centerPos + direction);
  195. if (it != suitableTiles.end())
  196. {
  197. updateTerrainType(*it);
  198. break;
  199. }
  200. }
  201. }
  202. }
  203. else
  204. {
  205. // add invalid native tiles which are not in the positions list
  206. for(const auto & nativeTile : tiles.nativeTiles)
  207. {
  208. if (positions.find(nativeTile) == positions.end())
  209. {
  210. positions.insert(nativeTile);
  211. }
  212. }
  213. positions.erase(centerPos);
  214. }
  215. }
  216. }
  217. void CDrawTerrainOperation::updateTerrainViews()
  218. {
  219. for(const auto & pos : invalidatedTerViews)
  220. {
  221. const auto & patterns = VLC->terviewh->getTerrainViewPatterns(map->getTile(pos).terType);
  222. // Detect a pattern which fits best
  223. int bestPattern = -1;
  224. ValidationResult valRslt(false);
  225. for(int k = 0; k < patterns.size(); ++k)
  226. {
  227. const auto & pattern = patterns[k];
  228. //(ETerrainGroup::ETerrainGroup terGroup, const std::string & id)
  229. valRslt = validateTerrainView(pos, &pattern);
  230. if (valRslt.result)
  231. {
  232. bestPattern = k;
  233. break;
  234. }
  235. }
  236. //assert(bestPattern != -1);
  237. if(bestPattern == -1)
  238. {
  239. // This shouldn't be the case
  240. logGlobal->warn("No pattern detected at pos '%s'.", pos.toString());
  241. CTerrainViewPatternUtils::printDebuggingInfoAboutTile(map, pos);
  242. continue;
  243. }
  244. // Get mapping
  245. const TerrainViewPattern& pattern = patterns[bestPattern][valRslt.flip];
  246. std::pair<int, int> mapping;
  247. if(valRslt.transitionReplacement.empty())
  248. {
  249. mapping = pattern.mapping[0];
  250. }
  251. else
  252. {
  253. mapping = valRslt.transitionReplacement == TerrainViewPattern::RULE_DIRT ? pattern.mapping[0] : pattern.mapping[1];
  254. }
  255. // Set terrain view
  256. auto & tile = map->getTile(pos);
  257. if(!pattern.diffImages)
  258. {
  259. tile.terView = gen->nextInt(mapping.first, mapping.second);
  260. tile.extTileFlags = valRslt.flip;
  261. }
  262. else
  263. {
  264. const int framesPerRot = (mapping.second - mapping.first + 1) / pattern.rotationTypesCount;
  265. int flip = (pattern.rotationTypesCount == 2 && valRslt.flip == 2) ? 1 : valRslt.flip;
  266. int firstFrame = mapping.first + flip * framesPerRot;
  267. tile.terView = gen->nextInt(firstFrame, firstFrame + framesPerRot - 1);
  268. tile.extTileFlags = 0;
  269. }
  270. }
  271. }
  272. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainView(const int3& pos, const std::vector<TerrainViewPattern>* pattern, int recDepth) const
  273. {
  274. for(int flip = 0; flip < 4; ++flip)
  275. {
  276. auto valRslt = validateTerrainViewInner(pos, pattern->at(flip), recDepth);
  277. if(valRslt.result)
  278. {
  279. valRslt.flip = flip;
  280. return valRslt;
  281. }
  282. }
  283. return ValidationResult(false);
  284. }
  285. CDrawTerrainOperation::ValidationResult CDrawTerrainOperation::validateTerrainViewInner(const int3& pos, const TerrainViewPattern& pattern, int recDepth) const
  286. {
  287. auto centerTerType = map->getTile(pos).terType;
  288. int totalPoints = 0;
  289. std::string transitionReplacement;
  290. for(int i = 0; i < 9; ++i)
  291. {
  292. // The center, middle cell can be skipped
  293. if(i == 4)
  294. {
  295. continue;
  296. }
  297. // Get terrain group of the current cell
  298. int cx = pos.x + (i % 3) - 1;
  299. int cy = pos.y + (i / 3) - 1;
  300. int3 currentPos(cx, cy, pos.z);
  301. bool isAlien = false;
  302. Terrain terType;
  303. if(!map->isInTheMap(currentPos))
  304. {
  305. // position is not in the map, so take the ter type from the neighbor tile
  306. bool widthTooHigh = currentPos.x >= map->width;
  307. bool widthTooLess = currentPos.x < 0;
  308. bool heightTooHigh = currentPos.y >= map->height;
  309. bool heightTooLess = currentPos.y < 0;
  310. if((widthTooHigh && heightTooHigh) || (widthTooHigh && heightTooLess) || (widthTooLess && heightTooHigh) || (widthTooLess && heightTooLess))
  311. {
  312. terType = centerTerType;
  313. }
  314. else if(widthTooHigh)
  315. {
  316. terType = map->getTile(int3(currentPos.x - 1, currentPos.y, currentPos.z)).terType;
  317. }
  318. else if(heightTooHigh)
  319. {
  320. terType = map->getTile(int3(currentPos.x, currentPos.y - 1, currentPos.z)).terType;
  321. }
  322. else if(widthTooLess)
  323. {
  324. terType = map->getTile(int3(currentPos.x + 1, currentPos.y, currentPos.z)).terType;
  325. }
  326. else if(heightTooLess)
  327. {
  328. terType = map->getTile(int3(currentPos.x, currentPos.y + 1, currentPos.z)).terType;
  329. }
  330. }
  331. else
  332. {
  333. terType = map->getTile(currentPos).terType;
  334. if(terType != centerTerType && (terType.isPassable() || centerTerType.isPassable()))
  335. {
  336. isAlien = true;
  337. }
  338. }
  339. // Validate all rules per cell
  340. int topPoints = -1;
  341. for(auto & elem : pattern.data[i])
  342. {
  343. TerrainViewPattern::WeightedRule rule = elem;
  344. if(!rule.isStandardRule())
  345. {
  346. if(recDepth == 0 && map->isInTheMap(currentPos))
  347. {
  348. if(terType == centerTerType)
  349. {
  350. const auto & patternForRule = VLC->terviewh->getTerrainViewPatternsById(centerTerType, rule.name);
  351. if(auto p = patternForRule)
  352. {
  353. auto rslt = validateTerrainView(currentPos, &(*p), 1);
  354. if(rslt.result) topPoints = std::max(topPoints, rule.points);
  355. }
  356. }
  357. continue;
  358. }
  359. else
  360. {
  361. rule.setNative();
  362. }
  363. }
  364. auto applyValidationRslt = [&](bool rslt)
  365. {
  366. if(rslt)
  367. {
  368. topPoints = std::max(topPoints, rule.points);
  369. }
  370. };
  371. // Validate cell with the ruleset of the pattern
  372. bool nativeTestOk, nativeTestStrongOk;
  373. nativeTestOk = nativeTestStrongOk = (rule.isNativeStrong() || rule.isNativeRule()) && !isAlien;
  374. if(centerTerType == Terrain("dirt"))
  375. {
  376. nativeTestOk = rule.isNativeRule() && !terType.isTransitionRequired();
  377. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  378. && terType.isTransitionRequired();
  379. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk || nativeTestStrongOk);
  380. }
  381. else if(centerTerType == Terrain("sand"))
  382. {
  383. applyValidationRslt(true);
  384. }
  385. else if(centerTerType.isTransitionRequired()) //water, rock and some special terrains require sand transition
  386. {
  387. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  388. && isAlien;
  389. applyValidationRslt(rule.isAnyRule() || sandTestOk || nativeTestOk);
  390. }
  391. else
  392. {
  393. bool dirtTestOk = (rule.isDirtRule() || rule.isTransition())
  394. && isAlien && !terType.isTransitionRequired();
  395. bool sandTestOk = (rule.isSandRule() || rule.isTransition())
  396. && terType.isTransitionRequired();
  397. if(transitionReplacement.empty() && rule.isTransition()
  398. && (dirtTestOk || sandTestOk))
  399. {
  400. transitionReplacement = dirtTestOk ? TerrainViewPattern::RULE_DIRT : TerrainViewPattern::RULE_SAND;
  401. }
  402. if(rule.isTransition())
  403. {
  404. applyValidationRslt((dirtTestOk && transitionReplacement != TerrainViewPattern::RULE_SAND) ||
  405. (sandTestOk && transitionReplacement != TerrainViewPattern::RULE_DIRT));
  406. }
  407. else
  408. {
  409. applyValidationRslt(rule.isAnyRule() || dirtTestOk || sandTestOk || nativeTestOk);
  410. }
  411. }
  412. }
  413. if(topPoints == -1)
  414. {
  415. return ValidationResult(false);
  416. }
  417. else
  418. {
  419. totalPoints += topPoints;
  420. }
  421. }
  422. if(totalPoints >= pattern.minPoints && totalPoints <= pattern.maxPoints)
  423. {
  424. return ValidationResult(true, transitionReplacement);
  425. }
  426. else
  427. {
  428. return ValidationResult(false);
  429. }
  430. }
  431. void CDrawTerrainOperation::invalidateTerrainViews(const int3& centerPos)
  432. {
  433. auto rect = extendTileAroundSafely(centerPos);
  434. rect.forEach([&](const int3& pos)
  435. {
  436. invalidatedTerViews.insert(pos);
  437. });
  438. }
  439. CDrawTerrainOperation::InvalidTiles CDrawTerrainOperation::getInvalidTiles(const int3& centerPos) const
  440. {
  441. //TODO: this is very expensive function for RMG, needs optimization
  442. InvalidTiles tiles;
  443. auto centerTerType = map->getTile(centerPos).terType;
  444. auto rect = extendTileAround(centerPos);
  445. rect.forEach([&](const int3& pos)
  446. {
  447. if(map->isInTheMap(pos))
  448. {
  449. auto ptrConfig = VLC->terviewh;
  450. auto terType = map->getTile(pos).terType;
  451. auto valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById("n1")).result;
  452. // Special validity check for rock & water
  453. if(valid && (terType.isWater() || !terType.isPassable()))
  454. {
  455. static const std::string patternIds[] = { "s1", "s2" };
  456. for(auto & patternId : patternIds)
  457. {
  458. valid = !validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  459. if(!valid) break;
  460. }
  461. }
  462. // Additional validity check for non rock OR water
  463. else if(!valid && (terType.isLand() && terType.isPassable()))
  464. {
  465. static const std::string patternIds[] = { "n2", "n3" };
  466. for (auto & patternId : patternIds)
  467. {
  468. valid = validateTerrainView(pos, ptrConfig->getTerrainTypePatternById(patternId)).result;
  469. if(valid) break;
  470. }
  471. }
  472. if(!valid)
  473. {
  474. if(terType == centerTerType) tiles.nativeTiles.insert(pos);
  475. else tiles.foreignTiles.insert(pos);
  476. }
  477. else if(centerPos == pos)
  478. {
  479. tiles.centerPosValid = true;
  480. }
  481. }
  482. });
  483. return tiles;
  484. }
  485. CDrawTerrainOperation::ValidationResult::ValidationResult(bool result, const std::string& transitionReplacement)
  486. : result(result), transitionReplacement(transitionReplacement), flip(0)
  487. {
  488. }
  489. CClearTerrainOperation::CClearTerrainOperation(CMap* map, CRandomGenerator* gen) : CComposedOperation(map)
  490. {
  491. CTerrainSelection terrainSel(map);
  492. terrainSel.selectRange(MapRect(int3(0, 0, 0), map->width, map->height));
  493. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain("water"), gen));
  494. if(map->twoLevel)
  495. {
  496. terrainSel.clearSelection();
  497. terrainSel.selectRange(MapRect(int3(0, 0, 1), map->width, map->height));
  498. addOperation(make_unique<CDrawTerrainOperation>(map, terrainSel, Terrain("rock"), gen));
  499. }
  500. }
  501. std::string CClearTerrainOperation::getLabel() const
  502. {
  503. return "Clear Terrain";
  504. }
  505. CInsertObjectOperation::CInsertObjectOperation(CMap* map, CGObjectInstance* obj)
  506. : CMapOperation(map), obj(obj)
  507. {
  508. }
  509. void CInsertObjectOperation::execute()
  510. {
  511. obj->id = ObjectInstanceID(map->objects.size());
  512. do
  513. {
  514. map->setUniqueInstanceName(obj);
  515. } while(vstd::contains(map->instanceNames, obj->instanceName));
  516. map->addNewObject(obj);
  517. }
  518. void CInsertObjectOperation::undo()
  519. {
  520. map->removeObject(obj);
  521. }
  522. void CInsertObjectOperation::redo()
  523. {
  524. execute();
  525. }
  526. std::string CInsertObjectOperation::getLabel() const
  527. {
  528. return "Insert Object";
  529. }
  530. CMoveObjectOperation::CMoveObjectOperation(CMap* map, CGObjectInstance* obj, const int3& targetPosition)
  531. : CMapOperation(map),
  532. obj(obj),
  533. initialPos(obj->pos),
  534. targetPos(targetPosition)
  535. {
  536. }
  537. void CMoveObjectOperation::execute()
  538. {
  539. map->moveObject(obj, targetPos);
  540. }
  541. void CMoveObjectOperation::undo()
  542. {
  543. map->moveObject(obj, initialPos);
  544. }
  545. void CMoveObjectOperation::redo()
  546. {
  547. execute();
  548. }
  549. std::string CMoveObjectOperation::getLabel() const
  550. {
  551. return "Move Object";
  552. }
  553. CRemoveObjectOperation::CRemoveObjectOperation(CMap* map, CGObjectInstance* obj)
  554. : CMapOperation(map), obj(obj)
  555. {
  556. }
  557. CRemoveObjectOperation::~CRemoveObjectOperation()
  558. {
  559. //when operation is destroyed and wasn't undone, the object is lost forever
  560. if(!obj)
  561. {
  562. return;
  563. }
  564. //do not destroy an object that belongs to map
  565. if(!vstd::contains(map->instanceNames, obj->instanceName))
  566. {
  567. delete obj;
  568. obj = nullptr;
  569. }
  570. }
  571. void CRemoveObjectOperation::execute()
  572. {
  573. map->removeObject(obj);
  574. }
  575. void CRemoveObjectOperation::undo()
  576. {
  577. try
  578. {
  579. //set new id, but do not rename object
  580. obj->id = ObjectInstanceID((si32)map->objects.size());
  581. map->addNewObject(obj);
  582. }
  583. catch(const std::exception& e)
  584. {
  585. logGlobal->error(e.what());
  586. }
  587. }
  588. void CRemoveObjectOperation::redo()
  589. {
  590. execute();
  591. }
  592. std::string CRemoveObjectOperation::getLabel() const
  593. {
  594. return "Remove Object";
  595. }