mainwindow.cpp 40 KB

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