mainwindow.cpp 40 KB

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