mainwindow.cpp 40 KB

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