mainwindow.cpp 40 KB

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