mainwindow.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. /*
  2. * mainwindow.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 "mainwindow.h"
  12. #include "ui_mainwindow.h"
  13. #include <QFileDialog>
  14. #include <QFile>
  15. #include <QMessageBox>
  16. #include <QFileInfo>
  17. #include "../lib/VCMIDirs.h"
  18. #include "../lib/VCMI_Lib.h"
  19. #include "../lib/logging/CBasicLogConfigurator.h"
  20. #include "../lib/CConfigHandler.h"
  21. #include "../lib/filesystem/Filesystem.h"
  22. #include "../lib/GameConstants.h"
  23. #include "../lib/mapObjectConstructors/AObjectTypeHandler.h"
  24. #include "../lib/mapObjectConstructors/CObjectClassesHandler.h"
  25. #include "../lib/mapObjects/ObjectTemplate.h"
  26. #include "../lib/mapping/CMapService.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "../lib/mapping/CMapEditManager.h"
  29. #include "../lib/mapping/MapFormat.h"
  30. #include "../lib/modding/ModIncompatibility.h"
  31. #include "../lib/RoadHandler.h"
  32. #include "../lib/RiverHandler.h"
  33. #include "../lib/TerrainHandler.h"
  34. #include "../lib/filesystem/CFilesystemLoader.h"
  35. #include "maphandler.h"
  36. #include "graphics.h"
  37. #include "windownewmap.h"
  38. #include "objectbrowser.h"
  39. #include "inspector/inspector.h"
  40. #include "mapsettings/mapsettings.h"
  41. #include "mapsettings/translations.h"
  42. #include "playersettings.h"
  43. #include "validator.h"
  44. static CBasicLogConfigurator * logConfig;
  45. QJsonValue jsonFromPixmap(const QPixmap &p)
  46. {
  47. QBuffer buffer;
  48. buffer.open(QIODevice::WriteOnly);
  49. p.save(&buffer, "PNG");
  50. auto const encoded = buffer.data().toBase64();
  51. return {QLatin1String(encoded)};
  52. }
  53. QPixmap pixmapFromJson(const QJsonValue &val)
  54. {
  55. auto const encoded = val.toString().toLatin1();
  56. QPixmap p;
  57. p.loadFromData(QByteArray::fromBase64(encoded), "PNG");
  58. return p;
  59. }
  60. void init()
  61. {
  62. loadDLLClasses();
  63. Settings config = settings.write["session"]["editor"];
  64. config->Bool() = true;
  65. logGlobal->info("Initializing VCMI_Lib");
  66. }
  67. void MainWindow::loadUserSettings()
  68. {
  69. //load window settings
  70. QSettings s(Ui::teamName, Ui::appName);
  71. auto size = s.value(mainWindowSizeSetting).toSize();
  72. if (size.isValid())
  73. {
  74. resize(size);
  75. }
  76. auto position = s.value(mainWindowPositionSetting).toPoint();
  77. if (!position.isNull())
  78. {
  79. move(position);
  80. }
  81. }
  82. void MainWindow::saveUserSettings()
  83. {
  84. QSettings s(Ui::teamName, Ui::appName);
  85. s.setValue(mainWindowSizeSetting, size());
  86. s.setValue(mainWindowPositionSetting, pos());
  87. }
  88. void MainWindow::parseCommandLine(ExtractionOptions & extractionOptions)
  89. {
  90. QCommandLineParser parser;
  91. parser.addHelpOption();
  92. parser.addPositionalArgument("map", QCoreApplication::translate("main", "Filepath of the map to open."));
  93. parser.addOptions({
  94. {"e", QCoreApplication::translate("main", "Extract original H3 archives into a separate folder.")},
  95. {"s", QCoreApplication::translate("main", "From an extracted archive, it Splits TwCrPort, CPRSMALL, FlagPort, ITPA, ITPt, Un32 and Un44 into individual PNG's.")},
  96. {"c", QCoreApplication::translate("main", "From an extracted archive, Converts single Images (found in Images folder) from .pcx to png.")},
  97. {"d", QCoreApplication::translate("main", "Delete original files, for the ones split / converted.")},
  98. });
  99. parser.process(qApp->arguments());
  100. const QStringList positionalArgs = parser.positionalArguments();
  101. if(!positionalArgs.isEmpty())
  102. mapFilePath = positionalArgs.at(0);
  103. extractionOptions = {
  104. parser.isSet("e"), {
  105. parser.isSet("s"),
  106. parser.isSet("c"),
  107. parser.isSet("d")}};
  108. }
  109. void MainWindow::loadTranslation()
  110. {
  111. #ifdef ENABLE_QT_TRANSLATIONS
  112. std::string translationFile = settings["general"]["language"].String() + ".qm";
  113. QVector<QString> searchPaths;
  114. for(auto const & string : VCMIDirs::get().dataPaths())
  115. searchPaths.push_back(pathToQString(string / "mapeditor" / "translation" / translationFile));
  116. searchPaths.push_back(pathToQString(VCMIDirs::get().userDataPath() / "mapeditor" / "translation" / translationFile));
  117. for(auto const & string : boost::adaptors::reverse(searchPaths))
  118. {
  119. if (translator.load(string))
  120. {
  121. if (!qApp->installTranslator(&translator))
  122. logGlobal->error("Failed to install translator");
  123. return;
  124. }
  125. }
  126. logGlobal->error("Failed to find translation");
  127. #endif
  128. }
  129. MainWindow::MainWindow(QWidget* parent) :
  130. QMainWindow(parent),
  131. ui(new Ui::MainWindow),
  132. controller(this)
  133. {
  134. // Set current working dir to executable folder.
  135. // This is important on Mac for relative paths to work inside DMG.
  136. QDir::setCurrent(QApplication::applicationDirPath());
  137. for(auto & string : VCMIDirs::get().dataPaths())
  138. QDir::addSearchPath("icons", pathToQString(string / "mapeditor" / "icons"));
  139. QDir::addSearchPath("icons", pathToQString(VCMIDirs::get().userDataPath() / "mapeditor" / "icons"));
  140. new QShortcut(QKeySequence("Backspace"), this, SLOT(on_actionErase_triggered()));
  141. ExtractionOptions extractionOptions;
  142. parseCommandLine(extractionOptions);
  143. //configure logging
  144. const boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Editor_log.txt";
  145. console = new CConsoleHandler();
  146. logConfig = new CBasicLogConfigurator(logPath, console);
  147. logConfig->configureDefault();
  148. logGlobal->info("The log file will be saved to %s", logPath);
  149. //init
  150. preinitDLL(::console, extractionOptions.extractArchives);
  151. // Initialize logging based on settings
  152. logConfig->configure();
  153. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  154. // Some basic data validation to produce better error messages in cases of incorrect install
  155. auto testFile = [](std::string filename, std::string message) -> bool
  156. {
  157. if (CResourceHandler::get()->existsResource(ResourcePath(filename)))
  158. return true;
  159. logGlobal->error("Error: %s was not found!", message);
  160. return false;
  161. };
  162. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  163. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  164. {
  165. QApplication::quit();
  166. }
  167. loadTranslation();
  168. ui->setupUi(this);
  169. loadUserSettings(); //For example window size
  170. setTitle();
  171. init();
  172. graphics = new Graphics(); // should be before curh->init()
  173. graphics->load();//must be after Content loading but should be in main thread
  174. if (extractionOptions.extractArchives)
  175. ResourceConverter::convertExtractedResourceFiles(extractionOptions.conversionOptions);
  176. ui->mapView->setScene(controller.scene(0));
  177. ui->mapView->setController(&controller);
  178. ui->mapView->setOptimizationFlags(QGraphicsView::DontSavePainterState | QGraphicsView::DontAdjustForAntialiasing);
  179. connect(ui->mapView, &MapView::openObjectProperties, this, &MainWindow::loadInspector);
  180. connect(ui->mapView, &MapView::currentCoordinates, this, &MainWindow::currentCoordinatesChanged);
  181. ui->minimapView->setScene(controller.miniScene(0));
  182. ui->minimapView->setController(&controller);
  183. connect(ui->minimapView, &MinimapView::cameraPositionChanged, ui->mapView, &MapView::cameraChanged);
  184. scenePreview = new QGraphicsScene(this);
  185. ui->objectPreview->setScene(scenePreview);
  186. //loading objects
  187. loadObjectsTree();
  188. ui->tabWidget->setCurrentIndex(0);
  189. for(int i = 0; i < PlayerColor::PLAYER_LIMIT.getNum(); ++i)
  190. {
  191. connect(getActionPlayer(PlayerColor(i)), &QAction::toggled, this, [&, i](){switchDefaultPlayer(PlayerColor(i));});
  192. }
  193. connect(getActionPlayer(PlayerColor::NEUTRAL), &QAction::toggled, this, [&](){switchDefaultPlayer(PlayerColor::NEUTRAL);});
  194. onPlayersChanged();
  195. show();
  196. //Load map from command line
  197. if(!mapFilePath.isEmpty())
  198. openMap(mapFilePath);
  199. }
  200. MainWindow::~MainWindow()
  201. {
  202. saveUserSettings(); //save window size etc.
  203. delete ui;
  204. }
  205. bool MainWindow::getAnswerAboutUnsavedChanges()
  206. {
  207. if(unsaved)
  208. {
  209. auto sure = QMessageBox::question(this, tr("Confirmation"), tr("Unsaved changes will be lost, are you sure?"));
  210. if(sure == QMessageBox::No)
  211. {
  212. return false;
  213. }
  214. }
  215. return true;
  216. }
  217. void MainWindow::closeEvent(QCloseEvent *event)
  218. {
  219. if(getAnswerAboutUnsavedChanges())
  220. QMainWindow::closeEvent(event);
  221. else
  222. event->ignore();
  223. }
  224. void MainWindow::setStatusMessage(const QString & status)
  225. {
  226. statusBar()->showMessage(status);
  227. }
  228. void MainWindow::setTitle()
  229. {
  230. QString title = QString("%1%2 - %3 (v%4)").arg(filename, unsaved ? "*" : "", VCMI_EDITOR_NAME, VCMI_EDITOR_VERSION);
  231. setWindowTitle(title);
  232. }
  233. void MainWindow::mapChanged()
  234. {
  235. unsaved = true;
  236. setTitle();
  237. }
  238. void MainWindow::initializeMap(bool isNew)
  239. {
  240. unsaved = isNew;
  241. if(isNew)
  242. filename.clear();
  243. setTitle();
  244. mapLevel = 0;
  245. ui->mapView->setScene(controller.scene(mapLevel));
  246. ui->minimapView->setScene(controller.miniScene(mapLevel));
  247. ui->minimapView->dimensions();
  248. if(initialScale.isValid())
  249. on_actionZoom_reset_triggered();
  250. initialScale = ui->mapView->mapToScene(ui->mapView->viewport()->geometry()).boundingRect();
  251. //enable settings
  252. ui->actionMapSettings->setEnabled(true);
  253. ui->actionPlayers_settings->setEnabled(true);
  254. ui->actionTranslations->setEnabled(true);
  255. ui->actionLevel->setEnabled(controller.map()->twoLevel);
  256. //set minimal players count
  257. if(isNew)
  258. {
  259. controller.map()->players[0].canComputerPlay = true;
  260. controller.map()->players[0].canHumanPlay = true;
  261. }
  262. onPlayersChanged();
  263. }
  264. std::unique_ptr<CMap> MainWindow::openMapInternal(const QString & filenameSelect)
  265. {
  266. QFileInfo fi(filenameSelect);
  267. std::string fname = fi.fileName().toStdString();
  268. std::string fdir = fi.dir().path().toStdString();
  269. ResourcePath resId("MAPEDITOR/" + fname, EResType::MAP);
  270. //addFilesystem takes care about memory deallocation if case of failure, no memory leak here
  271. auto * mapEditorFilesystem = new CFilesystemLoader("MAPEDITOR/", fdir, 0);
  272. CResourceHandler::removeFilesystem("local", "mapEditor");
  273. CResourceHandler::addFilesystem("local", "mapEditor", mapEditorFilesystem);
  274. if(!CResourceHandler::get("mapEditor")->existsResource(resId))
  275. throw std::runtime_error("Cannot open map from this folder");
  276. CMapService mapService;
  277. if(auto header = mapService.loadMapHeader(resId))
  278. {
  279. auto missingMods = CMapService::verifyMapHeaderMods(*header);
  280. ModIncompatibility::ModListWithVersion modList;
  281. for(const auto & m : missingMods)
  282. modList.push_back({m.second.name, m.second.version.toString()});
  283. if(!modList.empty())
  284. throw ModIncompatibility(modList);
  285. return mapService.loadMap(resId);
  286. }
  287. else
  288. throw std::runtime_error("Corrupted map");
  289. }
  290. bool MainWindow::openMap(const QString & filenameSelect)
  291. {
  292. try
  293. {
  294. controller.setMap(openMapInternal(filenameSelect));
  295. }
  296. catch(const ModIncompatibility & e)
  297. {
  298. assert(e.whatExcessive().empty());
  299. QMessageBox::warning(this, "Mods are required", QString::fromStdString(e.whatMissing()));
  300. return false;
  301. }
  302. catch(const std::exception & e)
  303. {
  304. QMessageBox::critical(this, "Failed to open map", tr(e.what()));
  305. return false;
  306. }
  307. filename = filenameSelect;
  308. initializeMap(controller.map()->version != EMapFormat::VCMI);
  309. return true;
  310. }
  311. void MainWindow::on_actionOpen_triggered()
  312. {
  313. if(!getAnswerAboutUnsavedChanges())
  314. return;
  315. auto filenameSelect = QFileDialog::getOpenFileName(this, tr("Open map"),
  316. QString::fromStdString(VCMIDirs::get().userCachePath().make_preferred().string()),
  317. tr("All supported maps (*.vmap *.h3m);;VCMI maps(*.vmap);;HoMM3 maps(*.h3m)"));
  318. if(filenameSelect.isEmpty())
  319. return;
  320. openMap(filenameSelect);
  321. }
  322. void MainWindow::saveMap()
  323. {
  324. if(!controller.map())
  325. return;
  326. if(!unsaved)
  327. return;
  328. //validate map
  329. auto issues = Validator::validate(controller.map());
  330. bool critical = false;
  331. for(auto & issue : issues)
  332. critical |= issue.critical;
  333. if(!issues.empty())
  334. {
  335. if(critical)
  336. QMessageBox::warning(this, "Map validation", "Map has critical problems and most probably will not be playable. Open Validator from the Map menu to see issues found");
  337. else
  338. QMessageBox::information(this, "Map validation", "Map has some errors. Open Validator from the Map menu to see issues found");
  339. }
  340. Translations::cleanupRemovedItems(*controller.map());
  341. CMapService mapService;
  342. try
  343. {
  344. mapService.saveMap(controller.getMapUniquePtr(), filename.toStdString());
  345. }
  346. catch(const std::exception & e)
  347. {
  348. QMessageBox::critical(this, "Failed to save map", e.what());
  349. return;
  350. }
  351. unsaved = false;
  352. setTitle();
  353. }
  354. void MainWindow::on_actionSave_as_triggered()
  355. {
  356. if(!controller.map())
  357. return;
  358. auto filenameSelect = QFileDialog::getSaveFileName(this, tr("Save map"), lastSavingDir, tr("VCMI maps (*.vmap)"));
  359. if(filenameSelect.isNull())
  360. return;
  361. if(filenameSelect == filename)
  362. return;
  363. filename = filenameSelect;
  364. lastSavingDir = filenameSelect.remove(QUrl(filenameSelect).fileName());
  365. saveMap();
  366. }
  367. void MainWindow::on_actionNew_triggered()
  368. {
  369. if(getAnswerAboutUnsavedChanges())
  370. new WindowNewMap(this);
  371. }
  372. void MainWindow::on_actionSave_triggered()
  373. {
  374. if(!controller.map())
  375. return;
  376. if(filename.isNull())
  377. on_actionSave_as_triggered();
  378. else
  379. saveMap();
  380. }
  381. void MainWindow::currentCoordinatesChanged(int x, int y)
  382. {
  383. setStatusMessage(QString("x: %1 y: %2").arg(x).arg(y));
  384. }
  385. void MainWindow::terrainButtonClicked(TerrainId terrain)
  386. {
  387. controller.commitTerrainChange(mapLevel, terrain);
  388. }
  389. void MainWindow::roadOrRiverButtonClicked(ui8 type, bool isRoad)
  390. {
  391. controller.commitRoadOrRiverChange(mapLevel, type, isRoad);
  392. }
  393. void MainWindow::addGroupIntoCatalog(const std::string & groupName, bool staticOnly)
  394. {
  395. auto knownObjects = VLC->objtypeh->knownObjects();
  396. for(auto ID : knownObjects)
  397. {
  398. if(catalog.count(ID))
  399. continue;
  400. addGroupIntoCatalog(groupName, true, staticOnly, ID);
  401. }
  402. }
  403. void MainWindow::addGroupIntoCatalog(const std::string & groupName, bool useCustomName, bool staticOnly, int ID)
  404. {
  405. QStandardItem * itemGroup = nullptr;
  406. auto itms = objectsModel.findItems(QString::fromStdString(groupName));
  407. if(itms.empty())
  408. {
  409. itemGroup = new QStandardItem(QString::fromStdString(groupName));
  410. objectsModel.appendRow(itemGroup);
  411. }
  412. else
  413. {
  414. itemGroup = itms.front();
  415. }
  416. if (VLC->objtypeh->knownObjects().count(ID) == 0)
  417. return;
  418. auto knownSubObjects = VLC->objtypeh->knownSubObjects(ID);
  419. for(auto secondaryID : knownSubObjects)
  420. {
  421. auto factory = VLC->objtypeh->getHandlerFor(ID, secondaryID);
  422. auto templates = factory->getTemplates();
  423. bool singleTemplate = templates.size() == 1;
  424. if(staticOnly && !factory->isStaticObject())
  425. continue;
  426. auto subGroupName = QString::fromStdString(VLC->objtypeh->getObjectName(ID, secondaryID));
  427. auto * itemType = new QStandardItem(subGroupName);
  428. for(int templateId = 0; templateId < templates.size(); ++templateId)
  429. {
  430. auto templ = templates[templateId];
  431. //selecting file
  432. const AnimationPath & afile = templ->editorAnimationFile.empty() ? templ->animationFile : templ->editorAnimationFile;
  433. //creating picture
  434. QPixmap preview(128, 128);
  435. preview.fill(QColor(255, 255, 255));
  436. QPainter painter(&preview);
  437. Animation animation(afile.getOriginalName());
  438. animation.preload();
  439. auto picture = animation.getImage(0);
  440. if(picture && picture->width() && picture->height())
  441. {
  442. qreal xscale = qreal(128) / qreal(picture->width()), yscale = qreal(128) / qreal(picture->height());
  443. qreal scale = std::min(xscale, yscale);
  444. painter.scale(scale, scale);
  445. painter.drawImage(QPoint(0, 0), *picture);
  446. }
  447. //create object to extract name
  448. std::unique_ptr<CGObjectInstance> temporaryObj(factory->create(templ));
  449. QString translated = useCustomName ? QString::fromStdString(temporaryObj->getObjectName().c_str()) : subGroupName;
  450. itemType->setText(translated);
  451. //add parameters
  452. QJsonObject data{{"id", QJsonValue(ID)},
  453. {"subid", QJsonValue(secondaryID)},
  454. {"template", QJsonValue(templateId)},
  455. {"animationEditor", QString::fromStdString(templ->editorAnimationFile.getOriginalName())},
  456. {"animation", QString::fromStdString(templ->animationFile.getOriginalName())},
  457. {"preview", jsonFromPixmap(preview)},
  458. {"typeName", QString::fromStdString(factory->getJsonKey())}
  459. };
  460. //do not have extra level
  461. if(singleTemplate)
  462. {
  463. itemType->setIcon(QIcon(preview));
  464. itemType->setData(data);
  465. }
  466. else
  467. {
  468. auto * item = new QStandardItem(QIcon(preview), QString::fromStdString(templ->stringID));
  469. item->setData(data);
  470. itemType->appendRow(item);
  471. }
  472. }
  473. itemGroup->appendRow(itemType);
  474. catalog.insert(ID);
  475. }
  476. }
  477. void MainWindow::loadObjectsTree()
  478. {
  479. try
  480. {
  481. ui->terrainFilterCombo->addItem("");
  482. //adding terrains
  483. for(auto & terrain : VLC->terrainTypeHandler->objects)
  484. {
  485. QPushButton *b = new QPushButton(QString::fromStdString(terrain->getNameTranslated()));
  486. ui->terrainLayout->addWidget(b);
  487. connect(b, &QPushButton::clicked, this, [this, terrain]{ terrainButtonClicked(terrain->getId()); });
  488. //filter
  489. QString displayName = QString::fromStdString(terrain->getNameTranslated());
  490. QString uniqueName = QString::fromStdString(terrain->getJsonKey());
  491. ui->terrainFilterCombo->addItem(displayName, QVariant(uniqueName));
  492. }
  493. //add spacer to keep terrain button on the top
  494. ui->terrainLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
  495. //adding roads
  496. for(auto & road : VLC->roadTypeHandler->objects)
  497. {
  498. QPushButton *b = new QPushButton(QString::fromStdString(road->getNameTranslated()));
  499. ui->roadLayout->addWidget(b);
  500. connect(b, &QPushButton::clicked, this, [this, road]{ roadOrRiverButtonClicked(road->getIndex(), true); });
  501. }
  502. //add spacer to keep terrain button on the top
  503. ui->roadLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
  504. //adding rivers
  505. for(auto & river : VLC->riverTypeHandler->objects)
  506. {
  507. QPushButton *b = new QPushButton(QString::fromStdString(river->getNameTranslated()));
  508. ui->riverLayout->addWidget(b);
  509. connect(b, &QPushButton::clicked, this, [this, river]{ roadOrRiverButtonClicked(river->getIndex(), false); });
  510. }
  511. //add spacer to keep terrain button on the top
  512. ui->riverLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding));
  513. if(objectBrowser)
  514. throw std::runtime_error("object browser exists");
  515. //model
  516. objectsModel.setHorizontalHeaderLabels(QStringList() << tr("Type"));
  517. objectBrowser = new ObjectBrowserProxyModel(this);
  518. objectBrowser->setSourceModel(&objectsModel);
  519. objectBrowser->setDynamicSortFilter(false);
  520. objectBrowser->setRecursiveFilteringEnabled(true);
  521. ui->treeView->setModel(objectBrowser);
  522. ui->treeView->setSelectionBehavior(QAbstractItemView::SelectItems);
  523. ui->treeView->setSelectionMode(QAbstractItemView::SingleSelection);
  524. connect(ui->treeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(treeViewSelected(const QModelIndex &, const QModelIndex &)));
  525. //adding objects
  526. addGroupIntoCatalog("TOWNS", false, false, Obj::TOWN);
  527. addGroupIntoCatalog("TOWNS", false, false, Obj::RANDOM_TOWN);
  528. addGroupIntoCatalog("TOWNS", true, false, Obj::SHIPYARD);
  529. addGroupIntoCatalog("TOWNS", true, false, Obj::GARRISON);
  530. addGroupIntoCatalog("TOWNS", true, false, Obj::GARRISON2);
  531. addGroupIntoCatalog("OBJECTS", true, false, Obj::ARENA);
  532. addGroupIntoCatalog("OBJECTS", true, false, Obj::BUOY);
  533. addGroupIntoCatalog("OBJECTS", true, false, Obj::CARTOGRAPHER);
  534. addGroupIntoCatalog("OBJECTS", true, false, Obj::SWAN_POND);
  535. addGroupIntoCatalog("OBJECTS", true, false, Obj::COVER_OF_DARKNESS);
  536. addGroupIntoCatalog("OBJECTS", true, false, Obj::CORPSE);
  537. addGroupIntoCatalog("OBJECTS", true, false, Obj::FAERIE_RING);
  538. addGroupIntoCatalog("OBJECTS", true, false, Obj::FOUNTAIN_OF_FORTUNE);
  539. addGroupIntoCatalog("OBJECTS", true, false, Obj::FOUNTAIN_OF_YOUTH);
  540. addGroupIntoCatalog("OBJECTS", true, false, Obj::GARDEN_OF_REVELATION);
  541. addGroupIntoCatalog("OBJECTS", true, false, Obj::HILL_FORT);
  542. addGroupIntoCatalog("OBJECTS", true, false, Obj::IDOL_OF_FORTUNE);
  543. addGroupIntoCatalog("OBJECTS", true, false, Obj::LIBRARY_OF_ENLIGHTENMENT);
  544. addGroupIntoCatalog("OBJECTS", true, false, Obj::LIGHTHOUSE);
  545. addGroupIntoCatalog("OBJECTS", true, false, Obj::SCHOOL_OF_MAGIC);
  546. addGroupIntoCatalog("OBJECTS", true, false, Obj::MAGIC_SPRING);
  547. addGroupIntoCatalog("OBJECTS", true, false, Obj::MAGIC_WELL);
  548. addGroupIntoCatalog("OBJECTS", true, false, Obj::MERCENARY_CAMP);
  549. addGroupIntoCatalog("OBJECTS", true, false, Obj::MERMAID);
  550. addGroupIntoCatalog("OBJECTS", true, false, Obj::MYSTICAL_GARDEN);
  551. addGroupIntoCatalog("OBJECTS", true, false, Obj::OASIS);
  552. addGroupIntoCatalog("OBJECTS", true, false, Obj::LEAN_TO);
  553. addGroupIntoCatalog("OBJECTS", true, false, Obj::OBELISK);
  554. addGroupIntoCatalog("OBJECTS", true, false, Obj::REDWOOD_OBSERVATORY);
  555. addGroupIntoCatalog("OBJECTS", true, false, Obj::PILLAR_OF_FIRE);
  556. addGroupIntoCatalog("OBJECTS", true, false, Obj::STAR_AXIS);
  557. addGroupIntoCatalog("OBJECTS", true, false, Obj::RALLY_FLAG);
  558. addGroupIntoCatalog("OBJECTS", true, false, Obj::WATERING_HOLE);
  559. addGroupIntoCatalog("OBJECTS", true, false, Obj::SCHOLAR);
  560. addGroupIntoCatalog("OBJECTS", true, false, Obj::SHRINE_OF_MAGIC_INCANTATION);
  561. addGroupIntoCatalog("OBJECTS", true, false, Obj::SHRINE_OF_MAGIC_GESTURE);
  562. addGroupIntoCatalog("OBJECTS", true, false, Obj::SHRINE_OF_MAGIC_THOUGHT);
  563. addGroupIntoCatalog("OBJECTS", true, false, Obj::SIRENS);
  564. addGroupIntoCatalog("OBJECTS", true, false, Obj::STABLES);
  565. addGroupIntoCatalog("OBJECTS", true, false, Obj::TAVERN);
  566. addGroupIntoCatalog("OBJECTS", true, false, Obj::TEMPLE);
  567. addGroupIntoCatalog("OBJECTS", true, false, Obj::DEN_OF_THIEVES);
  568. addGroupIntoCatalog("OBJECTS", true, false, Obj::LEARNING_STONE);
  569. addGroupIntoCatalog("OBJECTS", true, false, Obj::TREE_OF_KNOWLEDGE);
  570. addGroupIntoCatalog("OBJECTS", true, false, Obj::WAGON);
  571. addGroupIntoCatalog("OBJECTS", true, false, Obj::SCHOOL_OF_WAR);
  572. addGroupIntoCatalog("OBJECTS", true, false, Obj::WAR_MACHINE_FACTORY);
  573. addGroupIntoCatalog("OBJECTS", true, false, Obj::WARRIORS_TOMB);
  574. addGroupIntoCatalog("OBJECTS", true, false, Obj::WITCH_HUT);
  575. addGroupIntoCatalog("OBJECTS", true, false, Obj::SANCTUARY);
  576. addGroupIntoCatalog("OBJECTS", true, false, Obj::MARLETTO_TOWER);
  577. addGroupIntoCatalog("HEROES", true, false, Obj::PRISON);
  578. addGroupIntoCatalog("HEROES", false, false, Obj::HERO);
  579. addGroupIntoCatalog("HEROES", false, false, Obj::RANDOM_HERO);
  580. addGroupIntoCatalog("HEROES", false, false, Obj::HERO_PLACEHOLDER);
  581. addGroupIntoCatalog("HEROES", false, false, Obj::BOAT);
  582. addGroupIntoCatalog("ARTIFACTS", true, false, Obj::ARTIFACT);
  583. addGroupIntoCatalog("ARTIFACTS", false, false, Obj::RANDOM_ART);
  584. addGroupIntoCatalog("ARTIFACTS", false, false, Obj::RANDOM_TREASURE_ART);
  585. addGroupIntoCatalog("ARTIFACTS", false, false, Obj::RANDOM_MINOR_ART);
  586. addGroupIntoCatalog("ARTIFACTS", false, false, Obj::RANDOM_MAJOR_ART);
  587. addGroupIntoCatalog("ARTIFACTS", false, false, Obj::RANDOM_RELIC_ART);
  588. addGroupIntoCatalog("ARTIFACTS", true, false, Obj::SPELL_SCROLL);
  589. addGroupIntoCatalog("ARTIFACTS", true, false, Obj::PANDORAS_BOX);
  590. addGroupIntoCatalog("RESOURCES", true, false, Obj::RANDOM_RESOURCE);
  591. addGroupIntoCatalog("RESOURCES", false, false, Obj::RESOURCE);
  592. addGroupIntoCatalog("RESOURCES", true, false, Obj::SEA_CHEST);
  593. addGroupIntoCatalog("RESOURCES", true, false, Obj::TREASURE_CHEST);
  594. addGroupIntoCatalog("RESOURCES", true, false, Obj::CAMPFIRE);
  595. addGroupIntoCatalog("RESOURCES", true, false, Obj::SHIPWRECK_SURVIVOR);
  596. addGroupIntoCatalog("RESOURCES", true, false, Obj::FLOTSAM);
  597. addGroupIntoCatalog("BANKS", true, false, Obj::CREATURE_BANK);
  598. addGroupIntoCatalog("BANKS", true, false, Obj::DRAGON_UTOPIA);
  599. addGroupIntoCatalog("BANKS", true, false, Obj::CRYPT);
  600. addGroupIntoCatalog("BANKS", true, false, Obj::DERELICT_SHIP);
  601. addGroupIntoCatalog("BANKS", true, false, Obj::PYRAMID);
  602. addGroupIntoCatalog("BANKS", true, false, Obj::SHIPWRECK);
  603. addGroupIntoCatalog("DWELLINGS", true, false, Obj::CREATURE_GENERATOR1);
  604. addGroupIntoCatalog("DWELLINGS", true, false, Obj::CREATURE_GENERATOR2);
  605. addGroupIntoCatalog("DWELLINGS", true, false, Obj::CREATURE_GENERATOR3);
  606. addGroupIntoCatalog("DWELLINGS", true, false, Obj::CREATURE_GENERATOR4);
  607. addGroupIntoCatalog("DWELLINGS", true, false, Obj::REFUGEE_CAMP);
  608. addGroupIntoCatalog("DWELLINGS", false, false, Obj::RANDOM_DWELLING);
  609. addGroupIntoCatalog("DWELLINGS", false, false, Obj::RANDOM_DWELLING_LVL);
  610. addGroupIntoCatalog("DWELLINGS", false, false, Obj::RANDOM_DWELLING_FACTION);
  611. addGroupIntoCatalog("GROUNDS", true, false, Obj::CURSED_GROUND1);
  612. addGroupIntoCatalog("GROUNDS", true, false, Obj::MAGIC_PLAINS1);
  613. addGroupIntoCatalog("GROUNDS", true, false, Obj::CLOVER_FIELD);
  614. addGroupIntoCatalog("GROUNDS", true, false, Obj::CURSED_GROUND2);
  615. addGroupIntoCatalog("GROUNDS", true, false, Obj::EVIL_FOG);
  616. addGroupIntoCatalog("GROUNDS", true, false, Obj::FAVORABLE_WINDS);
  617. addGroupIntoCatalog("GROUNDS", true, false, Obj::FIERY_FIELDS);
  618. addGroupIntoCatalog("GROUNDS", true, false, Obj::HOLY_GROUNDS);
  619. addGroupIntoCatalog("GROUNDS", true, false, Obj::LUCID_POOLS);
  620. addGroupIntoCatalog("GROUNDS", true, false, Obj::MAGIC_CLOUDS);
  621. addGroupIntoCatalog("GROUNDS", true, false, Obj::MAGIC_PLAINS2);
  622. addGroupIntoCatalog("GROUNDS", true, false, Obj::ROCKLANDS);
  623. addGroupIntoCatalog("GROUNDS", true, false, Obj::HOLE);
  624. addGroupIntoCatalog("TELEPORTS", true, false, Obj::MONOLITH_ONE_WAY_ENTRANCE);
  625. addGroupIntoCatalog("TELEPORTS", true, false, Obj::MONOLITH_ONE_WAY_EXIT);
  626. addGroupIntoCatalog("TELEPORTS", true, false, Obj::MONOLITH_TWO_WAY);
  627. addGroupIntoCatalog("TELEPORTS", true, false, Obj::SUBTERRANEAN_GATE);
  628. addGroupIntoCatalog("TELEPORTS", true, false, Obj::WHIRLPOOL);
  629. addGroupIntoCatalog("MINES", true, false, Obj::MINE);
  630. addGroupIntoCatalog("MINES", false, false, Obj::ABANDONED_MINE);
  631. addGroupIntoCatalog("MINES", true, false, Obj::WINDMILL);
  632. addGroupIntoCatalog("MINES", true, false, Obj::WATER_WHEEL);
  633. addGroupIntoCatalog("TRIGGERS", true, false, Obj::EVENT);
  634. addGroupIntoCatalog("TRIGGERS", true, false, Obj::GRAIL);
  635. addGroupIntoCatalog("TRIGGERS", true, false, Obj::SIGN);
  636. addGroupIntoCatalog("TRIGGERS", true, false, Obj::OCEAN_BOTTLE);
  637. addGroupIntoCatalog("MONSTERS", false, false, Obj::MONSTER);
  638. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER);
  639. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L1);
  640. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L2);
  641. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L3);
  642. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L4);
  643. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L5);
  644. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L6);
  645. addGroupIntoCatalog("MONSTERS", true, false, Obj::RANDOM_MONSTER_L7);
  646. addGroupIntoCatalog("QUESTS", true, false, Obj::SEER_HUT);
  647. addGroupIntoCatalog("QUESTS", true, false, Obj::BORDER_GATE);
  648. addGroupIntoCatalog("QUESTS", true, false, Obj::QUEST_GUARD);
  649. addGroupIntoCatalog("QUESTS", true, false, Obj::HUT_OF_MAGI);
  650. addGroupIntoCatalog("QUESTS", true, false, Obj::EYE_OF_MAGI);
  651. addGroupIntoCatalog("QUESTS", true, false, Obj::BORDERGUARD);
  652. addGroupIntoCatalog("QUESTS", true, false, Obj::KEYMASTER);
  653. addGroupIntoCatalog("wog object", true, false, Obj::WOG_OBJECT);
  654. addGroupIntoCatalog("OBSTACLES", true);
  655. addGroupIntoCatalog("OTHER", false);
  656. }
  657. catch(const std::exception &)
  658. {
  659. QMessageBox::critical(this, "Mods loading problem", "Critical error during Mods loading. Disable invalid mods and restart.");
  660. }
  661. }
  662. void MainWindow::on_actionLevel_triggered()
  663. {
  664. if(controller.map() && controller.map()->twoLevel)
  665. {
  666. mapLevel = mapLevel ? 0 : 1;
  667. ui->mapView->setScene(controller.scene(mapLevel));
  668. ui->minimapView->setScene(controller.miniScene(mapLevel));
  669. if (mapLevel == 0)
  670. {
  671. ui->actionLevel->setToolTip(tr("View underground"));
  672. }
  673. else
  674. {
  675. ui->actionLevel->setToolTip(tr("View surface"));
  676. }
  677. }
  678. }
  679. void MainWindow::on_actionUndo_triggered()
  680. {
  681. QString str("Undo clicked");
  682. statusBar()->showMessage(str, 1000);
  683. if (controller.map())
  684. {
  685. controller.undo();
  686. }
  687. }
  688. void MainWindow::on_actionRedo_triggered()
  689. {
  690. QString str("Redo clicked");
  691. displayStatus(str);
  692. if (controller.map())
  693. {
  694. controller.redo();
  695. }
  696. }
  697. void MainWindow::on_actionPass_triggered(bool checked)
  698. {
  699. QString str("Passability clicked");
  700. displayStatus(str);
  701. if(controller.map())
  702. {
  703. controller.scene(0)->passabilityView.show(checked);
  704. controller.scene(1)->passabilityView.show(checked);
  705. }
  706. }
  707. void MainWindow::on_actionGrid_triggered(bool checked)
  708. {
  709. QString str("Grid clicked");
  710. displayStatus(str);
  711. if(controller.map())
  712. {
  713. controller.scene(0)->gridView.show(checked);
  714. controller.scene(1)->gridView.show(checked);
  715. }
  716. }
  717. void MainWindow::changeBrushState(int idx)
  718. {
  719. }
  720. void MainWindow::on_actionErase_triggered()
  721. {
  722. if(controller.map())
  723. {
  724. controller.commitObjectErase(mapLevel);
  725. }
  726. }
  727. void MainWindow::preparePreview(const QModelIndex &index)
  728. {
  729. scenePreview->clear();
  730. auto data = objectsModel.itemFromIndex(objectBrowser->mapToSource(index))->data().toJsonObject();
  731. if(!data.empty())
  732. {
  733. auto preview = data["preview"];
  734. if(preview != QJsonValue::Undefined)
  735. {
  736. QPixmap objPreview = pixmapFromJson(preview);
  737. scenePreview->addPixmap(objPreview);
  738. }
  739. }
  740. ui->objectPreview->fitInView(scenePreview->itemsBoundingRect(), Qt::KeepAspectRatio);
  741. }
  742. void MainWindow::treeViewSelected(const QModelIndex & index, const QModelIndex & deselected)
  743. {
  744. ui->toolSelect->setChecked(true);
  745. ui->mapView->selectionTool = MapView::SelectionTool::None;
  746. preparePreview(index);
  747. }
  748. void MainWindow::on_terrainFilterCombo_currentIndexChanged(int index)
  749. {
  750. if(!objectBrowser)
  751. return;
  752. QString uniqueName = ui->terrainFilterCombo->itemData(index).toString();
  753. objectBrowser->terrain = TerrainId(ETerrainId::ANY_TERRAIN);
  754. if (!uniqueName.isEmpty())
  755. {
  756. for (auto const & terrain : VLC->terrainTypeHandler->objects)
  757. if (terrain->getJsonKey() == uniqueName.toStdString())
  758. objectBrowser->terrain = terrain->getId();
  759. }
  760. objectBrowser->invalidate();
  761. objectBrowser->sort(0);
  762. }
  763. void MainWindow::on_filter_textChanged(const QString &arg1)
  764. {
  765. if(!objectBrowser)
  766. return;
  767. objectBrowser->filter = arg1;
  768. objectBrowser->invalidate();
  769. objectBrowser->sort(0);
  770. }
  771. void MainWindow::on_actionFill_triggered()
  772. {
  773. QString str("Fill clicked");
  774. displayStatus(str);
  775. if(!controller.map())
  776. return;
  777. controller.commitObstacleFill(mapLevel);
  778. }
  779. void MainWindow::loadInspector(CGObjectInstance * obj, bool switchTab)
  780. {
  781. if(switchTab)
  782. ui->tabWidget->setCurrentIndex(1);
  783. Inspector inspector(controller, obj, ui->inspectorWidget);
  784. inspector.updateProperties();
  785. }
  786. void MainWindow::on_inspectorWidget_itemChanged(QTableWidgetItem *item)
  787. {
  788. if(!item->isSelected() && !(item->flags() & Qt::ItemIsUserCheckable))
  789. return;
  790. int r = item->row();
  791. int c = item->column();
  792. if(c < 1)
  793. return;
  794. auto * tableWidget = item->tableWidget();
  795. //get identifier
  796. auto identifier = tableWidget->item(0, 1)->text();
  797. CGObjectInstance * obj = data_cast<CGObjectInstance>(identifier.toLongLong());
  798. //get parameter name
  799. auto param = tableWidget->item(r, c - 1)->text();
  800. //set parameter
  801. Inspector inspector(controller, obj, tableWidget);
  802. inspector.setProperty(param, item);
  803. controller.commitObjectChange(mapLevel);
  804. }
  805. void MainWindow::on_actionMapSettings_triggered()
  806. {
  807. auto settingsDialog = new MapSettings(controller, this);
  808. settingsDialog->setWindowModality(Qt::WindowModal);
  809. settingsDialog->setModal(true);
  810. }
  811. void MainWindow::on_actionPlayers_settings_triggered()
  812. {
  813. auto settingsDialog = new PlayerSettings(controller, this);
  814. settingsDialog->setWindowModality(Qt::WindowModal);
  815. settingsDialog->setModal(true);
  816. connect(settingsDialog, &QDialog::finished, this, &MainWindow::onPlayersChanged);
  817. }
  818. QAction * MainWindow::getActionPlayer(const PlayerColor & player)
  819. {
  820. if(player.getNum() == 0) return ui->actionPlayer_1;
  821. if(player.getNum() == 1) return ui->actionPlayer_2;
  822. if(player.getNum() == 2) return ui->actionPlayer_3;
  823. if(player.getNum() == 3) return ui->actionPlayer_4;
  824. if(player.getNum() == 4) return ui->actionPlayer_5;
  825. if(player.getNum() == 5) return ui->actionPlayer_6;
  826. if(player.getNum() == 6) return ui->actionPlayer_7;
  827. if(player.getNum() == 7) return ui->actionPlayer_8;
  828. return ui->actionNeutral;
  829. }
  830. void MainWindow::switchDefaultPlayer(const PlayerColor & player)
  831. {
  832. if(controller.defaultPlayer == player)
  833. return;
  834. ui->actionNeutral->blockSignals(true);
  835. ui->actionNeutral->setChecked(PlayerColor::NEUTRAL == player);
  836. ui->actionNeutral->blockSignals(false);
  837. for(int i = 0; i < PlayerColor::PLAYER_LIMIT.getNum(); ++i)
  838. {
  839. getActionPlayer(PlayerColor(i))->blockSignals(true);
  840. getActionPlayer(PlayerColor(i))->setChecked(PlayerColor(i) == player);
  841. getActionPlayer(PlayerColor(i))->blockSignals(false);
  842. }
  843. controller.defaultPlayer = player;
  844. }
  845. void MainWindow::onPlayersChanged()
  846. {
  847. if(controller.map())
  848. {
  849. getActionPlayer(PlayerColor::NEUTRAL)->setEnabled(true);
  850. for(int i = 0; i < controller.map()->players.size(); ++i)
  851. getActionPlayer(PlayerColor(i))->setEnabled(controller.map()->players.at(i).canAnyonePlay());
  852. if(!getActionPlayer(controller.defaultPlayer)->isEnabled() || controller.defaultPlayer == PlayerColor::NEUTRAL)
  853. switchDefaultPlayer(PlayerColor::NEUTRAL);
  854. }
  855. else
  856. {
  857. for(int i = 0; i < PlayerColor::PLAYER_LIMIT.getNum(); ++i)
  858. getActionPlayer(PlayerColor(i))->setEnabled(false);
  859. getActionPlayer(PlayerColor::NEUTRAL)->setEnabled(false);
  860. }
  861. }
  862. void MainWindow::enableUndo(bool enable)
  863. {
  864. ui->actionUndo->setEnabled(enable);
  865. }
  866. void MainWindow::enableRedo(bool enable)
  867. {
  868. ui->actionRedo->setEnabled(enable);
  869. }
  870. void MainWindow::onSelectionMade(int level, bool anythingSelected)
  871. {
  872. if (level == mapLevel)
  873. {
  874. ui->actionErase->setEnabled(anythingSelected);
  875. }
  876. }
  877. void MainWindow::displayStatus(const QString& message, int timeout /* = 2000 */)
  878. {
  879. statusBar()->showMessage(message, timeout);
  880. }
  881. void MainWindow::on_actionValidate_triggered()
  882. {
  883. new Validator(controller.map(), this);
  884. }
  885. void MainWindow::on_actionUpdate_appearance_triggered()
  886. {
  887. if(!controller.map())
  888. return;
  889. if(controller.scene(mapLevel)->selectionObjectsView.getSelection().empty())
  890. {
  891. QMessageBox::information(this, tr("Update appearance"), tr("No objects selected"));
  892. return;
  893. }
  894. if(QMessageBox::Yes != QMessageBox::question(this, tr("Update appearance"), tr("This operation is irreversible. Do you want to continue?")))
  895. return;
  896. controller.scene(mapLevel)->selectionTerrainView.clear();
  897. int errors = 0;
  898. std::set<CGObjectInstance*> staticObjects;
  899. for(auto * obj : controller.scene(mapLevel)->selectionObjectsView.getSelection())
  900. {
  901. auto handler = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID);
  902. if(!controller.map()->isInTheMap(obj->visitablePos()))
  903. {
  904. ++errors;
  905. continue;
  906. }
  907. auto * terrain = controller.map()->getTile(obj->visitablePos()).terType;
  908. if(handler->isStaticObject())
  909. {
  910. staticObjects.insert(obj);
  911. if(obj->appearance->canBePlacedAt(terrain->getId()))
  912. {
  913. controller.scene(mapLevel)->selectionObjectsView.deselectObject(obj);
  914. continue;
  915. }
  916. for(auto & offset : obj->appearance->getBlockedOffsets())
  917. controller.scene(mapLevel)->selectionTerrainView.select(obj->pos + offset);
  918. }
  919. else
  920. {
  921. auto app = handler->getOverride(terrain->getId(), obj);
  922. if(!app)
  923. {
  924. if(obj->appearance->canBePlacedAt(terrain->getId()))
  925. continue;
  926. auto templates = handler->getTemplates(terrain->getId());
  927. if(templates.empty())
  928. {
  929. ++errors;
  930. continue;
  931. }
  932. app = templates.front();
  933. }
  934. obj->appearance = app;
  935. controller.mapHandler()->invalidate(obj);
  936. controller.scene(mapLevel)->selectionObjectsView.deselectObject(obj);
  937. }
  938. }
  939. controller.commitObjectChange(mapLevel);
  940. controller.commitObjectErase(mapLevel);
  941. controller.commitObstacleFill(mapLevel);
  942. if(errors)
  943. QMessageBox::warning(this, tr("Update appearance"), QString(tr("Errors occurred. %1 objects were not updated")).arg(errors));
  944. }
  945. void MainWindow::on_actionRecreate_obstacles_triggered()
  946. {
  947. }
  948. void MainWindow::on_actionCut_triggered()
  949. {
  950. if(controller.map())
  951. {
  952. controller.copyToClipboard(mapLevel);
  953. controller.commitObjectErase(mapLevel);
  954. }
  955. }
  956. void MainWindow::on_actionCopy_triggered()
  957. {
  958. if(controller.map())
  959. {
  960. controller.copyToClipboard(mapLevel);
  961. }
  962. }
  963. void MainWindow::on_actionPaste_triggered()
  964. {
  965. if(controller.map())
  966. {
  967. controller.pasteFromClipboard(mapLevel);
  968. }
  969. }
  970. void MainWindow::on_actionExport_triggered()
  971. {
  972. QString fileName = QFileDialog::getSaveFileName(this, tr("Save to image"), lastSavingDir, "BMP (*.bmp);;JPEG (*.jpeg);;PNG (*.png)");
  973. if(!fileName.isNull())
  974. {
  975. QImage image(ui->mapView->scene()->sceneRect().size().toSize(), QImage::Format_RGB888);
  976. QPainter painter(&image);
  977. ui->mapView->scene()->render(&painter);
  978. image.save(fileName);
  979. }
  980. }
  981. void MainWindow::on_actionTranslations_triggered()
  982. {
  983. auto translationsDialog = new Translations(*controller.map(), this);
  984. translationsDialog->show();
  985. }
  986. void MainWindow::on_actionh3m_converter_triggered()
  987. {
  988. auto mapFiles = QFileDialog::getOpenFileNames(this, tr("Select maps to convert"),
  989. QString::fromStdString(VCMIDirs::get().userCachePath().make_preferred().string()),
  990. tr("HoMM3 maps(*.h3m)"));
  991. if(mapFiles.empty())
  992. return;
  993. auto saveDirectory = QFileDialog::getExistingDirectory(this, tr("Choose directory to save converted maps"), QCoreApplication::applicationDirPath());
  994. if(saveDirectory.isEmpty())
  995. return;
  996. try
  997. {
  998. for(auto & m : mapFiles)
  999. {
  1000. CMapService mapService;
  1001. auto map = openMapInternal(m);
  1002. controller.repairMap(map.get());
  1003. mapService.saveMap(map, (saveDirectory + '/' + QFileInfo(m).completeBaseName() + ".vmap").toStdString());
  1004. }
  1005. QMessageBox::information(this, tr("Operation completed"), tr("Successfully converted %1 maps").arg(mapFiles.size()));
  1006. }
  1007. catch(const std::exception & e)
  1008. {
  1009. QMessageBox::critical(this, tr("Failed to convert the map. Abort operation"), tr(e.what()));
  1010. }
  1011. }
  1012. void MainWindow::on_actionLock_triggered()
  1013. {
  1014. if(controller.map())
  1015. {
  1016. if(controller.scene(mapLevel)->selectionObjectsView.getSelection().empty())
  1017. {
  1018. for(auto obj : controller.map()->objects)
  1019. {
  1020. controller.scene(mapLevel)->selectionObjectsView.setLockObject(obj, true);
  1021. controller.scene(mapLevel)->objectsView.setLockObject(obj, true);
  1022. }
  1023. }
  1024. else
  1025. {
  1026. for(auto * obj : controller.scene(mapLevel)->selectionObjectsView.getSelection())
  1027. {
  1028. controller.scene(mapLevel)->selectionObjectsView.setLockObject(obj, true);
  1029. controller.scene(mapLevel)->objectsView.setLockObject(obj, true);
  1030. }
  1031. controller.scene(mapLevel)->selectionObjectsView.clear();
  1032. }
  1033. controller.scene(mapLevel)->objectsView.update();
  1034. controller.scene(mapLevel)->selectionObjectsView.update();
  1035. }
  1036. }
  1037. void MainWindow::on_actionUnlock_triggered()
  1038. {
  1039. if(controller.map())
  1040. {
  1041. controller.scene(mapLevel)->selectionObjectsView.unlockAll();
  1042. controller.scene(mapLevel)->objectsView.unlockAll();
  1043. }
  1044. controller.scene(mapLevel)->objectsView.update();
  1045. }
  1046. void MainWindow::on_actionZoom_in_triggered()
  1047. {
  1048. auto rect = ui->mapView->mapToScene(ui->mapView->viewport()->geometry()).boundingRect();
  1049. rect -= QMargins{32 + 1, 32 + 1, 32 + 2, 32 + 2}; //compensate bounding box
  1050. ui->mapView->fitInView(rect, Qt::KeepAspectRatioByExpanding);
  1051. }
  1052. void MainWindow::on_actionZoom_out_triggered()
  1053. {
  1054. auto rect = ui->mapView->mapToScene(ui->mapView->viewport()->geometry()).boundingRect();
  1055. rect += QMargins{32 - 1, 32 - 1, 32 - 2, 32 - 2}; //compensate bounding box
  1056. ui->mapView->fitInView(rect, Qt::KeepAspectRatioByExpanding);
  1057. }
  1058. void MainWindow::on_actionZoom_reset_triggered()
  1059. {
  1060. auto center = ui->mapView->mapToScene(ui->mapView->viewport()->geometry().center());
  1061. ui->mapView->fitInView(initialScale, Qt::KeepAspectRatioByExpanding);
  1062. ui->mapView->centerOn(center);
  1063. }
  1064. void MainWindow::on_toolLine_toggled(bool checked)
  1065. {
  1066. if(checked)
  1067. {
  1068. ui->mapView->selectionTool = MapView::SelectionTool::Line;
  1069. ui->tabWidget->setCurrentIndex(0);
  1070. }
  1071. }
  1072. void MainWindow::on_toolBrush2_toggled(bool checked)
  1073. {
  1074. if(checked)
  1075. {
  1076. ui->mapView->selectionTool = MapView::SelectionTool::Brush2;
  1077. ui->tabWidget->setCurrentIndex(0);
  1078. }
  1079. }
  1080. void MainWindow::on_toolBrush_toggled(bool checked)
  1081. {
  1082. if(checked)
  1083. {
  1084. ui->mapView->selectionTool = MapView::SelectionTool::Brush;
  1085. ui->tabWidget->setCurrentIndex(0);
  1086. }
  1087. }
  1088. void MainWindow::on_toolBrush4_toggled(bool checked)
  1089. {
  1090. if(checked)
  1091. {
  1092. ui->mapView->selectionTool = MapView::SelectionTool::Brush4;
  1093. ui->tabWidget->setCurrentIndex(0);
  1094. }
  1095. }
  1096. void MainWindow::on_toolLasso_toggled(bool checked)
  1097. {
  1098. if(checked)
  1099. {
  1100. ui->mapView->selectionTool = MapView::SelectionTool::Lasso;
  1101. ui->tabWidget->setCurrentIndex(0);
  1102. }
  1103. }
  1104. void MainWindow::on_toolArea_toggled(bool checked)
  1105. {
  1106. if(checked)
  1107. {
  1108. ui->mapView->selectionTool = MapView::SelectionTool::Area;
  1109. ui->tabWidget->setCurrentIndex(0);
  1110. }
  1111. }
  1112. void MainWindow::on_toolFill_toggled(bool checked)
  1113. {
  1114. if(checked)
  1115. {
  1116. ui->mapView->selectionTool = MapView::SelectionTool::Fill;
  1117. ui->tabWidget->setCurrentIndex(0);
  1118. }
  1119. }
  1120. void MainWindow::on_toolSelect_toggled(bool checked)
  1121. {
  1122. if(checked)
  1123. {
  1124. ui->mapView->selectionTool = MapView::SelectionTool::None;
  1125. ui->tabWidget->setCurrentIndex(0);
  1126. }
  1127. }