CMapOperation.cpp 17 KB

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