mapcontroller.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /*
  2. * mapcontroller.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 "mapcontroller.h"
  12. #include "../lib/ArtifactUtils.h"
  13. #include "../lib/GameConstants.h"
  14. #include "../lib/mapObjectConstructors/AObjectTypeHandler.h"
  15. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  16. #include "../lib/mapObjects/ObjectTemplate.h"
  17. #include "../lib/mapping/CMapService.h"
  18. #include "../lib/mapping/CMap.h"
  19. #include "../lib/mapping/CMapEditManager.h"
  20. #include "../lib/mapping/ObstacleProxy.h"
  21. #include "../lib/modding/CModHandler.h"
  22. #include "../lib/modding/CModInfo.h"
  23. #include "../lib/TerrainHandler.h"
  24. #include "../lib/CSkillHandler.h"
  25. #include "../lib/spells/CSpellHandler.h"
  26. #include "../lib/CHeroHandler.h"
  27. #include "../lib/CRandomGenerator.h"
  28. #include "../lib/serializer/CMemorySerializer.h"
  29. #include "mapview.h"
  30. #include "scenelayer.h"
  31. #include "maphandler.h"
  32. #include "mainwindow.h"
  33. #include "inspector/inspector.h"
  34. #include "VCMI_Lib.h"
  35. MapController::MapController(MainWindow * m): main(m)
  36. {
  37. for(int i : {0, 1})
  38. {
  39. _scenes[i].reset(new MapScene(i));
  40. _miniscenes[i].reset(new MinimapScene(i));
  41. }
  42. connectScenes();
  43. }
  44. void MapController::connectScenes()
  45. {
  46. for (int level = 0; level <= 1; level++)
  47. {
  48. //selections for both layers will be handled separately
  49. QObject::connect(_scenes[level].get(), &MapScene::selected, [this, level](bool anythingSelected)
  50. {
  51. main->onSelectionMade(level, anythingSelected);
  52. });
  53. }
  54. }
  55. MapController::~MapController()
  56. {
  57. main = nullptr;
  58. }
  59. const std::unique_ptr<CMap> & MapController::getMapUniquePtr() const
  60. {
  61. return _map;
  62. }
  63. CMap * MapController::map()
  64. {
  65. return _map.get();
  66. }
  67. MapHandler * MapController::mapHandler()
  68. {
  69. return _mapHandler.get();
  70. }
  71. MapScene * MapController::scene(int level)
  72. {
  73. return _scenes[level].get();
  74. }
  75. MinimapScene * MapController::miniScene(int level)
  76. {
  77. return _miniscenes[level].get();
  78. }
  79. void MapController::repairMap()
  80. {
  81. repairMap(map());
  82. }
  83. void MapController::repairMap(CMap * map) const
  84. {
  85. if(!map)
  86. return;
  87. //make sure events/rumors has name to have proper identifiers
  88. int emptyNameId = 1;
  89. for(auto & e : map->events)
  90. if(e.name.empty())
  91. e.name = "event_" + std::to_string(emptyNameId++);
  92. emptyNameId = 1;
  93. for(auto & e : map->rumors)
  94. if(e.name.empty())
  95. e.name = "rumor_" + std::to_string(emptyNameId++);
  96. //fix owners for objects
  97. auto allImpactedObjects(map->objects);
  98. allImpactedObjects.insert(allImpactedObjects.end(), map->predefinedHeroes.begin(), map->predefinedHeroes.end());
  99. for(auto obj : allImpactedObjects)
  100. {
  101. //fix flags
  102. if(obj->getOwner() == PlayerColor::UNFLAGGABLE)
  103. {
  104. if(dynamic_cast<CGMine*>(obj.get()) ||
  105. dynamic_cast<CGDwelling*>(obj.get()) ||
  106. dynamic_cast<CGTownInstance*>(obj.get()) ||
  107. dynamic_cast<CGGarrison*>(obj.get()) ||
  108. dynamic_cast<CGShipyard*>(obj.get()) ||
  109. dynamic_cast<CGLighthouse*>(obj.get()) ||
  110. dynamic_cast<CGHeroInstance*>(obj.get()))
  111. obj->tempOwner = PlayerColor::NEUTRAL;
  112. }
  113. //fix hero instance
  114. if(auto * nih = dynamic_cast<CGHeroInstance*>(obj.get()))
  115. {
  116. // All heroes present on map or in prisons need to be allowed to rehire them after they are defeated
  117. // FIXME: How about custom scenarios where defeated hero cannot be hired again?
  118. map->allowedHeroes.insert(nih->getHeroTypeID());
  119. auto const & type = VLC->heroh->objects[nih->subID];
  120. assert(type->heroClass);
  121. if(nih->ID == Obj::HERO) //not prison
  122. nih->appearance = VLC->objtypeh->getHandlerFor(Obj::HERO, type->heroClass->getIndex())->getTemplates().front();
  123. //fix spellbook
  124. if(nih->spellbookContainsSpell(SpellID::SPELLBOOK_PRESET))
  125. {
  126. nih->removeSpellFromSpellbook(SpellID::SPELLBOOK_PRESET);
  127. if(!nih->getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook)
  128. nih->putArtifact(ArtifactPosition::SPELLBOOK, ArtifactUtils::createArtifact(ArtifactID::SPELLBOOK));
  129. }
  130. }
  131. //fix town instance
  132. if(auto * tnh = dynamic_cast<CGTownInstance*>(obj.get()))
  133. {
  134. if(tnh->getTown())
  135. {
  136. for(const auto & building : tnh->getBuildings())
  137. {
  138. if(!tnh->getTown()->buildings.count(building))
  139. tnh->removeBuilding(building);
  140. }
  141. vstd::erase_if(tnh->forbiddenBuildings, [tnh](BuildingID bid)
  142. {
  143. return !tnh->getTown()->buildings.count(bid);
  144. });
  145. }
  146. }
  147. //fix spell scrolls
  148. if(auto * art = dynamic_cast<CGArtifact*>(obj.get()))
  149. {
  150. if(art->ID == Obj::SPELL_SCROLL && !art->storedArtifact)
  151. {
  152. std::vector<SpellID> out;
  153. for(auto const & spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  154. {
  155. //if(map->isAllowedSpell(spell->id))
  156. {
  157. out.push_back(spell->id);
  158. }
  159. }
  160. auto a = ArtifactUtils::createScroll(*RandomGeneratorUtil::nextItem(out, CRandomGenerator::getDefault()));
  161. art->storedArtifact = a;
  162. }
  163. }
  164. //fix mines
  165. if(auto * mine = dynamic_cast<CGMine*>(obj.get()))
  166. {
  167. if(!mine->isAbandoned())
  168. {
  169. mine->producedResource = GameResID(mine->subID);
  170. mine->producedQuantity = mine->defaultResProduction();
  171. }
  172. }
  173. }
  174. }
  175. void MapController::setMap(std::unique_ptr<CMap> cmap)
  176. {
  177. _map = std::move(cmap);
  178. repairMap();
  179. for(int i : {0, 1})
  180. {
  181. _scenes[i].reset(new MapScene(i));
  182. _miniscenes[i].reset(new MinimapScene(i));
  183. }
  184. resetMapHandler();
  185. sceneForceUpdate();
  186. connectScenes();
  187. _map->getEditManager()->getUndoManager().setUndoCallback([this](bool allowUndo, bool allowRedo)
  188. {
  189. if(!main)
  190. return;
  191. main->enableUndo(allowUndo);
  192. main->enableRedo(allowRedo);
  193. }
  194. );
  195. _map->getEditManager()->getUndoManager().clearAll();
  196. initObstaclePainters(_map.get());
  197. }
  198. void MapController::initObstaclePainters(CMap * map)
  199. {
  200. for (auto const & terrain : VLC->terrainTypeHandler->objects)
  201. {
  202. auto terrainId = terrain->getId();
  203. _obstaclePainters[terrainId] = std::make_unique<EditorObstaclePlacer>(map);
  204. _obstaclePainters[terrainId]->collectPossibleObstacles(terrainId);
  205. }
  206. }
  207. void MapController::sceneForceUpdate()
  208. {
  209. _scenes[0]->updateViews();
  210. _miniscenes[0]->updateViews();
  211. if(_map->twoLevel)
  212. {
  213. _scenes[1]->updateViews();
  214. _miniscenes[1]->updateViews();
  215. }
  216. }
  217. void MapController::sceneForceUpdate(int level)
  218. {
  219. _scenes[level]->updateViews();
  220. _miniscenes[level]->updateViews();
  221. }
  222. void MapController::resetMapHandler()
  223. {
  224. if(!_mapHandler)
  225. _mapHandler.reset(new MapHandler());
  226. _mapHandler->reset(map());
  227. for(int i : {0, 1})
  228. {
  229. _scenes[i]->initialize(*this);
  230. _miniscenes[i]->initialize(*this);
  231. }
  232. }
  233. void MapController::commitTerrainChange(int level, const TerrainId & terrain)
  234. {
  235. static const int terrainDecorationPercentageLevel = 10;
  236. std::vector<int3> v(_scenes[level]->selectionTerrainView.selection().begin(),
  237. _scenes[level]->selectionTerrainView.selection().end());
  238. if(v.empty())
  239. return;
  240. _scenes[level]->selectionTerrainView.clear();
  241. _scenes[level]->selectionTerrainView.draw();
  242. _map->getEditManager()->getTerrainSelection().setSelection(v);
  243. _map->getEditManager()->drawTerrain(terrain, terrainDecorationPercentageLevel, &CRandomGenerator::getDefault());
  244. for(auto & t : v)
  245. _scenes[level]->terrainView.setDirty(t);
  246. _scenes[level]->terrainView.draw();
  247. _miniscenes[level]->updateViews();
  248. main->mapChanged();
  249. }
  250. void MapController::commitRoadOrRiverChange(int level, ui8 type, bool isRoad)
  251. {
  252. std::vector<int3> v(_scenes[level]->selectionTerrainView.selection().begin(),
  253. _scenes[level]->selectionTerrainView.selection().end());
  254. if(v.empty())
  255. return;
  256. _scenes[level]->selectionTerrainView.clear();
  257. _scenes[level]->selectionTerrainView.draw();
  258. _map->getEditManager()->getTerrainSelection().setSelection(v);
  259. if(isRoad)
  260. _map->getEditManager()->drawRoad(RoadId(type), &CRandomGenerator::getDefault());
  261. else
  262. _map->getEditManager()->drawRiver(RiverId(type), &CRandomGenerator::getDefault());
  263. for(auto & t : v)
  264. _scenes[level]->terrainView.setDirty(t);
  265. _scenes[level]->terrainView.draw();
  266. _miniscenes[level]->updateViews();
  267. main->mapChanged();
  268. }
  269. void MapController::commitObjectErase(int level)
  270. {
  271. auto selectedObjects = _scenes[level]->selectionObjectsView.getSelection();
  272. if (selectedObjects.size() > 1)
  273. {
  274. //mass erase => undo in one operation
  275. _map->getEditManager()->removeObjects(selectedObjects);
  276. }
  277. else if (selectedObjects.size() == 1)
  278. {
  279. _map->getEditManager()->removeObject(*selectedObjects.begin());
  280. }
  281. else //nothing to erase - shouldn't be here
  282. {
  283. return;
  284. }
  285. for (auto & obj : selectedObjects)
  286. {
  287. //invalidate tiles under objects
  288. _mapHandler->removeObject(obj);
  289. _scenes[level]->objectsView.setDirty(obj);
  290. }
  291. _scenes[level]->selectionObjectsView.clear();
  292. _scenes[level]->objectsView.draw();
  293. _scenes[level]->selectionObjectsView.draw();
  294. _scenes[level]->passabilityView.update();
  295. _miniscenes[level]->updateViews();
  296. main->mapChanged();
  297. }
  298. void MapController::copyToClipboard(int level)
  299. {
  300. _clipboard.clear();
  301. _clipboardShiftIndex = 0;
  302. auto selectedObjects = _scenes[level]->selectionObjectsView.getSelection();
  303. for(auto * obj : selectedObjects)
  304. {
  305. assert(obj->pos.z == level);
  306. _clipboard.push_back(CMemorySerializer::deepCopy(*obj));
  307. }
  308. }
  309. void MapController::pasteFromClipboard(int level)
  310. {
  311. _scenes[level]->selectionObjectsView.clear();
  312. auto shift = int3::getDirs()[_clipboardShiftIndex++];
  313. if(_clipboardShiftIndex == int3::getDirs().size())
  314. _clipboardShiftIndex = 0;
  315. QStringList errors;
  316. for(auto & objUniquePtr : _clipboard)
  317. {
  318. auto * obj = CMemorySerializer::deepCopy(*objUniquePtr).release();
  319. QString errorMsg;
  320. if (!canPlaceObject(level, obj, errorMsg))
  321. {
  322. errors.push_back(std::move(errorMsg));
  323. }
  324. auto newPos = objUniquePtr->pos + shift;
  325. if(_map->isInTheMap(newPos))
  326. obj->pos = newPos;
  327. obj->pos.z = level;
  328. Initializer init(obj, defaultPlayer);
  329. _map->getEditManager()->insertObject(obj);
  330. _scenes[level]->selectionObjectsView.selectObject(obj);
  331. _mapHandler->invalidate(obj);
  332. }
  333. QMessageBox::warning(main, QObject::tr("Can't place object"), errors.join('\n'));
  334. _scenes[level]->objectsView.draw();
  335. _scenes[level]->passabilityView.update();
  336. _scenes[level]->selectionObjectsView.draw();
  337. _miniscenes[level]->updateViews();
  338. main->mapChanged();
  339. }
  340. bool MapController::discardObject(int level) const
  341. {
  342. _scenes[level]->selectionObjectsView.clear();
  343. if(_scenes[level]->selectionObjectsView.newObject)
  344. {
  345. delete _scenes[level]->selectionObjectsView.newObject;
  346. _scenes[level]->selectionObjectsView.newObject = nullptr;
  347. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  348. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  349. _scenes[level]->selectionObjectsView.draw();
  350. return true;
  351. }
  352. return false;
  353. }
  354. void MapController::createObject(int level, CGObjectInstance * obj) const
  355. {
  356. _scenes[level]->selectionObjectsView.newObject = obj;
  357. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::MOVEMENT;
  358. _scenes[level]->selectionObjectsView.draw();
  359. }
  360. void MapController::commitObstacleFill(int level)
  361. {
  362. auto selection = _scenes[level]->selectionTerrainView.selection();
  363. if(selection.empty())
  364. return;
  365. //split by zones
  366. for (auto & painter : _obstaclePainters)
  367. {
  368. painter.second->clearBlockedArea();
  369. }
  370. for(auto & t : selection)
  371. {
  372. auto tl = _map->getTile(t);
  373. if(tl.blocked || tl.visitable)
  374. continue;
  375. auto terrain = tl.terType->getId();
  376. _obstaclePainters[terrain]->addBlockedTile(t);
  377. }
  378. for(auto & sel : _obstaclePainters)
  379. {
  380. for(auto * o : sel.second->placeObstacles(CRandomGenerator::getDefault()))
  381. {
  382. _mapHandler->invalidate(o);
  383. _scenes[level]->objectsView.setDirty(o);
  384. }
  385. }
  386. _scenes[level]->selectionTerrainView.clear();
  387. _scenes[level]->selectionTerrainView.draw();
  388. _scenes[level]->objectsView.draw();
  389. _scenes[level]->passabilityView.update();
  390. _miniscenes[level]->updateViews();
  391. main->mapChanged();
  392. }
  393. void MapController::commitObjectChange(int level)
  394. {
  395. for( auto * o : _scenes[level]->selectionObjectsView.getSelection())
  396. _scenes[level]->objectsView.setDirty(o);
  397. _scenes[level]->objectsView.draw();
  398. _scenes[level]->selectionObjectsView.draw();
  399. _scenes[level]->passabilityView.update();
  400. _miniscenes[level]->updateViews();
  401. main->mapChanged();
  402. }
  403. void MapController::commitChangeWithoutRedraw()
  404. {
  405. //DO NOT REDRAW
  406. main->mapChanged();
  407. }
  408. void MapController::commitObjectShift(int level)
  409. {
  410. auto shift = _scenes[level]->selectionObjectsView.shift;
  411. bool makeShift = !shift.isNull();
  412. if(makeShift)
  413. {
  414. for(auto * obj : _scenes[level]->selectionObjectsView.getSelection())
  415. {
  416. int3 pos = obj->pos;
  417. pos.z = level;
  418. pos.x += shift.x(); pos.y += shift.y();
  419. _scenes[level]->objectsView.setDirty(obj); //set dirty before movement
  420. _map->getEditManager()->moveObject(obj, pos);
  421. _mapHandler->invalidate(obj);
  422. }
  423. }
  424. _scenes[level]->selectionObjectsView.newObject = nullptr;
  425. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  426. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  427. if(makeShift)
  428. {
  429. _scenes[level]->objectsView.draw();
  430. _scenes[level]->selectionObjectsView.draw();
  431. _scenes[level]->passabilityView.update();
  432. _miniscenes[level]->updateViews();
  433. main->mapChanged();
  434. }
  435. }
  436. void MapController::commitObjectCreate(int level)
  437. {
  438. auto * newObj = _scenes[level]->selectionObjectsView.newObject;
  439. if(!newObj)
  440. return;
  441. auto shift = _scenes[level]->selectionObjectsView.shift;
  442. int3 pos = newObj->pos;
  443. pos.z = level;
  444. pos.x += shift.x(); pos.y += shift.y();
  445. newObj->pos = pos;
  446. Initializer init(newObj, defaultPlayer);
  447. _map->getEditManager()->insertObject(newObj);
  448. _mapHandler->invalidate(newObj);
  449. _scenes[level]->objectsView.setDirty(newObj);
  450. _scenes[level]->selectionObjectsView.newObject = nullptr;
  451. _scenes[level]->selectionObjectsView.shift = QPoint(0, 0);
  452. _scenes[level]->selectionObjectsView.selectionMode = SelectionObjectsLayer::NOTHING;
  453. _scenes[level]->objectsView.draw();
  454. _scenes[level]->selectionObjectsView.draw();
  455. _scenes[level]->passabilityView.update();
  456. _miniscenes[level]->updateViews();
  457. main->mapChanged();
  458. }
  459. bool MapController::canPlaceObject(int level, CGObjectInstance * newObj, QString & error) const
  460. {
  461. //find all objects of such type
  462. int objCounter = 0;
  463. for(auto o : _map->objects)
  464. {
  465. if(o->ID == newObj->ID && o->subID == newObj->subID)
  466. {
  467. ++objCounter;
  468. }
  469. }
  470. if(newObj->ID == Obj::GRAIL && objCounter >= 1) //special case for grail
  471. {
  472. error = QObject::tr("There can only be one grail object on the map.");
  473. return false; //maplimit reached
  474. }
  475. if(defaultPlayer == PlayerColor::NEUTRAL && (newObj->ID == Obj::HERO || newObj->ID == Obj::RANDOM_HERO))
  476. {
  477. error = QObject::tr("Hero %1 cannot be created as NEUTRAL.").arg(QString::fromStdString(newObj->instanceName));
  478. return false;
  479. }
  480. return true;
  481. }
  482. void MapController::undo()
  483. {
  484. _map->getEditManager()->getUndoManager().undo();
  485. resetMapHandler();
  486. sceneForceUpdate(); //TODO: use smart invalidation (setDirty)
  487. main->mapChanged();
  488. }
  489. void MapController::redo()
  490. {
  491. _map->getEditManager()->getUndoManager().redo();
  492. resetMapHandler();
  493. sceneForceUpdate(); //TODO: use smart invalidation (setDirty)
  494. main->mapChanged();
  495. }
  496. ModCompatibilityInfo MapController::modAssessmentAll()
  497. {
  498. ModCompatibilityInfo result;
  499. for(auto primaryID : VLC->objtypeh->knownObjects())
  500. {
  501. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  502. {
  503. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  504. auto modName = QString::fromStdString(handler->getJsonKey()).split(":").at(0).toStdString();
  505. if(modName != "core")
  506. result[modName] = VLC->modh->getModInfo(modName).getVerificationInfo();
  507. }
  508. }
  509. return result;
  510. }
  511. ModCompatibilityInfo MapController::modAssessmentMap(const CMap & map)
  512. {
  513. ModCompatibilityInfo result;
  514. auto extractEntityMod = [&result](const auto & entity)
  515. {
  516. auto modScope = entity->getModScope();
  517. if(modScope != "core")
  518. result[modScope] = VLC->modh->getModInfo(modScope).getVerificationInfo();
  519. };
  520. for(auto obj : map.objects)
  521. {
  522. auto handler = obj->getObjectHandler();
  523. auto modScope = handler->getModScope();
  524. if(modScope != "core")
  525. result[modScope] = VLC->modh->getModInfo(modScope).getVerificationInfo();
  526. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  527. {
  528. auto town = dynamic_cast<CGTownInstance *>(obj.get());
  529. for(const auto & spellID : town->possibleSpells)
  530. {
  531. if(spellID == SpellID::PRESET)
  532. continue;
  533. extractEntityMod(spellID.toEntity(VLC));
  534. }
  535. for(const auto & spellID : town->obligatorySpells)
  536. {
  537. extractEntityMod(spellID.toEntity(VLC));
  538. }
  539. }
  540. if(obj->ID == Obj::HERO || obj->ID == Obj::RANDOM_HERO)
  541. {
  542. auto hero = dynamic_cast<CGHeroInstance *>(obj.get());
  543. for(const auto & spellID : hero->getSpellsInSpellbook())
  544. {
  545. if(spellID == SpellID::PRESET || spellID == SpellID::SPELLBOOK_PRESET)
  546. continue;
  547. extractEntityMod(spellID.toEntity(VLC));
  548. }
  549. }
  550. }
  551. //TODO: terrains, artifacts?
  552. return result;
  553. }