From e3edb503ed6caf112fed4184175d38d37b24ea4b Mon Sep 17 00:00:00 2001 From: GriffinR Date: Mon, 25 Jan 2021 11:04:07 -0500 Subject: [PATCH 01/46] Exclude non-item constants in items.h --- src/project.cpp | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/project.cpp b/src/project.cpp index 8ef9b4b3..19df02a9 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -2009,7 +2009,7 @@ QMap Project::getTilesetLabels() { bool Project::readTilesetProperties() { QStringList definePrefixes; - definePrefixes << "NUM_"; + definePrefixes << "\\bNUM_"; QString filename = "include/fieldmap.h"; fileWatcher.addPath(root + "/" + filename); QMap defines = parser.readCDefines(filename, definePrefixes); @@ -2067,7 +2067,7 @@ bool Project::readTilesetProperties() { bool Project::readMaxMapDataSize() { QStringList definePrefixes; - definePrefixes << "MAX_"; + definePrefixes << "\\bMAX_"; QString filename = "include/fieldmap.h"; // already in fileWatcher from readTilesetProperties QMap defines = parser.readCDefines(filename, definePrefixes); @@ -2096,7 +2096,7 @@ bool Project::readRegionMapSections() { this->mapSectionNameToValue.clear(); this->mapSectionValueToName.clear(); - QStringList prefixes = (QStringList() << "MAPSEC_"); + QStringList prefixes = (QStringList() << "\\bMAPSEC_"); QString filename = "include/constants/region_map_sections.h"; fileWatcher.addPath(root + "/" + filename); this->mapSectionNameToValue = parser.readCDefines(filename, prefixes); @@ -2161,7 +2161,7 @@ bool Project::readHealLocations() { bool Project::readItemNames() { itemNames->clear(); - QStringList prefixes = (QStringList() << "ITEM_"); + QStringList prefixes = (QStringList() << "\\bITEM_(?!(B_)?USE_)"); // Exclude ITEM_USE_ and ITEM_B_USE_ constants QString filename = "include/constants/items.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, itemNames); @@ -2177,10 +2177,10 @@ bool Project::readFlagNames() { // If this fails flags may simply be out of order, no need to check for success QString opponentsFilename = "include/constants/opponents.h"; fileWatcher.addPath(root + "/" + opponentsFilename); - QMap maxTrainers = parser.readCDefines(opponentsFilename, QStringList() << "MAX_"); + QMap maxTrainers = parser.readCDefines(opponentsFilename, QStringList() << "\\bMAX_"); // Parse flags flagNames->clear(); - QStringList prefixes = (QStringList() << "FLAG_"); + QStringList prefixes = (QStringList() << "\\bFLAG_"); QString flagsFilename = "include/constants/flags.h"; fileWatcher.addPath(root + "/" + flagsFilename); parser.readCDefinesSorted(flagsFilename, prefixes, flagNames, maxTrainers); @@ -2193,7 +2193,7 @@ bool Project::readFlagNames() { bool Project::readVarNames() { varNames->clear(); - QStringList prefixes = (QStringList() << "VAR_"); + QStringList prefixes = (QStringList() << "\\bVAR_"); QString filename = "include/constants/vars.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, varNames); @@ -2206,7 +2206,7 @@ bool Project::readVarNames() { bool Project::readMovementTypes() { movementTypes->clear(); - QStringList prefixes = (QStringList() << "MOVEMENT_TYPE_"); + QStringList prefixes = (QStringList() << "\\bMOVEMENT_TYPE_"); QString filename = "include/constants/event_object_movement.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, movementTypes); @@ -2230,7 +2230,7 @@ bool Project::readInitialFacingDirections() { bool Project::readMapTypes() { mapTypes->clear(); - QStringList prefixes = (QStringList() << "MAP_TYPE_"); + QStringList prefixes = (QStringList() << "\\bMAP_TYPE_"); QString filename = "include/constants/map_types.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, mapTypes); @@ -2243,7 +2243,7 @@ bool Project::readMapTypes() { bool Project::readMapBattleScenes() { mapBattleScenes->clear(); - QStringList prefixes = (QStringList() << "MAP_BATTLE_SCENE_"); + QStringList prefixes = (QStringList() << "\\bMAP_BATTLE_SCENE_"); QString filename = "include/constants/map_types.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted("include/constants/map_types.h", prefixes, mapBattleScenes); @@ -2271,7 +2271,7 @@ bool Project::readCoordEventWeatherNames() { if (!projectConfig.getEventWeatherTriggerEnabled()) return true; coordEventWeatherNames->clear(); - QStringList prefixes = (QStringList() << "COORD_EVENT_WEATHER_"); + QStringList prefixes = (QStringList() << "\\bCOORD_EVENT_WEATHER_"); QString filename = "include/constants/weather.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, coordEventWeatherNames); @@ -2286,7 +2286,7 @@ bool Project::readSecretBaseIds() { if (!projectConfig.getEventSecretBaseEnabled()) return true; secretBaseIds->clear(); - QStringList prefixes = (QStringList() << "SECRET_BASE_[A-Za-z0-9_]*_[0-9]+"); + QStringList prefixes = (QStringList() << "\\bSECRET_BASE_[A-Za-z0-9_]*_[0-9]+"); QString filename = "include/constants/secret_bases.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, secretBaseIds); @@ -2299,7 +2299,7 @@ bool Project::readSecretBaseIds() { bool Project::readBgEventFacingDirections() { bgEventFacingDirections->clear(); - QStringList prefixes = (QStringList() << "BG_EVENT_PLAYER_FACING_"); + QStringList prefixes = (QStringList() << "\\bBG_EVENT_PLAYER_FACING_"); QString filename = "include/constants/event_bg.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, bgEventFacingDirections); @@ -2312,7 +2312,7 @@ bool Project::readBgEventFacingDirections() { bool Project::readTrainerTypes() { trainerTypes->clear(); - QStringList prefixes = (QStringList() << "TRAINER_TYPE_"); + QStringList prefixes = (QStringList() << "\\bTRAINER_TYPE_"); QString filename = "include/constants/trainer_types.h"; fileWatcher.addPath(root + "/" + filename); parser.readCDefinesSorted(filename, prefixes, trainerTypes); @@ -2327,7 +2327,7 @@ bool Project::readMetatileBehaviors() { this->metatileBehaviorMap.clear(); this->metatileBehaviorMapInverse.clear(); - QStringList prefixes = (QStringList() << "MB_"); + QStringList prefixes = (QStringList() << "\\bMB_"); QString filename = "include/constants/metatile_behaviors.h"; fileWatcher.addPath(root + "/" + filename); this->metatileBehaviorMap = parser.readCDefines(filename, prefixes); @@ -2344,7 +2344,7 @@ bool Project::readMetatileBehaviors() { QStringList Project::getSongNames() { QStringList songDefinePrefixes; - songDefinePrefixes << "SE_" << "MUS_"; + songDefinePrefixes << "\\bSE_" << "\\bMUS_"; QString filename = "include/constants/songs.h"; fileWatcher.addPath(root + "/" + filename); QMap songDefines = parser.readCDefines(filename, songDefinePrefixes); @@ -2356,7 +2356,7 @@ QStringList Project::getSongNames() { QMap Project::getEventObjGfxConstants() { QStringList eventObjGfxPrefixes; - eventObjGfxPrefixes << "OBJ_EVENT_GFX_"; + eventObjGfxPrefixes << "\\bOBJ_EVENT_GFX_"; QString filename = "include/constants/event_objects.h"; fileWatcher.addPath(root + "/" + filename); @@ -2378,7 +2378,7 @@ bool Project::readMiscellaneousConstants() { QString filename = "include/constants/global.h"; fileWatcher.addPath(root + "/" + filename); QStringList definePrefixes; - definePrefixes << "OBJECT_"; + definePrefixes << "\\bOBJECT_"; QMap defines = parser.readCDefines(filename, definePrefixes); auto it = defines.find("OBJECT_EVENT_TEMPLATES_COUNT"); From 6335151c394d1ff5b6f1cbf92931e6a280449718 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Wed, 3 Feb 2021 10:24:59 -0500 Subject: [PATCH 02/46] Add option to open log file --- forms/mainwindow.ui | 6 ++++++ include/core/parseutil.h | 1 + include/editor.h | 2 +- include/mainwindow.h | 1 + src/core/parseutil.cpp | 7 ++++++- src/editor.cpp | 1 - src/mainwindow.cpp | 6 ++++++ 7 files changed, 21 insertions(+), 3 deletions(-) diff --git a/forms/mainwindow.ui b/forms/mainwindow.ui index f752e85d..ce31269f 100644 --- a/forms/mainwindow.ui +++ b/forms/mainwindow.ui @@ -2649,6 +2649,7 @@ Help + @@ -2944,6 +2945,11 @@ Export Map Timelapse Image... + + + Open Log File + + diff --git a/include/core/parseutil.h b/include/core/parseutil.h index 82fad4e2..96cc1201 100644 --- a/include/core/parseutil.h +++ b/include/core/parseutil.h @@ -42,6 +42,7 @@ public: ParseUtil(); void set_root(QString); static QString readTextFile(QString); + static int textFileLineCount(const QString &path); void strip_comment(QString*); QList* parseAsm(QString); int evaluateDefine(QString, QMap*); diff --git a/include/editor.h b/include/editor.h index e876a3ca..e03b3a9e 100644 --- a/include/editor.h +++ b/include/editor.h @@ -154,6 +154,7 @@ public: void shouldReselectEvents(); void scaleMapView(int); + void openInTextEditor(const QString &path, int lineNum = 0) const; public slots: void openMapScripts() const; @@ -188,7 +189,6 @@ private: QString getMovementPermissionText(uint16_t collision, uint16_t elevation); QString getMetatileDisplayMessage(uint16_t metatileId); bool eventLimitReached(Map *, QString); - void openInTextEditor(const QString &path, int lineNum = 0) const; bool startDetachedProcess(const QString &command, const QString &workingDirectory = QString(), qint64 *pid = nullptr) const; diff --git a/include/mainwindow.h b/include/mainwindow.h index 3d09c5e7..d6754f1b 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -222,6 +222,7 @@ private slots: void on_toolButton_ExpandAll_clicked(); void on_toolButton_CollapseAll_clicked(); void on_actionAbout_Porymap_triggered(); + void on_actionOpen_Log_File_triggered(); void on_pushButton_AddCustomHeaderField_clicked(); void on_pushButton_DeleteCustomHeaderField_clicked(); void on_tableWidget_CustomHeaderFields_cellChanged(int row, int column); diff --git a/src/core/parseutil.cpp b/src/core/parseutil.cpp index 74330738..e59cee49 100644 --- a/src/core/parseutil.cpp +++ b/src/core/parseutil.cpp @@ -49,11 +49,16 @@ QString ParseUtil::readTextFile(QString path) { in.setCodec("UTF-8"); QString text = ""; while (!in.atEnd()) { - text += in.readLine() + "\n"; + text += in.readLine() + '\n'; } return text; } +int ParseUtil::textFileLineCount(const QString &path) { + const QString text = readTextFile(path); + return text.split('\n').count() + 1; +} + QList* ParseUtil::parseAsm(QString filename) { QList *parsed = new QList; diff --git a/src/editor.cpp b/src/editor.cpp index 617f29d3..cd11a598 100644 --- a/src/editor.cpp +++ b/src/editor.cpp @@ -2078,7 +2078,6 @@ bool Editor::startDetachedProcess(const QString &command, const QString &working logInfo("Executing command: " + command); QProcess process; #ifdef Q_OS_WIN - // Windows is WeirdChamp QStringList arguments = ParseUtil::splitShellCommand(command); const QString program = arguments.takeFirst(); QFileInfo programFileInfo(program); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index dd7f71bf..467ac6bc 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2691,6 +2691,12 @@ void MainWindow::on_actionAbout_Porymap_triggered() window->show(); } +void MainWindow::on_actionOpen_Log_File_triggered() { + const QString logPath = getLogPath(); + const int lineCount = ParseUtil::textFileLineCount(logPath); + editor->openInTextEditor(logPath, lineCount); +} + void MainWindow::on_actionEdit_Preferences_triggered() { if (!preferenceEditor) { preferenceEditor = new PreferenceEditor(this); From 2c065ae5b6404db7eea34983c62b78132a2c008c Mon Sep 17 00:00:00 2001 From: BigBahss Date: Wed, 3 Feb 2021 10:32:00 -0500 Subject: [PATCH 03/46] Dont disable option to open log when project open fails --- src/mainwindow.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 467ac6bc..853d0a2b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -84,6 +84,7 @@ void MainWindow::setWindowDisabled(bool disabled) { ui->action_Exit->setDisabled(false); ui->menuHelp->setDisabled(false); ui->actionAbout_Porymap->setDisabled(false); + ui->actionOpen_Log_File->setDisabled(false); if (!disabled) togglePreferenceSpecificUi(); } From 3d394bc4bb4b0b18701f594eed9ec5b908ef9afd Mon Sep 17 00:00:00 2001 From: BigBahss Date: Wed, 3 Feb 2021 11:24:07 -0500 Subject: [PATCH 04/46] Add option to open config folder --- forms/mainwindow.ui | 6 ++++++ include/mainwindow.h | 1 + src/mainwindow.cpp | 5 +++++ 3 files changed, 12 insertions(+) diff --git a/forms/mainwindow.ui b/forms/mainwindow.ui index ce31269f..8b4a5dd4 100644 --- a/forms/mainwindow.ui +++ b/forms/mainwindow.ui @@ -2650,6 +2650,7 @@ + @@ -2950,6 +2951,11 @@ Open Log File + + + Open Config Folder + + diff --git a/include/mainwindow.h b/include/mainwindow.h index d6754f1b..bf3a4d40 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -223,6 +223,7 @@ private slots: void on_toolButton_CollapseAll_clicked(); void on_actionAbout_Porymap_triggered(); void on_actionOpen_Log_File_triggered(); + void on_actionOpen_Config_Folder_triggered(); void on_pushButton_AddCustomHeaderField_clicked(); void on_pushButton_DeleteCustomHeaderField_clicked(); void on_tableWidget_CustomHeaderFields_cellChanged(int row, int column); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 853d0a2b..14a8fc3d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -85,6 +85,7 @@ void MainWindow::setWindowDisabled(bool disabled) { ui->menuHelp->setDisabled(false); ui->actionAbout_Porymap->setDisabled(false); ui->actionOpen_Log_File->setDisabled(false); + ui->actionOpen_Config_Folder->setDisabled(false); if (!disabled) togglePreferenceSpecificUi(); } @@ -2698,6 +2699,10 @@ void MainWindow::on_actionOpen_Log_File_triggered() { editor->openInTextEditor(logPath, lineCount); } +void MainWindow::on_actionOpen_Config_Folder_triggered() { + QDesktopServices::openUrl(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)); +} + void MainWindow::on_actionEdit_Preferences_triggered() { if (!preferenceEditor) { preferenceEditor = new PreferenceEditor(this); From 36a6212af6b16d781248028130dd568ede40cc04 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Wed, 3 Feb 2021 12:13:24 -0500 Subject: [PATCH 05/46] Store recent map in ProjectConfig instead of PorymapConfig --- include/config.h | 8 ++++---- src/config.cpp | 24 ++++++++++++------------ src/mainwindow.cpp | 8 ++++---- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/include/config.h b/include/config.h index e9264d15..ed5403a2 100644 --- a/include/config.h +++ b/include/config.h @@ -38,7 +38,6 @@ public: } virtual void reset() override { this->recentProject = ""; - this->recentMap = ""; this->mapSortOrder = MapSortOrder::Group; this->prettyCursors = true; this->collisionOpacity = 50; @@ -52,7 +51,6 @@ public: this->textEditorGotoLine = ""; } void setRecentProject(QString project); - void setRecentMap(QString map); void setMapSortOrder(MapSortOrder order); void setPrettyCursors(bool enabled); void setMainGeometry(QByteArray, QByteArray, QByteArray, QByteArray); @@ -69,7 +67,6 @@ public: void setTextEditorOpenFolder(const QString &command); void setTextEditorGotoLine(const QString &command); QString getRecentProject(); - QString getRecentMap(); MapSortOrder getMapSortOrder(); bool getPrettyCursors(); QMap getMainGeometry(); @@ -93,7 +90,6 @@ protected: virtual void setUnreadKeys() override {}; private: QString recentProject; - QString recentMap; QString stringFromByteArray(QByteArray); QByteArray bytesFromString(QString); MapSortOrder mapSortOrder; @@ -136,6 +132,7 @@ public: } virtual void reset() override { this->baseGameVersion = BaseGameVersion::pokeemerald; + this->recentMap = QString(); this->useEncounterJson = true; this->useCustomBorderSize = false; this->enableEventWeatherTrigger = true; @@ -151,6 +148,8 @@ public: } void setBaseGameVersion(BaseGameVersion baseGameVersion); BaseGameVersion getBaseGameVersion(); + void setRecentMap(const QString &map); + QString getRecentMap(); void setEncounterJsonActive(bool active); bool getEncounterJsonActive(); void setUsePoryScript(bool usePoryScript); @@ -186,6 +185,7 @@ protected: private: BaseGameVersion baseGameVersion; QString projectDir; + QString recentMap; bool useEncounterJson; bool usePoryScript; bool useCustomBorderSize; diff --git a/src/config.cpp b/src/config.cpp index 5ef3723f..daf53067 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -109,8 +109,6 @@ QString PorymapConfig::getConfigFilepath() { void PorymapConfig::parseConfigKeyValue(QString key, QString value) { if (key == "recent_project") { this->recentProject = value; - } else if (key == "recent_map") { - this->recentMap = value; } else if (key == "pretty_cursors") { bool ok; this->prettyCursors = value.toInt(&ok); @@ -202,7 +200,6 @@ void PorymapConfig::parseConfigKeyValue(QString key, QString value) { QMap PorymapConfig::getKeyValueMap() { QMap map; map.insert("recent_project", this->recentProject); - map.insert("recent_map", this->recentMap); map.insert("pretty_cursors", this->prettyCursors ? "1" : "0"); map.insert("map_sort_order", mapSortOrderMap.value(this->mapSortOrder)); map.insert("main_window_geometry", stringFromByteArray(this->mainWindowGeometry)); @@ -250,11 +247,6 @@ void PorymapConfig::setRecentProject(QString project) { this->save(); } -void PorymapConfig::setRecentMap(QString map) { - this->recentMap = map; - this->save(); -} - void PorymapConfig::setMapSortOrder(MapSortOrder order) { this->mapSortOrder = order; this->save(); @@ -339,10 +331,6 @@ QString PorymapConfig::getRecentProject() { return this->recentProject; } -QString PorymapConfig::getRecentMap() { - return this->recentMap; -} - MapSortOrder PorymapConfig::getMapSortOrder() { return this->mapSortOrder; } @@ -453,6 +441,8 @@ void ProjectConfig::parseConfigKeyValue(QString key, QString value) { this->baseGameVersion = BaseGameVersion::pokeemerald; logWarn(QString("Invalid config value for base_game_version: '%1'. Must be 'pokeruby', 'pokefirered' or 'pokeemerald'.").arg(value)); } + } else if (key == "recent_map") { + this->recentMap = value; } else if (key == "use_encounter_json") { bool ok; this->useEncounterJson = value.toInt(&ok); @@ -550,6 +540,7 @@ void ProjectConfig::setUnreadKeys() { QMap ProjectConfig::getKeyValueMap() { QMap map; map.insert("base_game_version", baseGameVersionMap.value(this->baseGameVersion)); + map.insert("recent_map", this->recentMap); map.insert("use_encounter_json", QString::number(this->useEncounterJson)); map.insert("use_poryscript", QString::number(this->usePoryScript)); map.insert("use_custom_border_size", QString::number(this->useCustomBorderSize)); @@ -623,6 +614,15 @@ BaseGameVersion ProjectConfig::getBaseGameVersion() { return this->baseGameVersion; } +void ProjectConfig::setRecentMap(const QString &map) { + this->recentMap = map; + this->save(); +} + +QString ProjectConfig::getRecentMap() { + return this->recentMap; +} + void ProjectConfig::setEncounterJsonActive(bool active) { this->useEncounterJson = active; this->save(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 14a8fc3d..836eafbd 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -541,7 +541,7 @@ QString MainWindow::getDefaultMap() { if (editor && editor->project) { QList names = editor->project->groupedMapNames; if (!names.isEmpty()) { - QString recentMap = porymapConfig.getRecentMap(); + QString recentMap = projectConfig.getRecentMap(); if (!recentMap.isNull() && recentMap.length() > 0) { for (int i = 0; i < names.length(); i++) { if (names.value(i).contains(recentMap)) { @@ -568,8 +568,8 @@ QString MainWindow::getExistingDirectory(QString dir) { void MainWindow::on_action_Open_Project_triggered() { QString recent = "."; - if (!porymapConfig.getRecentMap().isNull() && porymapConfig.getRecentMap().length() > 0) { - recent = porymapConfig.getRecentMap(); + if (!projectConfig.getRecentMap().isEmpty()) { + recent = projectConfig.getRecentMap(); } QString dir = getExistingDirectory(recent); if (!dir.isEmpty()) { @@ -711,7 +711,7 @@ void MainWindow::openWarpMap(QString map_name, QString warp_num) { } void MainWindow::setRecentMap(QString mapName) { - porymapConfig.setRecentMap(mapName); + projectConfig.setRecentMap(mapName); } void MainWindow::displayMapProperties() { From 3c2aa5d2e9cf4e76a1a19cc3b8b8d3fad6de9d81 Mon Sep 17 00:00:00 2001 From: Marcus Huderle Date: Fri, 12 Feb 2021 17:23:45 -0600 Subject: [PATCH 06/46] Fix out-of-bounds array access in bucket fill --- src/ui/mappixmapitem.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index 0e02545d..a5bae08f 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -488,13 +488,12 @@ void MapPixmapItem::floodFill( QPoint point = todo.takeAt(0); int x = point.x(); int y = point.y(); - visited[x + y * map->getWidth()] = true; - Block *block = map->getBlock(x, y); if (!block) { continue; } + visited[x + y * map->getWidth()] = true; int xDiff = x - initialX; int yDiff = y - initialY; int i = xDiff % selectionDimensions.x(); From e9c4d5b73f17d642adbd6649a6eeead89426846e Mon Sep 17 00:00:00 2001 From: Marcus Huderle Date: Sat, 13 Feb 2021 15:16:52 -0600 Subject: [PATCH 07/46] Fix getBlock() memory leak --- include/core/map.h | 2 +- src/core/map.cpp | 50 ++++---- src/mainwindow_scriptapi.cpp | 42 +++--- src/ui/collisionpixmapitem.cpp | 22 ++-- src/ui/mappixmapitem.cpp | 226 ++++++++++++++++----------------- 5 files changed, 169 insertions(+), 173 deletions(-) diff --git a/include/core/map.h b/include/core/map.h index 7052802a..cedb7c19 100644 --- a/include/core/map.h +++ b/include/core/map.h @@ -79,7 +79,7 @@ public: bool borderBlockChanged(int i, Blockdata * cache); void cacheBlockdata(); void cacheCollision(); - Block *getBlock(int x, int y); + bool getBlock(int x, int y, Block *out); void setBlock(int x, int y, Block block, bool enableScriptCallback = false); void floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation); void _floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation); diff --git a/src/core/map.cpp b/src/core/map.cpp index 14da4650..567c8a24 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -367,14 +367,15 @@ void Map::setBorderDimensions(int newWidth, int newHeight, bool setNewBlockdata) emit mapChanged(this); } -Block* Map::getBlock(int x, int y) { +bool Map::getBlock(int x, int y, Block *out) { if (layout->blockdata && layout->blockdata->blocks) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { int i = y * getWidth() + x; - return new Block(layout->blockdata->blocks->value(i)); + *out = layout->blockdata->blocks->value(i); + return true; } } - return nullptr; + return false; } void Map::setBlock(int x, int y, Block block, bool enableScriptCallback) { @@ -395,55 +396,54 @@ void Map::_floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_ QPoint point = todo.takeAt(0); x = point.x(); y = point.y(); - Block *block = getBlock(x, y); - if (!block) { + Block block; + if (!getBlock(x, y, &block)) { continue; } - uint old_coll = block->collision; - uint old_elev = block->elevation; + uint old_coll = block.collision; + uint old_elev = block.elevation; if (old_coll == collision && old_elev == elevation) { continue; } - block->collision = collision; - block->elevation = elevation; - setBlock(x, y, *block, true); - if ((block = getBlock(x + 1, y)) && block->collision == old_coll && block->elevation == old_elev) { + block.collision = collision; + block.elevation = elevation; + setBlock(x, y, block, true); + if (getBlock(x + 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { todo.append(QPoint(x + 1, y)); } - if ((block = getBlock(x - 1, y)) && block->collision == old_coll && block->elevation == old_elev) { + if (getBlock(x - 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { todo.append(QPoint(x - 1, y)); } - if ((block = getBlock(x, y + 1)) && block->collision == old_coll && block->elevation == old_elev) { + if (getBlock(x, y + 1, &block) && block.collision == old_coll && block.elevation == old_elev) { todo.append(QPoint(x, y + 1)); } - if ((block = getBlock(x, y - 1)) && block->collision == old_coll && block->elevation == old_elev) { + if (getBlock(x, y - 1, &block) && block.collision == old_coll && block.elevation == old_elev) { todo.append(QPoint(x, y - 1)); } } } void Map::floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation) { - Block *block = getBlock(x, y); - if (block && (block->collision != collision || block->elevation != elevation)) { + Block block;; + if (getBlock(x, y, &block) && (block.collision != collision || block.elevation != elevation)) { _floodFillCollisionElevation(x, y, collision, elevation); } } void Map::magicFillCollisionElevation(int initialX, int initialY, uint16_t collision, uint16_t elevation) { - Block *block = getBlock(initialX, initialY); - if (block && (block->collision != collision || block->elevation != elevation)) { - uint old_coll = block->collision; - uint old_elev = block->elevation; + Block block; + if (getBlock(initialX, initialY, &block) && (block.collision != collision || block.elevation != elevation)) { + uint old_coll = block.collision; + uint old_elev = block.elevation; for (int y = 0; y < getHeight(); y++) { for (int x = 0; x < getWidth(); x++) { - block = getBlock(x, y); - if (block && block->collision == old_coll && block->elevation == old_elev) { - block->collision = collision; - block->elevation = elevation; - setBlock(x, y, *block, true); + if (getBlock(x, y, &block) && block.collision == old_coll && block.elevation == old_elev) { + block.collision = collision; + block.elevation = elevation; + setBlock(x, y, block, true); } } } diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index b60ba820..8f073c79 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -6,11 +6,11 @@ QJSValue MainWindow::getBlock(int x, int y) { if (!this->editor || !this->editor->map) return QJSValue(); - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return Scripting::fromBlock(Block()); } - return Scripting::fromBlock(*block); + return Scripting::fromBlock(block); } void MainWindow::tryRedrawMapArea(bool forceRedraw) { @@ -51,21 +51,21 @@ void MainWindow::setBlocksFromSelection(int x, int y, bool forceRedraw, bool com int MainWindow::getMetatileId(int x, int y) { if (!this->editor || !this->editor->map) return 0; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return 0; } - return block->tile; + return block.tile; } void MainWindow::setMetatileId(int x, int y, int metatileId, bool forceRedraw, bool commitChanges) { if (!this->editor || !this->editor->map) return; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return; } - this->editor->map->setBlock(x, y, Block(metatileId, block->collision, block->elevation)); + this->editor->map->setBlock(x, y, Block(metatileId, block.collision, block.elevation)); this->tryCommitMapChanges(commitChanges); this->tryRedrawMapArea(forceRedraw); } @@ -73,21 +73,21 @@ void MainWindow::setMetatileId(int x, int y, int metatileId, bool forceRedraw, b int MainWindow::getCollision(int x, int y) { if (!this->editor || !this->editor->map) return 0; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return 0; } - return block->collision; + return block.collision; } void MainWindow::setCollision(int x, int y, int collision, bool forceRedraw, bool commitChanges) { if (!this->editor || !this->editor->map) return; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return; } - this->editor->map->setBlock(x, y, Block(block->tile, collision, block->elevation)); + this->editor->map->setBlock(x, y, Block(block.tile, collision, block.elevation)); this->tryCommitMapChanges(commitChanges); this->tryRedrawMapArea(forceRedraw); } @@ -95,21 +95,21 @@ void MainWindow::setCollision(int x, int y, int collision, bool forceRedraw, boo int MainWindow::getElevation(int x, int y) { if (!this->editor || !this->editor->map) return 0; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return 0; } - return block->elevation; + return block.elevation; } void MainWindow::setElevation(int x, int y, int elevation, bool forceRedraw, bool commitChanges) { if (!this->editor || !this->editor->map) return; - Block *block = this->editor->map->getBlock(x, y); - if (!block) { + Block block; + if (!this->editor->map->getBlock(x, y, &block)) { return; } - this->editor->map->setBlock(x, y, Block(block->tile, block->collision, elevation)); + this->editor->map->setBlock(x, y, Block(block.tile, block.collision, elevation)); this->tryCommitMapChanges(commitChanges); this->tryRedrawMapArea(forceRedraw); } diff --git a/src/ui/collisionpixmapitem.cpp b/src/ui/collisionpixmapitem.cpp index 48b8b368..3dbeb391 100644 --- a/src/ui/collisionpixmapitem.cpp +++ b/src/ui/collisionpixmapitem.cpp @@ -58,11 +58,11 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { this->lockedAxis = MapPixmapItem::Axis::None; } - Block *block = map->getBlock(pos.x(), pos.y()); - if (block) { - block->collision = this->movementPermissionsSelector->getSelectedCollision(); - block->elevation = this->movementPermissionsSelector->getSelectedElevation(); - map->setBlock(pos.x(), pos.y(), *block, true); + Block block; + if (map->getBlock(pos.x(), pos.y(), &block)) { + block.collision = this->movementPermissionsSelector->getSelectedCollision(); + block.elevation = this->movementPermissionsSelector->getSelectedElevation(); + map->setBlock(pos.x(), pos.y(), block, true); } Blockdata *newCollision = map->layout->blockdata->copy(); @@ -118,9 +118,9 @@ void CollisionPixmapItem::magicFill(QGraphicsSceneMouseEvent *event) { void CollisionPixmapItem::pick(QGraphicsSceneMouseEvent *event) { QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); - Block *block = map->getBlock(pos.x(), pos.y()); - if (block) { - this->movementPermissionsSelector->select(block->collision, block->elevation); + Block block; + if (map->getBlock(pos.x(), pos.y(), &block)) { + this->movementPermissionsSelector->select(block.collision, block.elevation); } } @@ -133,6 +133,8 @@ void CollisionPixmapItem::updateMovementPermissionSelection(QGraphicsSceneMouseE if (pos.y() < 0) pos.setY(0); if (pos.y() >= map->getHeight()) pos.setY(map->getHeight() - 1); - Block *block = map->getBlock(pos.x(), pos.y()); - this->movementPermissionsSelector->select(block->collision, block->elevation); + Block block; + if (map->getBlock(pos.x(), pos.y(), &block)) { + this->movementPermissionsSelector->select(block.collision, block.elevation); + } } diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index a5bae08f..5e524896 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -131,15 +131,15 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { for (int j = 0; j < selectionDimensions.y() && j + y < map->getHeight(); j++) { int actualX = i + x; int actualY = j + y; - Block *block = map->getBlock(actualX, actualY); - if (block) { + Block block; + if (map->getBlock(actualX, actualY, &block)) { int index = j * selectionDimensions.x() + i; - block->tile = selectedMetatiles->at(index); + block.tile = selectedMetatiles->at(index); if (selectedCollisions && selectedCollisions->length() == selectedMetatiles->length()) { - block->collision = selectedCollisions->at(index).first; - block->elevation = selectedCollisions->at(index).second; + block.collision = selectedCollisions->at(index).first; + block.elevation = selectedCollisions->at(index).second; } - map->setBlock(actualX, actualY, *block, !fromScriptCall); + map->setBlock(actualX, actualY, block, !fromScriptCall); } } @@ -176,7 +176,7 @@ QList MapPixmapItem::smartPathTable = QList({ 4, // 1111 }); -#define IS_SMART_PATH_TILE(block) (selectedMetatiles->contains(block->tile)) +#define IS_SMART_PATH_TILE(block) (selectedMetatiles->contains(block.tile)) void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { QPoint selectionDimensions = this->metatileSelector->getSelectionDimensions(); @@ -209,14 +209,14 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { continue; int actualX = i + x; int actualY = j + y; - Block *block = map->getBlock(actualX, actualY); - if (block) { - block->tile = openTile; + Block block; + if (map->getBlock(actualX, actualY, &block)) { + block.tile = openTile; if (setCollisions) { - block->collision = openTileCollision; - block->elevation = openTileElevation; + block.collision = openTileCollision; + block.elevation = openTileElevation; } - map->setBlock(actualX, actualY, *block, !fromScriptCall); + map->setBlock(actualX, actualY, block, !fromScriptCall); } } @@ -234,33 +234,33 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { // Ignore tiles that aren't part of the smart path set. int actualX = i + x; int actualY = j + y; - Block *block = map->getBlock(actualX, actualY); - if (!block || !IS_SMART_PATH_TILE(block)) { + Block block; + if (!map->getBlock(actualX, actualY, &block) || !IS_SMART_PATH_TILE(block)) { continue; } int id = 0; - Block *top = map->getBlock(actualX, actualY - 1); - Block *right = map->getBlock(actualX + 1, actualY); - Block *bottom = map->getBlock(actualX, actualY + 1); - Block *left = map->getBlock(actualX - 1, actualY); + Block top; + Block right; + Block bottom; + Block left; // Get marching squares value, to determine which tile to use. - if (top && IS_SMART_PATH_TILE(top)) + if (map->getBlock(actualX, actualY - 1, &top) && IS_SMART_PATH_TILE(top)) id += 1; - if (right && IS_SMART_PATH_TILE(right)) + if (map->getBlock(actualX + 1, actualY, &right) && IS_SMART_PATH_TILE(right)) id += 2; - if (bottom && IS_SMART_PATH_TILE(bottom)) + if (map->getBlock(actualX, actualY + 1, &bottom) && IS_SMART_PATH_TILE(bottom)) id += 4; - if (left && IS_SMART_PATH_TILE(left)) + if (map->getBlock(actualX - 1, actualY, &left) && IS_SMART_PATH_TILE(left)) id += 8; - block->tile = selectedMetatiles->at(smartPathTable[id]); + block.tile = selectedMetatiles->at(smartPathTable[id]); if (setCollisions) { - block->collision = selectedCollisions->at(smartPathTable[id]).first; - block->elevation = selectedCollisions->at(smartPathTable[id]).second; + block.collision = selectedCollisions->at(smartPathTable[id]).first; + block.elevation = selectedCollisions->at(smartPathTable[id]).second; } - map->setBlock(actualX, actualY, *block, !fromScriptCall); + map->setBlock(actualX, actualY, block, !fromScriptCall); } if (!fromScriptCall) { @@ -324,8 +324,10 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) { selection_origin = QPoint(pos.x(), pos.y()); selection.clear(); selection.append(QPoint(pos.x(), pos.y())); - Block *block = map->getBlock(pos.x(), pos.y()); - this->metatileSelector->selectFromMap(block->tile, block->collision, block->elevation); + Block block; + if (map->getBlock(pos.x(), pos.y(), &block)) { + this->metatileSelector->selectFromMap(block.tile, block.collision, block.elevation); + } } else if (event->type() == QEvent::GraphicsSceneMouseMove) { int x1 = selection_origin.x(); int y1 = selection_origin.y(); @@ -345,10 +347,15 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) { for (QPoint point : selection) { int x = point.x(); int y = point.y(); - metatiles.append(map->getBlock(x, y)->tile); + Block block; + if (map->getBlock(x, y, &block)) { + metatiles.append(block.tile); + } int blockIndex = y * map->getWidth() + x; - Block block = map->layout->blockdata->blocks->at(blockIndex); - collisions.append(QPair(block.collision, block.elevation)); + block = map->layout->blockdata->blocks->at(blockIndex); + auto collision = block.collision; + auto elevation = block.elevation; + collisions.append(QPair(collision, elevation)); } this->metatileSelector->setExternalSelection(x2 - x1 + 1, y2 - y1 + 1, metatiles, collisions); @@ -361,11 +368,11 @@ void MapPixmapItem::floodFill(QGraphicsSceneMouseEvent *event) { actionId_++; } else { QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); - Block *block = map->getBlock(pos.x(), pos.y()); + Block block; QList *selectedMetatiles = this->metatileSelector->getSelectedMetatiles(); QPoint selectionDimensions = this->metatileSelector->getSelectionDimensions(); int tile = selectedMetatiles->first(); - if (selectedMetatiles->count() > 1 || (block && block->tile != tile)) { + if (selectedMetatiles->count() > 1 || (map->getBlock(pos.x(), pos.y(), &block) && block.tile != tile)) { bool smartPathsEnabled = event->modifiers() & Qt::ShiftModifier; if ((this->settings->smartPathsEnabled || smartPathsEnabled) && selectionDimensions.x() == 3 && selectionDimensions.y() == 3) this->floodFillSmartPath(pos.x(), pos.y()); @@ -391,6 +398,7 @@ void MapPixmapItem::magicFill(int x, int y, uint16_t metatileId, bool fromScript QPoint selectionDimensions(1, 1); QList *selectedMetatiles = new QList({ metatileId }); this->magicFill(x, y, selectionDimensions, selectedMetatiles, nullptr, fromScriptCall); + delete selectedMetatiles; } void MapPixmapItem::magicFill(int x, int y, bool fromScriptCall) { @@ -407,10 +415,9 @@ void MapPixmapItem::magicFill( QList *selectedMetatiles, QList> *selectedCollisions, bool fromScriptCall) { - Block *block = map->getBlock(initialX, initialY); - if (block) { - if (selectedMetatiles->length() == 1 && selectedMetatiles->value(0) == block->tile) { - logInfo("early exit"); + Block block; + if (map->getBlock(initialX, initialY, &block)) { + if (selectedMetatiles->length() == 1 && selectedMetatiles->value(0) == block.tile) { return; } @@ -418,11 +425,10 @@ void MapPixmapItem::magicFill( if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); - uint16_t tile = block->tile; + uint16_t tile = block.tile; for (int y = 0; y < map->getHeight(); y++) { for (int x = 0; x < map->getWidth(); x++) { - block = map->getBlock(x, y); - if (block && block->tile == tile) { + if (map->getBlock(x, y, &block) && block.tile == tile) { int xDiff = x - initialX; int yDiff = y - initialY; int i = xDiff % selectionDimensions.x(); @@ -430,12 +436,12 @@ void MapPixmapItem::magicFill( if (i < 0) i = selectionDimensions.x() + i; if (j < 0) j = selectionDimensions.y() + j; int index = j * selectionDimensions.x() + i; - block->tile = selectedMetatiles->at(index); + block.tile = selectedMetatiles->at(index); if (setCollisions) { - block->collision = selectedCollisions->at(index).first; - block->elevation = selectedCollisions->at(index).second; + block.collision = selectedCollisions->at(index).first; + block.elevation = selectedCollisions->at(index).second; } - map->setBlock(x, y, *block, !fromScriptCall); + map->setBlock(x, y, block, !fromScriptCall); } } } @@ -463,6 +469,7 @@ void MapPixmapItem::floodFill(int initialX, int initialY, uint16_t metatileId, b QPoint selectionDimensions(1, 1); QList *selectedMetatiles = new QList({ metatileId }); this->floodFill(initialX, initialY, selectionDimensions, selectedMetatiles, nullptr, fromScriptCall); + delete selectedMetatiles; } void MapPixmapItem::floodFill( @@ -473,27 +480,24 @@ void MapPixmapItem::floodFill( QList> *selectedCollisions, bool fromScriptCall) { bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); - - int numMetatiles = map->getWidth() * map->getHeight(); - bool *visited = new bool[numMetatiles]; - for (int i = 0; i < numMetatiles; i++) - visited[i] = false; - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); + if (!fromScriptCall) { + oldMetatiles = map->layout->blockdata->copy(); + } + QSet visited; QList todo; todo.append(QPoint(initialX, initialY)); while (todo.length()) { QPoint point = todo.takeAt(0); int x = point.x(); int y = point.y(); - Block *block = map->getBlock(x, y); - if (!block) { + Block block; + if (!map->getBlock(x, y, &block)) { continue; } - visited[x + y * map->getWidth()] = true; + visited.insert(x + y * map->getWidth()); int xDiff = x - initialX; int yDiff = y - initialY; int i = xDiff % selectionDimensions.x(); @@ -502,30 +506,30 @@ void MapPixmapItem::floodFill( if (j < 0) j = selectionDimensions.y() + j; int index = j * selectionDimensions.x() + i; uint16_t tile = selectedMetatiles->at(index); - uint16_t old_tile = block->tile; + uint16_t old_tile = block.tile; if (selectedMetatiles->count() != 1 || old_tile != tile) { - block->tile = tile; + block.tile = tile; if (setCollisions) { - block->collision = selectedCollisions->at(index).first; - block->elevation = selectedCollisions->at(index).second; + block.collision = selectedCollisions->at(index).first; + block.elevation = selectedCollisions->at(index).second; } - map->setBlock(x, y, *block, !fromScriptCall); + map->setBlock(x, y, block, !fromScriptCall); } - if (!visited[x + 1 + y * map->getWidth()] && (block = map->getBlock(x + 1, y)) && block->tile == old_tile) { + if (!visited.contains(x + 1 + y * map->getWidth()) && map->getBlock(x + 1, y, &block) && block.tile == old_tile) { todo.append(QPoint(x + 1, y)); - visited[x + 1 + y * map->getWidth()] = true; + visited.insert(x + 1 + y * map->getWidth()); } - if (!visited[x - 1 + y * map->getWidth()] && (block = map->getBlock(x - 1, y)) && block->tile == old_tile) { + if (!visited.contains(x - 1 + y * map->getWidth()) && map->getBlock(x - 1, y, &block) && block.tile == old_tile) { todo.append(QPoint(x - 1, y)); - visited[x - 1 + y * map->getWidth()] = true; + visited.insert(x - 1 + y * map->getWidth()); } - if (!visited[x + (y + 1) * map->getWidth()] && (block = map->getBlock(x, y + 1)) && block->tile == old_tile) { + if (!visited.contains(x + (y + 1) * map->getWidth()) && map->getBlock(x, y + 1, &block) && block.tile == old_tile) { todo.append(QPoint(x, y + 1)); - visited[x + (y + 1) * map->getWidth()] = true; + visited.insert(x + (y + 1) * map->getWidth()); } - if (!visited[x + (y - 1) * map->getWidth()] && (block = map->getBlock(x, y - 1)) && block->tile == old_tile) { + if (!visited.contains(x + (y - 1) * map->getWidth()) && map->getBlock(x, y - 1, &block) && block.tile == old_tile) { todo.append(QPoint(x, y - 1)); - visited[x + (y - 1) * map->getWidth()] = true; + visited.insert(x + (y - 1) * map->getWidth()); } } @@ -538,8 +542,6 @@ void MapPixmapItem::floodFill( map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } - - delete[] visited; } void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScriptCall) { @@ -571,95 +573,89 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri QPoint point = todo.takeAt(0); int x = point.x(); int y = point.y(); - - Block *block = map->getBlock(x, y); - if (!block) { + Block block; + if (!map->getBlock(x, y, &block)) { continue; } - uint16_t old_tile = block->tile; + uint16_t old_tile = block.tile; if (old_tile == openTile) { continue; } - block->tile = openTile; + block.tile = openTile; if (setCollisions) { - block->collision = openTileCollision; - block->elevation = openTileElevation; + block.collision = openTileCollision; + block.elevation = openTileElevation; } - map->setBlock(x, y, *block, !fromScriptCall); - if ((block = map->getBlock(x + 1, y)) && block->tile == old_tile) { + map->setBlock(x, y, block, !fromScriptCall); + if (map->getBlock(x + 1, y, &block) && block.tile == old_tile) { todo.append(QPoint(x + 1, y)); } - if ((block = map->getBlock(x - 1, y)) && block->tile == old_tile) { + if (map->getBlock(x - 1, y, &block) && block.tile == old_tile) { todo.append(QPoint(x - 1, y)); } - if ((block = map->getBlock(x, y + 1)) && block->tile == old_tile) { + if (map->getBlock(x, y + 1, &block) && block.tile == old_tile) { todo.append(QPoint(x, y + 1)); } - if ((block = map->getBlock(x, y - 1)) && block->tile == old_tile) { + if (map->getBlock(x, y - 1, &block) && block.tile == old_tile) { todo.append(QPoint(x, y - 1)); } } // Go back and resolve the flood-filled edge tiles. // Mark tiles as visited while we go. - int numMetatiles = map->getWidth() * map->getHeight(); - bool *visited = new bool[numMetatiles]; - for (int i = 0; i < numMetatiles; i++) - visited[i] = false; - + QSet visited; todo.append(QPoint(initialX, initialY)); while (todo.length()) { QPoint point = todo.takeAt(0); int x = point.x(); int y = point.y(); - visited[x + y * map->getWidth()] = true; - - Block *block = map->getBlock(x, y); - if (!block) { + Block block; + if (!map->getBlock(x, y, &block)) { continue; } + visited.insert(x + y * map->getWidth()); int id = 0; - Block *top = map->getBlock(x, y - 1); - Block *right = map->getBlock(x + 1, y); - Block *bottom = map->getBlock(x, y + 1); - Block *left = map->getBlock(x - 1, y); + Block top; + Block right; + Block bottom; + Block left; // Get marching squares value, to determine which tile to use. - if (top && IS_SMART_PATH_TILE(top)) + if (map->getBlock(x, y - 1, &top) && IS_SMART_PATH_TILE(top)) id += 1; - if (right && IS_SMART_PATH_TILE(right)) + if (map->getBlock(x + 1, y, &right) && IS_SMART_PATH_TILE(right)) id += 2; - if (bottom && IS_SMART_PATH_TILE(bottom)) + if (map->getBlock(x, y + 1, &bottom) && IS_SMART_PATH_TILE(bottom)) id += 4; - if (left && IS_SMART_PATH_TILE(left)) + if (map->getBlock(x - 1, y, &left) && IS_SMART_PATH_TILE(left)) id += 8; - block->tile = selectedMetatiles->at(smartPathTable[id]); + block.tile = selectedMetatiles->at(smartPathTable[id]); if (setCollisions) { - block->collision = selectedCollisions->at(smartPathTable[id]).first; - block->elevation = selectedCollisions->at(smartPathTable[id]).second; + block.collision = selectedCollisions->at(smartPathTable[id]).first; + block.elevation = selectedCollisions->at(smartPathTable[id]).second; } - map->setBlock(x, y, *block, !fromScriptCall); + map->setBlock(x, y, block, !fromScriptCall); // Visit neighbors if they are smart-path tiles, and don't revisit any. - if (!visited[x + 1 + y * map->getWidth()] && (block = map->getBlock(x + 1, y)) && IS_SMART_PATH_TILE(block)) { + if (!visited.contains(x + 1 + y * map->getWidth()) && map->getBlock(x + 1, y, &block) && IS_SMART_PATH_TILE(block)) { todo.append(QPoint(x + 1, y)); - visited[x + 1 + y * map->getWidth()] = true; + visited.insert(x + 1 + y * map->getWidth()); } - if (!visited[x - 1 + y * map->getWidth()] && (block = map->getBlock(x - 1, y)) && IS_SMART_PATH_TILE(block)) { + if (!visited.contains(x - 1 + y * map->getWidth()) && map->getBlock(x - 1, y, &block) && IS_SMART_PATH_TILE(block)) { todo.append(QPoint(x - 1, y)); - visited[x - 1 + y * map->getWidth()] = true; + visited.insert(x - 1 + y * map->getWidth()); } - if (!visited[x + (y + 1) * map->getWidth()] && (block = map->getBlock(x, y + 1)) && IS_SMART_PATH_TILE(block)) { + if (!visited.contains(x + (y + 1) * map->getWidth()) && map->getBlock(x, y + 1, &block) && IS_SMART_PATH_TILE(block)) { todo.append(QPoint(x, y + 1)); - visited[x + (y + 1) * map->getWidth()] = true; + visited.insert(x + (y + 1) * map->getWidth()); } - if (!visited[x + (y - 1) * map->getWidth()] && (block = map->getBlock(x, y - 1)) && IS_SMART_PATH_TILE(block)) { + if (!visited.contains(x + (y - 1) * map->getWidth()) && map->getBlock(x, y - 1, &block) && IS_SMART_PATH_TILE(block)) { todo.append(QPoint(x, y - 1)); - visited[x + (y - 1) * map->getWidth()] = true; + visited.insert(x + (y - 1) * map->getWidth()); } } @@ -672,15 +668,13 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } - - delete[] visited; } void MapPixmapItem::pick(QGraphicsSceneMouseEvent *event) { QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); - Block *block = map->getBlock(pos.x(), pos.y()); - if (block) { - this->metatileSelector->selectFromMap(block->tile, block->collision, block->elevation); + Block block; + if (map->getBlock(pos.x(), pos.y(), &block)) { + this->metatileSelector->selectFromMap(block.tile, block.collision, block.elevation); } } From ef449f6f8d96dd02605d9c6954334122387153c1 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 09:16:23 -0500 Subject: [PATCH 08/46] Upgrade signal/slot connections in MainWindow --- src/mainwindow.cpp | 52 ++++++++++++++++++------------------ src/mainwindow_scriptapi.cpp | 2 +- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 836eafbd..14ccf8d6 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -189,11 +189,11 @@ void MainWindow::initCustomUI() { void MainWindow::initExtraSignals() { // Right-clicking on items in the map list tree view brings up a context menu. ui->mapList->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->mapList, SIGNAL(customContextMenuRequested(const QPoint &)), - this, SLOT(onOpenMapListContextMenu(const QPoint &))); + connect(ui->mapList, &QTreeView::customContextMenuRequested, + this, &MainWindow::onOpenMapListContextMenu); // other signals - connect(ui->newEventToolButton, SIGNAL(newEventAdded(QString)), this, SLOT(addNewEvent(QString))); + connect(ui->newEventToolButton, &NewEventToolButton::newEventAdded, this, &MainWindow::addNewEvent); connect(ui->tabWidget_EventType, &QTabWidget::currentChanged, this, &MainWindow::eventTabChanged); // Change pages on wild encounter groups @@ -230,12 +230,12 @@ void MainWindow::initExtraSignals() { void MainWindow::initEditor() { this->editor = new Editor(ui); - connect(this->editor, SIGNAL(objectsChanged()), this, SLOT(updateObjects())); - connect(this->editor, SIGNAL(selectedObjectsChanged()), this, SLOT(updateSelectedObjects())); - connect(this->editor, SIGNAL(loadMapRequested(QString, QString)), this, SLOT(onLoadMapRequested(QString, QString))); - connect(this->editor, SIGNAL(warpEventDoubleClicked(QString,QString)), this, SLOT(openWarpMap(QString,QString))); - connect(this->editor, SIGNAL(currentMetatilesSelectionChanged()), this, SLOT(currentMetatilesSelectionChanged())); - connect(this->editor, SIGNAL(wildMonDataChanged()), this, SLOT(onWildMonDataChanged())); + connect(this->editor, &Editor::objectsChanged, this, &MainWindow::updateObjects); + connect(this->editor, &Editor::selectedObjectsChanged, this, &MainWindow::updateSelectedObjects); + connect(this->editor, &Editor::loadMapRequested, this, &MainWindow::onLoadMapRequested); + connect(this->editor, &Editor::warpEventDoubleClicked, this, &MainWindow::openWarpMap); + connect(this->editor, &Editor::currentMetatilesSelectionChanged, this, &MainWindow::currentMetatilesSelectionChanged); + connect(this->editor, &Editor::wildMonDataChanged, this, &MainWindow::onWildMonDataChanged); connect(this->editor, &Editor::mapRulerStatusChanged, this, &MainWindow::onMapRulerStatusChanged); connect(ui->toolButton_Open_Scripts, &QToolButton::pressed, this->editor, &Editor::openMapScripts); connect(ui->actionOpen_Project_in_Text_Editor, &QAction::triggered, this->editor, &Editor::openProjectInTextEditor); @@ -492,9 +492,9 @@ bool MainWindow::openProject(QString dir) { if (!already_open) { editor->closeProject(); editor->project = new Project(this); - QObject::connect(editor->project, SIGNAL(reloadProject()), this, SLOT(on_action_Reload_Project_triggered())); - QObject::connect(editor->project, SIGNAL(mapCacheCleared()), this, SLOT(onMapCacheCleared())); - QObject::connect(editor->project, &Project::uncheckMonitorFilesAction, [this] () { ui->actionMonitor_Project_Files->setChecked(false); }); + QObject::connect(editor->project, &Project::reloadProject, this, &MainWindow::on_action_Reload_Project_triggered); + QObject::connect(editor->project, &Project::mapCacheCleared, this, &MainWindow::onMapCacheCleared); + QObject::connect(editor->project, &Project::uncheckMonitorFilesAction, [this]() { ui->actionMonitor_Project_Files->setChecked(false); }); on_actionMonitor_Project_Files_triggered(porymapConfig.getMonitorFiles()); editor->project->set_root(dir); success = loadDataStructures() @@ -624,8 +624,8 @@ bool MainWindow::setMap(QString map_name, bool scrollTreeView) { showWindowTitle(); - connect(editor->map, SIGNAL(mapChanged(Map*)), this, SLOT(onMapChanged(Map *))); - connect(editor->map, SIGNAL(mapNeedsRedrawing()), this, SLOT(onMapNeedsRedrawing())); + connect(editor->map, &Map::mapChanged, this, &MainWindow::onMapChanged); + connect(editor->map, &Map::mapNeedsRedrawing, this, &MainWindow::onMapNeedsRedrawing); setRecentMap(map_name); updateMapList(); @@ -1066,21 +1066,21 @@ void MainWindow::onOpenMapListContextMenu(const QPoint &point) QMenu* menu = new QMenu(this); QActionGroup* actions = new QActionGroup(menu); actions->addAction(menu->addAction("Add New Map to Group"))->setData(groupNum); - connect(actions, SIGNAL(triggered(QAction*)), this, SLOT(onAddNewMapToGroupClick(QAction*))); + connect(actions, &QActionGroup::triggered, this, &MainWindow::onAddNewMapToGroupClick); menu->exec(QCursor::pos()); } else if (itemType == "map_sec") { QString secName = selectedItem->data(Qt::UserRole).toString(); QMenu* menu = new QMenu(this); QActionGroup* actions = new QActionGroup(menu); actions->addAction(menu->addAction("Add New Map to Area"))->setData(secName); - connect(actions, SIGNAL(triggered(QAction*)), this, SLOT(onAddNewMapToAreaClick(QAction*))); + connect(actions, &QActionGroup::triggered, this, &MainWindow::onAddNewMapToAreaClick); menu->exec(QCursor::pos()); } else if (itemType == "map_layout") { QString layoutId = selectedItem->data(MapListUserRoles::TypeRole2).toString(); QMenu* menu = new QMenu(this); QActionGroup* actions = new QActionGroup(menu); actions->addAction(menu->addAction("Add New Map with Layout"))->setData(layoutId); - connect(actions, SIGNAL(triggered(QAction*)), this, SLOT(onAddNewMapToLayoutClick(QAction*))); + connect(actions, &QActionGroup::triggered, this, &MainWindow::onAddNewMapToLayoutClick); menu->exec(QCursor::pos()); } } @@ -1132,7 +1132,7 @@ void MainWindow::onNewMapCreated() { editor->save();// required } - disconnect(this->newmapprompt, SIGNAL(applied()), this, SLOT(onNewMapCreated())); + disconnect(this->newmapprompt, &NewMapPopup::applied, this, &MainWindow::onNewMapCreated); } void MainWindow::openNewMapPopupWindow(int type, QVariant data) { @@ -1157,7 +1157,7 @@ void MainWindow::openNewMapPopupWindow(int type, QVariant data) { this->newmapprompt->init(type, 0, QString(), data.toString()); break; } - connect(this->newmapprompt, SIGNAL(applied()), this, SLOT(onNewMapCreated())); + connect(this->newmapprompt, &NewMapPopup::applied, this, &MainWindow::onNewMapCreated); connect(this->newmapprompt, &QObject::destroyed, [=](QObject *) { this->newmapprompt = nullptr; }); this->newmapprompt->setAttribute(Qt::WA_DeleteOnClose); } @@ -1682,7 +1682,7 @@ void MainWindow::updateSelectedObjects() { if (delta) editor->map->editHistory.push(new EventMove(QList() << item->event, delta, 0, x->getActionId())); }); - connect(item, SIGNAL(xChanged(int)), x, SLOT(setValue(int))); + connect(item, &DraggablePixmapItem::xChanged, x, &NoScrollSpinBox::setValue); y->setValue(item->event->y()); connect(y, QOverload::of(&QSpinBox::valueChanged), [this, item, y](int value) { @@ -1690,11 +1690,11 @@ void MainWindow::updateSelectedObjects() { if (delta) editor->map->editHistory.push(new EventMove(QList() << item->event, 0, delta, y->getActionId())); }); - connect(item, SIGNAL(yChanged(int)), y, SLOT(setValue(int))); + connect(item, &DraggablePixmapItem::yChanged, y, &NoScrollSpinBox::setValue); z->setValue(item->event->elevation()); - connect(z, SIGNAL(valueChanged(QString)), item, SLOT(set_elevation(QString))); - connect(item, SIGNAL(elevationChanged(int)), z, SLOT(setValue(int))); + connect(z, &NoScrollSpinBox::textChanged, item, &DraggablePixmapItem::set_elevation); + connect(item, &DraggablePixmapItem::elevationChanged, z, &NoScrollSpinBox::setValue); QString event_type = item->event->get("event_type"); QString event_group_type = item->event->get("event_group_type"); @@ -1717,7 +1717,7 @@ void MainWindow::updateSelectedObjects() { } frame->ui->label_spritePixmap->setPixmap(item->event->pixmap); - connect(item, SIGNAL(spriteChanged(QPixmap)), frame->ui->label_spritePixmap, SLOT(setPixmap(QPixmap))); + connect(item, &DraggablePixmapItem::spriteChanged, frame->ui->label_spritePixmap, &QLabel::setPixmap); frame->ui->sprite->setVisible(false); @@ -2608,7 +2608,7 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() errorLabel->setVisible(true); } }); - connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); form.addRow(errorLabel); @@ -2668,7 +2668,7 @@ void MainWindow::on_actionTileset_Editor_triggered() void MainWindow::initTilesetEditor() { this->tilesetEditor = new TilesetEditor(this->editor->project, this->editor->map, this); - connect(this->tilesetEditor, SIGNAL(tilesetsSaved(QString, QString)), this, SLOT(onTilesetsSaved(QString, QString))); + connect(this->tilesetEditor, &TilesetEditor::tilesetsSaved, this, &MainWindow::onTilesetsSaved); connect(this->tilesetEditor, &QObject::destroyed, [=](QObject *) { this->tilesetEditor = nullptr; }); } diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index 8f073c79..494cb779 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -502,7 +502,7 @@ void MainWindow::setTimeout(QJSValue callback, int milliseconds) { connect(timer, &QTimer::timeout, [=](){ this->invokeCallback(callback); }); - connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater())); + connect(timer, &QTimer::timeout, timer, &QTimer::deleteLater); timer->setSingleShot(true); timer->start(milliseconds); } From 51dccf77738f94cbbc850641e514af726892abe0 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 09:48:50 -0500 Subject: [PATCH 09/46] Upgrade signal/slot connections in Editor --- src/editor.cpp | 71 +++++++++++++++++++++++++------------------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/src/editor.cpp b/src/editor.cpp index cd11a598..d2da8aca 100644 --- a/src/editor.cpp +++ b/src/editor.cpp @@ -316,7 +316,7 @@ void Editor::addNewWildMonGroup(QWidget *window) { dialog.accept(); } }); - connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); form.addRow(&buttonBox); if (dialog.exec() == QDialog::Accepted) { @@ -511,8 +511,8 @@ void Editor::configureEncounterJSON(QWidget *window) { QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog); - connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept())); - connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); // lambda: Get a QStringList of the existing field names. auto getFieldNames = [&tempFields]() { @@ -552,8 +552,8 @@ void Editor::configureEncounterJSON(QWidget *window) { QDialog newNameDialog(nullptr, Qt::WindowTitleHint | Qt::WindowCloseButtonHint); newNameDialog.setWindowModality(Qt::NonModal); QDialogButtonBox newFieldButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &newNameDialog); - connect(&newFieldButtonBox, SIGNAL(accepted()), &newNameDialog, SLOT(accept())); - connect(&newFieldButtonBox, SIGNAL(rejected()), &newNameDialog, SLOT(reject())); + connect(&newFieldButtonBox, &QDialogButtonBox::accepted, &newNameDialog, &QDialog::accept); + connect(&newFieldButtonBox, &QDialogButtonBox::rejected, &newNameDialog, &QDialog::reject); QLineEdit *newNameEdit = new QLineEdit; newNameEdit->setClearButtonEnabled(true); @@ -1320,12 +1320,12 @@ void Editor::displayMetatileSelector() { scene_metatiles = new QGraphicsScene; if (!metatile_selector_item) { metatile_selector_item = new MetatileSelector(8, map); - connect(metatile_selector_item, SIGNAL(hoveredMetatileSelectionChanged(uint16_t)), - this, SLOT(onHoveredMetatileSelectionChanged(uint16_t))); - connect(metatile_selector_item, SIGNAL(hoveredMetatileSelectionCleared()), - this, SLOT(onHoveredMetatileSelectionCleared())); - connect(metatile_selector_item, SIGNAL(selectedMetatilesChanged()), - this, SLOT(onSelectedMetatilesChanged())); + connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionChanged, + this, &Editor::onHoveredMetatileSelectionChanged); + connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionCleared, + this, &Editor::onHoveredMetatileSelectionCleared); + connect(metatile_selector_item, &MetatileSelector::selectedMetatilesChanged, + this, &Editor::onSelectedMetatilesChanged); metatile_selector_item->select(0); } else { metatile_selector_item->setMap(map); @@ -1337,16 +1337,11 @@ void Editor::displayMetatileSelector() { void Editor::displayMapMetatiles() { map_item = new MapPixmapItem(map, this->metatile_selector_item, this->settings); - connect(map_item, SIGNAL(mouseEvent(QGraphicsSceneMouseEvent*,MapPixmapItem*)), - this, SLOT(mouseEvent_map(QGraphicsSceneMouseEvent*,MapPixmapItem*))); - connect(map_item, SIGNAL(startPaint(QGraphicsSceneMouseEvent*,MapPixmapItem*)), - this, SLOT(onMapStartPaint(QGraphicsSceneMouseEvent*,MapPixmapItem*))); - connect(map_item, SIGNAL(endPaint(QGraphicsSceneMouseEvent*,MapPixmapItem*)), - this, SLOT(onMapEndPaint(QGraphicsSceneMouseEvent*,MapPixmapItem*))); - connect(map_item, SIGNAL(hoveredMapMetatileChanged(const QPoint&)), - this, SLOT(onHoveredMapMetatileChanged(const QPoint&))); - connect(map_item, SIGNAL(hoveredMapMetatileCleared()), - this, SLOT(onHoveredMapMetatileCleared())); + connect(map_item, &MapPixmapItem::mouseEvent, this, &Editor::mouseEvent_map); + connect(map_item, &MapPixmapItem::startPaint, this, &Editor::onMapStartPaint); + connect(map_item, &MapPixmapItem::endPaint, this, &Editor::onMapEndPaint); + connect(map_item, &MapPixmapItem::hoveredMapMetatileChanged, this, &Editor::onHoveredMapMetatileChanged); + connect(map_item, &MapPixmapItem::hoveredMapMetatileCleared, this, &Editor::onHoveredMapMetatileCleared); map_item->draw(true); scene->addItem(map_item); @@ -1366,13 +1361,13 @@ void Editor::displayMapMovementPermissions() { scene->removeItem(collision_item); delete collision_item; } - collision_item = new CollisionPixmapItem(map, this->movement_permissions_selector_item, this->metatile_selector_item, this->settings, &this->collisionOpacity); - connect(collision_item, SIGNAL(mouseEvent(QGraphicsSceneMouseEvent*,CollisionPixmapItem*)), - this, SLOT(mouseEvent_collision(QGraphicsSceneMouseEvent*,CollisionPixmapItem*))); - connect(collision_item, SIGNAL(hoveredMapMovementPermissionChanged(int, int)), - this, SLOT(onHoveredMapMovementPermissionChanged(int, int))); - connect(collision_item, SIGNAL(hoveredMapMovementPermissionCleared()), - this, SLOT(onHoveredMapMovementPermissionCleared())); + collision_item = new CollisionPixmapItem(map, this->movement_permissions_selector_item, + this->metatile_selector_item, this->settings, &this->collisionOpacity); + connect(collision_item, &CollisionPixmapItem::mouseEvent, this, &Editor::mouseEvent_collision); + connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionChanged, + this, &Editor::onHoveredMapMovementPermissionChanged); + connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionCleared, + this, &Editor::onHoveredMapMovementPermissionCleared); collision_item->draw(true); scene->addItem(collision_item); @@ -1389,7 +1384,8 @@ void Editor::displayBorderMetatiles() { selected_border_metatiles_item->draw(); scene_selected_border_metatiles->addItem(selected_border_metatiles_item); - connect(selected_border_metatiles_item, SIGNAL(borderMetatilesChanged()), this, SLOT(onBorderMetatilesChanged())); + connect(selected_border_metatiles_item, &BorderMetatilesPixmapItem::borderMetatilesChanged, + this, &Editor::onBorderMetatilesChanged); } void Editor::displayCurrentMetatilesSelection() { @@ -1421,10 +1417,10 @@ void Editor::displayMovementPermissionSelector() { scene_collision_metatiles = new QGraphicsScene; if (!movement_permissions_selector_item) { movement_permissions_selector_item = new MovementPermissionsSelector(); - connect(movement_permissions_selector_item, SIGNAL(hoveredMovementPermissionChanged(uint16_t, uint16_t)), - this, SLOT(onHoveredMovementPermissionChanged(uint16_t, uint16_t))); - connect(movement_permissions_selector_item, SIGNAL(hoveredMovementPermissionCleared()), - this, SLOT(onHoveredMovementPermissionCleared())); + connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionChanged, + this, &Editor::onHoveredMovementPermissionChanged); + connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionCleared, + this, &Editor::onHoveredMovementPermissionCleared); movement_permissions_selector_item->select(0, 3); } @@ -1540,9 +1536,12 @@ void Editor::createConnectionItem(MapConnection* connection, bool hide) { connection_edit_item->setY(y); connection_edit_item->setZValue(-1); scene->addItem(connection_edit_item); - connect(connection_edit_item, SIGNAL(connectionMoved(MapConnection*)), this, SLOT(onConnectionMoved(MapConnection*))); - connect(connection_edit_item, SIGNAL(connectionItemSelected(ConnectionPixmapItem*)), this, SLOT(onConnectionItemSelected(ConnectionPixmapItem*))); - connect(connection_edit_item, SIGNAL(connectionItemDoubleClicked(ConnectionPixmapItem*)), this, SLOT(onConnectionItemDoubleClicked(ConnectionPixmapItem*))); + connect(connection_edit_item, &ConnectionPixmapItem::connectionMoved, + this, &Editor::onConnectionMoved); + connect(connection_edit_item, &ConnectionPixmapItem::connectionItemSelected, + this, &Editor::onConnectionItemSelected); + connect(connection_edit_item, &ConnectionPixmapItem::connectionItemDoubleClicked, + this, &Editor::onConnectionItemDoubleClicked); connection_edit_items.append(connection_edit_item); } From 7937c3fe9873acc28833b6b8e1e7ab378036573e Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 10:07:55 -0500 Subject: [PATCH 10/46] Upgrade signal/slot connections in all other files --- src/config.cpp | 2 +- src/ui/neweventtoolbutton.cpp | 17 ++++++------- src/ui/regionmapeditor.cpp | 8 +++--- src/ui/tileseteditor.cpp | 48 +++++++++++++++++++---------------- 4 files changed, 39 insertions(+), 36 deletions(-) diff --git a/src/config.cpp b/src/config.cpp index daf53067..0ea49b6c 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -575,7 +575,7 @@ void ProjectConfig::onNewConfigFileCreated() { form.addRow(new QLabel("Game Version"), baseGameVersionComboBox); QDialogButtonBox buttonBox(QDialogButtonBox::Ok, Qt::Horizontal, &dialog); - connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept())); + connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); form.addRow(&buttonBox); if (dialog.exec() == QDialog::Accepted) { diff --git a/src/ui/neweventtoolbutton.cpp b/src/ui/neweventtoolbutton.cpp index 6c3a59a0..58510a2d 100644 --- a/src/ui/neweventtoolbutton.cpp +++ b/src/ui/neweventtoolbutton.cpp @@ -7,8 +7,7 @@ NewEventToolButton::NewEventToolButton(QWidget *parent) : QToolButton(parent) { setPopupMode(QToolButton::MenuButtonPopup); - QObject::connect(this, SIGNAL(triggered(QAction*)), - this, SLOT(setDefaultAction(QAction*))); + QObject::connect(this, &NewEventToolButton::triggered, this, &NewEventToolButton::setDefaultAction); this->init(); } @@ -17,11 +16,11 @@ void NewEventToolButton::init() // Add a context menu to select different types of map events. this->newObjectAction = new QAction("New Object", this); this->newObjectAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newObjectAction, SIGNAL(triggered(bool)), this, SLOT(newObject())); + connect(this->newObjectAction, &QAction::triggered, this, &NewEventToolButton::newObject); this->newWarpAction = new QAction("New Warp", this); this->newWarpAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newWarpAction, SIGNAL(triggered(bool)), this, SLOT(newWarp())); + connect(this->newWarpAction, &QAction::triggered, this, &NewEventToolButton::newWarp); /* // disable this functionality for now this->newHealLocationAction = new QAction("New Heal Location", this); @@ -31,23 +30,23 @@ void NewEventToolButton::init() this->newTriggerAction = new QAction("New Trigger", this); this->newTriggerAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newTriggerAction, SIGNAL(triggered(bool)), this, SLOT(newTrigger())); + connect(this->newTriggerAction, &QAction::triggered, this, &NewEventToolButton::newTrigger); this->newWeatherTriggerAction = new QAction("New Weather Trigger", this); this->newWeatherTriggerAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newWeatherTriggerAction, SIGNAL(triggered(bool)), this, SLOT(newWeatherTrigger())); + connect(this->newWeatherTriggerAction, &QAction::triggered, this, &NewEventToolButton::newWeatherTrigger); this->newSignAction = new QAction("New Sign", this); this->newSignAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newSignAction, SIGNAL(triggered(bool)), this, SLOT(newSign())); + connect(this->newSignAction, &QAction::triggered, this, &NewEventToolButton::newSign); this->newHiddenItemAction = new QAction("New Hidden Item", this); this->newHiddenItemAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newHiddenItemAction, SIGNAL(triggered(bool)), this, SLOT(newHiddenItem())); + connect(this->newHiddenItemAction, &QAction::triggered, this, &NewEventToolButton::newHiddenItem); this->newSecretBaseAction = new QAction("New Secret Base", this); this->newSecretBaseAction->setIcon(QIcon(":/icons/add.ico")); - connect(this->newSecretBaseAction, SIGNAL(triggered(bool)), this, SLOT(newSecretBase())); + connect(this->newSecretBaseAction, &QAction::triggered, this, &NewEventToolButton::newSecretBase); QMenu *alignMenu = new QMenu(); alignMenu->addAction(this->newObjectAction); diff --git a/src/ui/regionmapeditor.cpp b/src/ui/regionmapeditor.cpp index a116aa5a..eab70589 100644 --- a/src/ui/regionmapeditor.cpp +++ b/src/ui/regionmapeditor.cpp @@ -631,7 +631,7 @@ void RegionMapEditor::on_pushButton_CityMap_add_clicked() { QString name; form.addRow(&buttonBox); - connect(&buttonBox, SIGNAL(rejected()), &popup, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::rejected, &popup, &QDialog::reject); connect(&buttonBox, &QDialogButtonBox::accepted, [&popup, &input, &name](){ name = input->text().remove(QRegularExpression("[^a-zA-Z0-9_]+")); if (!name.isEmpty()) @@ -666,8 +666,8 @@ void RegionMapEditor::on_action_RegionMap_Resize_triggered() { QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &popup); form.addRow(&buttonBox); - connect(&buttonBox, SIGNAL(rejected()), &popup, SLOT(reject())); - connect(&buttonBox, SIGNAL(accepted()), &popup, SLOT(accept())); + connect(&buttonBox, &QDialogButtonBox::rejected, &popup, &QDialog::reject); + connect(&buttonBox, &QDialogButtonBox::accepted, &popup, &QDialog::accept); if (popup.exec() == QDialog::Accepted) { resize(widthSpinBox->value(), heightSpinBox->value()); @@ -760,7 +760,7 @@ void RegionMapEditor::on_action_Swap_triggered() { QString beforeSection, afterSection; uint8_t oldId, newId; - connect(&buttonBox, SIGNAL(rejected()), &popup, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::rejected, &popup, &QDialog::reject); connect(&buttonBox, &QDialogButtonBox::accepted, [this, &popup, &oldSecBox, &newSecBox, &beforeSection, &afterSection, &oldId, &newId](){ beforeSection = oldSecBox->currentText(); diff --git a/src/ui/tileseteditor.cpp b/src/ui/tileseteditor.cpp index 755e941d..2729fd37 100644 --- a/src/ui/tileseteditor.cpp +++ b/src/ui/tileseteditor.cpp @@ -157,12 +157,12 @@ void TilesetEditor::setMetatileLabelValidator() { void TilesetEditor::initMetatileSelector() { this->metatileSelector = new TilesetEditorMetatileSelector(this->primaryTileset, this->secondaryTileset, this->map); - connect(this->metatileSelector, SIGNAL(hoveredMetatileChanged(uint16_t)), - this, SLOT(onHoveredMetatileChanged(uint16_t))); - connect(this->metatileSelector, SIGNAL(hoveredMetatileCleared()), - this, SLOT(onHoveredMetatileCleared())); - connect(this->metatileSelector, SIGNAL(selectedMetatileChanged(uint16_t)), - this, SLOT(onSelectedMetatileChanged(uint16_t))); + connect(this->metatileSelector, &TilesetEditorMetatileSelector::hoveredMetatileChanged, + this, &TilesetEditor::onHoveredMetatileChanged); + connect(this->metatileSelector, &TilesetEditorMetatileSelector::hoveredMetatileCleared, + this, &TilesetEditor::onHoveredMetatileCleared); + connect(this->metatileSelector, &TilesetEditorMetatileSelector::selectedMetatileChanged, + this, &TilesetEditor::onSelectedMetatileChanged); this->metatilesScene = new QGraphicsScene; this->metatilesScene->addItem(this->metatileSelector); @@ -175,10 +175,10 @@ void TilesetEditor::initMetatileSelector() void TilesetEditor::initMetatileLayersItem() { Metatile *metatile = Tileset::getMetatile(this->metatileSelector->getSelectedMetatile(), this->primaryTileset, this->secondaryTileset); this->metatileLayersItem = new MetatileLayersItem(metatile, this->primaryTileset, this->secondaryTileset); - connect(this->metatileLayersItem, SIGNAL(tileChanged(int, int)), - this, SLOT(onMetatileLayerTileChanged(int, int))); - connect(this->metatileLayersItem, SIGNAL(selectedTilesChanged(QPoint, int, int)), - this, SLOT(onMetatileLayerSelectionChanged(QPoint, int, int))); + connect(this->metatileLayersItem, &MetatileLayersItem::tileChanged, + this, &TilesetEditor::onMetatileLayerTileChanged); + connect(this->metatileLayersItem, &MetatileLayersItem::selectedTilesChanged, + this, &TilesetEditor::onMetatileLayerSelectionChanged); this->metatileLayersScene = new QGraphicsScene; this->metatileLayersScene->addItem(this->metatileLayersItem); @@ -187,13 +187,14 @@ void TilesetEditor::initMetatileLayersItem() { void TilesetEditor::initTileSelector() { - this->tileSelector = new TilesetEditorTileSelector(this->primaryTileset, this->secondaryTileset, projectConfig.getTripleLayerMetatilesEnabled()); - connect(this->tileSelector, SIGNAL(hoveredTileChanged(uint16_t)), - this, SLOT(onHoveredTileChanged(uint16_t))); - connect(this->tileSelector, SIGNAL(hoveredTileCleared()), - this, SLOT(onHoveredTileCleared())); - connect(this->tileSelector, SIGNAL(selectedTilesChanged()), - this, SLOT(onSelectedTilesChanged())); + this->tileSelector = new TilesetEditorTileSelector(this->primaryTileset, this->secondaryTileset, + projectConfig.getTripleLayerMetatilesEnabled()); + connect(this->tileSelector, &TilesetEditorTileSelector::hoveredTileChanged, + this, &TilesetEditor::onHoveredTileChanged); + connect(this->tileSelector, &TilesetEditorTileSelector::hoveredTileCleared, + this, &TilesetEditor::onHoveredTileCleared); + connect(this->tileSelector, &TilesetEditorTileSelector::selectedTilesChanged, + this, &TilesetEditor::onSelectedTilesChanged); this->tilesScene = new QGraphicsScene; this->tilesScene->addItem(this->tileSelector); @@ -715,8 +716,8 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() form.addRow(new QLabel("Secondary Tileset"), secondarySpinBox); QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog); - connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept())); - connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); + connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept); + connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject); form.addRow(&buttonBox); if (dialog.exec() == QDialog::Accepted) { @@ -773,9 +774,12 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() void TilesetEditor::on_actionChange_Palettes_triggered() { if (!this->paletteEditor) { - this->paletteEditor = new PaletteEditor(this->project, this->primaryTileset, this->secondaryTileset, this->paletteId, this); - connect(this->paletteEditor, SIGNAL(changedPaletteColor()), this, SLOT(onPaletteEditorChangedPaletteColor())); - connect(this->paletteEditor, SIGNAL(changedPalette(int)), this, SLOT(onPaletteEditorChangedPalette(int))); + this->paletteEditor = new PaletteEditor(this->project, this->primaryTileset, + this->secondaryTileset, this->paletteId, this); + connect(this->paletteEditor, &PaletteEditor::changedPaletteColor, + this, &TilesetEditor::onPaletteEditorChangedPaletteColor); + connect(this->paletteEditor, &PaletteEditor::changedPalette, + this, &TilesetEditor::onPaletteEditorChangedPalette); } if (!this->paletteEditor->isVisible()) { From c103142c65d090ad4ad6deb1cd2513d2b6318ae7 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 12:37:51 -0500 Subject: [PATCH 11/46] Silence deprecated-copy warning --- include/core/block.h | 3 ++- src/core/block.cpp | 39 ++++++++++++++++++++++----------------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/include/core/block.h b/include/core/block.h index 6a787265..0f30c4da 100644 --- a/include/core/block.h +++ b/include/core/block.h @@ -10,7 +10,8 @@ public: Block(); Block(uint16_t); Block(uint16_t tile, uint16_t collision, uint16_t elevation); - Block(const Block&); + Block(const Block &); + Block &operator=(const Block &); bool operator ==(Block); bool operator !=(Block); uint16_t tile:10; diff --git a/src/core/block.cpp b/src/core/block.cpp index 2a6b057d..1479ed10 100644 --- a/src/core/block.cpp +++ b/src/core/block.cpp @@ -1,25 +1,30 @@ #include "block.h" -Block::Block() : tile(0), collision(0), elevation(0) { -} +Block::Block() : tile(0), collision(0), elevation(0) { } -Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) { - this->tile = tile; - this->collision = collision; - this->elevation = elevation; -} +Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) : + tile(tile), + collision(collision), + elevation(elevation) +{ } -Block::Block(uint16_t word) -{ - tile = word & 0x3ff; - collision = (word >> 10) & 0x3; - elevation = (word >> 12) & 0xf; -} +Block::Block(uint16_t word) : + tile(word & 0x3ff), + collision((word >> 10) & 0x3), + elevation((word >> 12) & 0xf) +{ } -Block::Block(const Block &block) { - tile = block.tile; - collision = block.collision; - elevation = block.elevation; +Block::Block(const Block &other) : + tile(other.tile), + collision(other.collision), + elevation(other.elevation) +{ } + +Block &Block::operator=(const Block &other) { + tile = other.tile; + collision = other.collision; + elevation = other.elevation; + return *this; } uint16_t Block::rawValue() { From fe5d4982f705489dbb837f96393ca4f63d7937d7 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 02:45:38 -0500 Subject: [PATCH 12/46] Use QPointer when we need to set a nullptr on destruction --- include/mainwindow.h | 14 +++++++------- src/mainwindow.cpp | 9 +-------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/include/mainwindow.h b/include/mainwindow.h index bf3a4d40..4d333e5c 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -238,14 +238,14 @@ private slots: private: Ui::MainWindow *ui; - QLabel *label_MapRulerStatus; - TilesetEditor *tilesetEditor = nullptr; - RegionMapEditor *regionMapEditor = nullptr; - ShortcutsEditor *shortcutsEditor = nullptr; - MapImageExporter *mapImageExporter = nullptr; + QLabel *label_MapRulerStatus = nullptr; + QPointer tilesetEditor = nullptr; + QPointer regionMapEditor = nullptr; + QPointer shortcutsEditor = nullptr; + QPointer mapImageExporter = nullptr; + QPointer newmapprompt = nullptr; + QPointer preferenceEditor = nullptr; FilterChildrenProxyModel *mapListProxyModel; - NewMapPopup *newmapprompt = nullptr; - PreferenceEditor *preferenceEditor = nullptr; QStandardItemModel *mapListModel; QList *mapGroupItemsList; QMap mapListIndexes; diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 14ccf8d6..75f4494c 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -40,7 +40,6 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), - label_MapRulerStatus(nullptr), selectedObject(nullptr), selectedWarp(nullptr), selectedTrigger(nullptr), @@ -1158,8 +1157,7 @@ void MainWindow::openNewMapPopupWindow(int type, QVariant data) { break; } connect(this->newmapprompt, &NewMapPopup::applied, this, &MainWindow::onNewMapCreated); - connect(this->newmapprompt, &QObject::destroyed, [=](QObject *) { this->newmapprompt = nullptr; }); - this->newmapprompt->setAttribute(Qt::WA_DeleteOnClose); + this->newmapprompt->setAttribute(Qt::WA_DeleteOnClose); } void MainWindow::on_action_NewMap_triggered() { @@ -1496,7 +1494,6 @@ void MainWindow::initShortcutsEditor() { shortcutsEditor = new ShortcutsEditor(this); connect(shortcutsEditor, &ShortcutsEditor::shortcutsSaved, this, &MainWindow::applyUserShortcuts); - connect(shortcutsEditor, &QObject::destroyed, [=](QObject *) { shortcutsEditor = nullptr; }); connectSubEditorsToShortcutsEditor(); @@ -2462,7 +2459,6 @@ void MainWindow::showExportMapImageWindow(ImageExporterMode mode) { delete this->mapImageExporter; this->mapImageExporter = new MapImageExporter(this, this->editor, mode); - connect(this->mapImageExporter, &QObject::destroyed, [=](QObject *) { this->mapImageExporter = nullptr; }); this->mapImageExporter->setAttribute(Qt::WA_DeleteOnClose); if (!this->mapImageExporter->isVisible()) { @@ -2669,7 +2665,6 @@ void MainWindow::on_actionTileset_Editor_triggered() void MainWindow::initTilesetEditor() { this->tilesetEditor = new TilesetEditor(this->editor->project, this->editor->map, this); connect(this->tilesetEditor, &TilesetEditor::tilesetsSaved, this, &MainWindow::onTilesetsSaved); - connect(this->tilesetEditor, &QObject::destroyed, [=](QObject *) { this->tilesetEditor = nullptr; }); } void MainWindow::on_toolButton_ExpandAll_clicked() @@ -2712,7 +2707,6 @@ void MainWindow::on_actionEdit_Preferences_triggered() { editor, &Editor::maskNonVisibleConnectionTiles); connect(preferenceEditor, &PreferenceEditor::preferencesSaved, this, &MainWindow::togglePreferenceSpecificUi); - connect(preferenceEditor, &QObject::destroyed, [=](QObject *) { preferenceEditor = nullptr; }); } if (!preferenceEditor->isVisible()) { @@ -2827,7 +2821,6 @@ bool MainWindow::initRegionMapEditor() { return false; } - connect(this->regionMapEditor, &QObject::destroyed, [=](QObject *) { this->regionMapEditor = nullptr; }); return true; } From 40a7e23b340e3ffff2dc246c5ade281c347a12be Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 09:22:26 -0500 Subject: [PATCH 13/46] Remove undefined functions in Editor --- include/editor.h | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/include/editor.h b/include/editor.h index e03b3a9e..2b70a6f6 100644 --- a/include/editor.h +++ b/include/editor.h @@ -60,7 +60,6 @@ public: void displayCurrentMetatilesSelection(); void redrawCurrentMetatilesSelection(); void displayMovementPermissionSelector(); - void displayElevationMetatiles(); void displayMapEvents(); void displayMapConnections(); void displayMapBorder(); @@ -75,7 +74,6 @@ public: void setEditingObjects(); void setEditingConnections(); void setMapEditingButtonsEnabled(bool enabled); - void clearWildMonTabWidgets(); void setCurrentConnectionDirection(QString curDirection); void updateCurrentConnectionDirection(QString curDirection); void setConnectionsVisibility(bool visible); @@ -99,7 +97,6 @@ public: void selectMapEvent(DraggablePixmapItem *object); void selectMapEvent(DraggablePixmapItem *object, bool toggle); DraggablePixmapItem *addNewEvent(QString event_type); - Event* createNewEvent(QString event_type); void deleteEvent(Event *); void updateSelectedEvents(); void duplicateSelectedEvents(); @@ -143,8 +140,6 @@ public: qreal collisionOpacity = 0.5; void objectsView_onMousePress(QMouseEvent *event); - void objectsView_onMouseMove(QMouseEvent *event); - void objectsView_onMouseRelease(QMouseEvent *event); int getBorderDrawDistance(int dimension); @@ -178,14 +173,6 @@ private: void updateMirroredConnectionMap(MapConnection*, QString); void updateMirroredConnection(MapConnection*, QString, QString, bool isDelete = false); void updateEncounterFields(EncounterFields newFields); - Event* createNewObjectEvent(); - Event* createNewWarpEvent(); - Event* createNewHealLocationEvent(); - Event* createNewTriggerEvent(); - Event* createNewWeatherTriggerEvent(); - Event* createNewSignEvent(); - Event* createNewHiddenItemEvent(); - Event* createNewSecretBaseEvent(); QString getMovementPermissionText(uint16_t collision, uint16_t elevation); QString getMetatileDisplayMessage(uint16_t metatileId); bool eventLimitReached(Map *, QString); From 8e2388cf62063016215e72b6e7d5ebcca834677f Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 10:49:14 -0500 Subject: [PATCH 14/46] Correct UB in Event constructors; use member initializer lists --- src/core/event.cpp | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/src/core/event.cpp b/src/core/event.cpp index 754a3ab9..5b10d20f 100644 --- a/src/core/event.cpp +++ b/src/core/event.cpp @@ -12,29 +12,25 @@ QString EventType::HiddenItem = "event_hidden_item"; QString EventType::SecretBase = "event_secret_base"; QString EventType::HealLocation = "event_heal_location"; -Event::Event() -{ - this->spriteWidth = 16; - this->spriteHeight = 16; - this->usingSprite = false; -} +Event::Event() : + spriteWidth(16), + spriteHeight(16), + usingSprite(false) +{ } -Event::Event(const Event& toCopy) -{ - Event(); - this->values = toCopy.values; - this->customValues = toCopy.customValues; - this->pixmap = toCopy.pixmap; - this->spriteWidth = toCopy.spriteWidth; - this->spriteHeight = toCopy.spriteHeight; - this->frame = toCopy.frame; - this->hFlip = toCopy.hFlip; - this->usingSprite = toCopy.usingSprite; -} +Event::Event(const Event& toCopy) : + values(toCopy.values), + customValues(toCopy.customValues), + pixmap(toCopy.pixmap), + spriteWidth(toCopy.spriteWidth), + spriteHeight(toCopy.spriteHeight), + frame(toCopy.frame), + hFlip(toCopy.hFlip), + usingSprite(toCopy.usingSprite) +{ } -Event::Event(QJsonObject obj, QString type) +Event::Event(QJsonObject obj, QString type) : Event() { - Event(); this->put("event_type", type); this->readCustomValues(obj); } From 8187b2d4bbaace08cb43c4b59351fab9eb6edf0d Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 12:14:27 -0500 Subject: [PATCH 15/46] Plug leaks in Metatile --- include/core/metatile.h | 3 ++- src/core/metatile.cpp | 28 +++++++++++++++++++--------- src/core/metatileparser.cpp | 4 ++-- src/core/tileset.cpp | 3 +-- src/mainwindow.cpp | 16 ++++++++-------- src/project.cpp | 4 ++-- src/ui/imageproviders.cpp | 4 ++-- src/ui/metatilelayersitem.cpp | 2 +- src/ui/tileseteditor.cpp | 18 +++++++++--------- 9 files changed, 46 insertions(+), 36 deletions(-) diff --git a/include/core/metatile.h b/include/core/metatile.h index c016ae7c..561a747e 100644 --- a/include/core/metatile.h +++ b/include/core/metatile.h @@ -11,8 +11,9 @@ class Metatile { public: Metatile(); + Metatile(const Metatile &other); public: - QList *tiles = nullptr; + QList tiles; uint16_t behavior; // 8 bits RSE, 9 bits FRLG uint8_t layerType; uint8_t encounterType; // FRLG only diff --git a/src/core/metatile.cpp b/src/core/metatile.cpp index e870dcad..7301eb12 100644 --- a/src/core/metatile.cpp +++ b/src/core/metatile.cpp @@ -2,10 +2,21 @@ #include "tileset.h" #include "project.h" -Metatile::Metatile() -{ - tiles = new QList; -} +Metatile::Metatile() : + behavior(0), + layerType(0), + encounterType(0), + terrainType(0) +{ } + +Metatile::Metatile(const Metatile &other) : + tiles(other.tiles), + behavior(other.behavior), + layerType(other.layerType), + encounterType(other.encounterType), + terrainType(other.terrainType), + label(other.label) +{ } Metatile* Metatile::copy() { Metatile *copy = new Metatile; @@ -13,10 +24,9 @@ Metatile* Metatile::copy() { copy->layerType = this->layerType; copy->encounterType = this->encounterType; copy->terrainType = this->terrainType; - copy->tiles = new QList; copy->label = this->label; - for (Tile tile : *this->tiles) { - copy->tiles->append(tile); + for (const Tile &tile : this->tiles) { + copy->tiles.append(tile); } return copy; } @@ -27,8 +37,8 @@ void Metatile::copyInPlace(Metatile *other) { this->encounterType = other->encounterType; this->terrainType = other->terrainType; this->label = other->label; - for (int i = 0; i < this->tiles->length(); i++) { - (*this->tiles)[i] = other->tiles->at(i); + for (int i = 0; i < this->tiles.length(); i++) { + this->tiles[i] = other->tiles.at(i); } } diff --git a/src/core/metatileparser.cpp b/src/core/metatileparser.cpp index 7c52c187..2fef6dc0 100644 --- a/src/core/metatileparser.cpp +++ b/src/core/metatileparser.cpp @@ -75,14 +75,14 @@ QList *MetatileParser::parse(QString filepath, bool *error, bool prim QList *metatiles = new QList(); for (int i = 0; i < numMetatiles; i++) { Metatile *metatile = new Metatile(); - QList *tiles = new QList(); + QList tiles; for (int j = 0; j < 8; j++) { int metatileOffset = 4 + i * metatileSize + j * 2; uint16_t word = static_cast( static_cast(in.at(metatileOffset)) | (static_cast(in.at(metatileOffset + 1)) << 8)); Tile tile(word & 0x3ff, (word >> 10) & 1, (word >> 11) & 1, (word >> 12) & 0xf); - tiles->append(tile); + tiles.append(tile); } int attrOffset = 4 + (numMetatiles * metatileSize) + (i * attrSize); diff --git a/src/core/tileset.cpp b/src/core/tileset.cpp index b3c81bc5..0ec18e0b 100644 --- a/src/core/tileset.cpp +++ b/src/core/tileset.cpp @@ -71,8 +71,7 @@ Metatile* Tileset::getMetatile(int index, Tileset *primaryTileset, Tileset *seco if (!tileset || !tileset->metatiles) { return nullptr; } - Metatile *metatile = tileset->metatiles->value(local_index, nullptr); - return metatile; + return tileset->metatiles->value(local_index, nullptr); } bool Tileset::metatileIsValid(uint16_t metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 75f4494c..5d1740fc 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1219,16 +1219,16 @@ void MainWindow::on_actionNew_Tileset_triggered() { int tilesPerMetatile = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8; Metatile *mt = new Metatile(); for(int j = 0; j < tilesPerMetatile; ++j){ - Tile *tile = new Tile(); + Tile tile; //Create a checkerboard-style dummy tileset if(((i / 8) % 2) == 0) - tile->tile = ((i % 2) == 0) ? 1 : 2; + tile.tile = ((i % 2) == 0) ? 1 : 2; else - tile->tile = ((i % 2) == 1) ? 1 : 2; - tile->xflip = false; - tile->yflip = false; - tile->palette = 0; - mt->tiles->append(*tile); + tile.tile = ((i % 2) == 1) ? 1 : 2; + tile.xflip = false; + tile.yflip = false; + tile.palette = 0; + mt->tiles.append(tile); } mt->behavior = 0; mt->layerType = 0; @@ -1239,7 +1239,7 @@ void MainWindow::on_actionNew_Tileset_triggered() { } newSet->palettes = new QList>(); newSet->palettePreviews = new QList>(); - newSet->palettePaths = *new QList(); + newSet->palettePaths.clear(); for(int i = 0; i < 16; ++i) { QList *currentPal = new QList(); for(int i = 0; i < 16;++i) { diff --git a/src/project.cpp b/src/project.cpp index 19df02a9..710e4edc 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1088,7 +1088,7 @@ void Project::saveTilesetMetatiles(Tileset *tileset) { for (Metatile *metatile : *tileset->metatiles) { int numTiles = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8; for (int i = 0; i < numTiles; i++) { - Tile tile = metatile->tiles->at(i); + Tile tile = metatile->tiles.at(i); uint16_t value = static_cast((tile.tile & 0x3ff) | ((tile.xflip & 1) << 10) | ((tile.yflip & 1) << 11) @@ -1626,7 +1626,7 @@ void Project::loadTilesetMetatiles(Tileset* tileset) { tile.xflip = (word >> 10) & 1; tile.yflip = (word >> 11) & 1; tile.palette = (word >> 12) & 0xf; - metatile->tiles->append(tile); + metatile->tiles.append(tile); } metatiles->append(metatile); } diff --git a/src/ui/imageproviders.cpp b/src/ui/imageproviders.cpp index a9d7cf29..4c37206e 100644 --- a/src/ui/imageproviders.cpp +++ b/src/ui/imageproviders.cpp @@ -26,7 +26,7 @@ QImage getMetatileImage( metatile_image.fill(Qt::black); Metatile* metatile = Tileset::getMetatile(tile, primaryTileset, secondaryTileset); - if (!metatile || !metatile->tiles) { + if (!metatile) { metatile_image.fill(Qt::magenta); return metatile_image; } @@ -46,7 +46,7 @@ QImage getMetatileImage( for (int x = 0; x < 2; x++) { int l = layerOrder.size() >= numLayers ? layerOrder[layer] : layer; int bottomLayer = layerOrder.size() >= numLayers ? layerOrder[0] : 0; - Tile tile_ = metatile->tiles->value((y * 2) + x + (l * 4)); + Tile tile_ = metatile->tiles.value((y * 2) + x + (l * 4)); QImage tile_image = getTileImage(tile_.tile, primaryTileset, secondaryTileset); if (tile_image.isNull()) { // Some metatiles specify tiles that are outside the valid range. diff --git a/src/ui/metatilelayersitem.cpp b/src/ui/metatilelayersitem.cpp index 9883c4d5..2f5f8b80 100644 --- a/src/ui/metatilelayersitem.cpp +++ b/src/ui/metatilelayersitem.cpp @@ -25,7 +25,7 @@ void MetatileLayersItem::draw() { QPainter painter(&pixmap); int numTiles = isTripleLayerMetatile ? 12 : 8; for (int i = 0; i < numTiles; i++) { - Tile tile = this->metatile->tiles->at(i); + Tile tile = this->metatile->tiles.at(i); QImage tileImage = getPalettedTileImage(tile.tile, this->primaryTileset, this->secondaryTileset, tile.palette, true) .mirrored(tile.xflip, tile.yflip) .scaled(16, 16); diff --git a/src/ui/tileseteditor.cpp b/src/ui/tileseteditor.cpp index 2729fd37..9048f5a8 100644 --- a/src/ui/tileseteditor.cpp +++ b/src/ui/tileseteditor.cpp @@ -361,7 +361,7 @@ void TilesetEditor::onSelectedTilesChanged() { } void TilesetEditor::onMetatileLayerTileChanged(int x, int y) { - const QList tileCoords = QList{ + static const QList tileCoords = QList{ QPoint(0, 0), QPoint(1, 0), QPoint(0, 1), @@ -387,11 +387,11 @@ void TilesetEditor::onMetatileLayerTileChanged(int x, int y) { if (tileIndex < maxTileIndex && tileCoords.at(tileIndex).x() >= x && tileCoords.at(tileIndex).y() >= y){ - Tile *tile = &(*this->metatile->tiles)[tileIndex]; - tile->tile = tiles.at(selectedTileIndex).tile; - tile->xflip = tiles.at(selectedTileIndex).xflip; - tile->yflip = tiles.at(selectedTileIndex).yflip; - tile->palette = tiles.at(selectedTileIndex).palette; + Tile &tile = this->metatile->tiles[tileIndex]; + tile.tile = tiles.at(selectedTileIndex).tile; + tile.xflip = tiles.at(selectedTileIndex).xflip; + tile.yflip = tiles.at(selectedTileIndex).yflip; + tile.palette = tiles.at(selectedTileIndex).palette; } selectedTileIndex++; } @@ -416,7 +416,7 @@ void TilesetEditor::onMetatileLayerSelectionChanged(QPoint selectionOrigin, int for (int i = 0; i < width; i++) { int tileIndex = ((x + i) / 2 * 4) + ((y + j) * 2) + ((x + i) % 2); if (tileIndex < maxTileIndex) { - tiles.append(this->metatile->tiles->at(tileIndex)); + tiles.append(this->metatile->tiles.at(tileIndex)); tileIdxs.append(tileIndex); } } @@ -740,7 +740,7 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() metatile->encounterType = 0; metatile->terrainType = 0; for (int i = 0; i < numTiles; i++) { - metatile->tiles->append(tile); + metatile->tiles.append(tile); } this->primaryTileset->metatiles->append(metatile); } @@ -760,7 +760,7 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() metatile->encounterType = 0; metatile->terrainType = 0; for (int i = 0; i < numTiles; i++) { - metatile->tiles->append(tile); + metatile->tiles.append(tile); } this->secondaryTileset->metatiles->append(metatile); } From 6a825d0b394dfcce35d298c597ca81983b194de1 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 13:22:41 -0500 Subject: [PATCH 16/46] Use implicit copy constructor/assignment for Metatile --- include/core/metatile.h | 6 +++--- src/core/metatile.cpp | 33 ------------------------------ src/core/tileset.cpp | 2 +- src/ui/tileseteditor.cpp | 43 +++++++++++++++++++++++----------------- 4 files changed, 29 insertions(+), 55 deletions(-) diff --git a/include/core/metatile.h b/include/core/metatile.h index 561a747e..5b9bb813 100644 --- a/include/core/metatile.h +++ b/include/core/metatile.h @@ -11,7 +11,9 @@ class Metatile { public: Metatile(); - Metatile(const Metatile &other); + Metatile(const Metatile &other) = default; + Metatile &operator=(const Metatile &other) = default; + public: QList tiles; uint16_t behavior; // 8 bits RSE, 9 bits FRLG @@ -20,8 +22,6 @@ public: uint8_t terrainType; // FRLG only QString label; - Metatile *copy(); - void copyInPlace(Metatile*); static int getBlockIndex(int); static QPoint coordFromPixmapCoord(const QPointF &pixelCoord); }; diff --git a/src/core/metatile.cpp b/src/core/metatile.cpp index 7301eb12..4c97418d 100644 --- a/src/core/metatile.cpp +++ b/src/core/metatile.cpp @@ -9,39 +9,6 @@ Metatile::Metatile() : terrainType(0) { } -Metatile::Metatile(const Metatile &other) : - tiles(other.tiles), - behavior(other.behavior), - layerType(other.layerType), - encounterType(other.encounterType), - terrainType(other.terrainType), - label(other.label) -{ } - -Metatile* Metatile::copy() { - Metatile *copy = new Metatile; - copy->behavior = this->behavior; - copy->layerType = this->layerType; - copy->encounterType = this->encounterType; - copy->terrainType = this->terrainType; - copy->label = this->label; - for (const Tile &tile : this->tiles) { - copy->tiles.append(tile); - } - return copy; -} - -void Metatile::copyInPlace(Metatile *other) { - this->behavior = other->behavior; - this->layerType = other->layerType; - this->encounterType = other->encounterType; - this->terrainType = other->terrainType; - this->label = other->label; - for (int i = 0; i < this->tiles.length(); i++) { - this->tiles[i] = other->tiles.at(i); - } -} - int Metatile::getBlockIndex(int index) { if (index < Project::getNumMetatilesPrimary()) { return index; diff --git a/src/core/tileset.cpp b/src/core/tileset.cpp index 0ec18e0b..03b0fb7c 100644 --- a/src/core/tileset.cpp +++ b/src/core/tileset.cpp @@ -36,7 +36,7 @@ Tileset* Tileset::copy() { } copy->metatiles = new QList; for (Metatile *metatile : *this->metatiles) { - copy->metatiles->append(metatile->copy()); + copy->metatiles->append(new Metatile(*metatile)); } copy->palettes = new QList>; for (QList palette : *this->palettes) { diff --git a/src/ui/tileseteditor.cpp b/src/ui/tileseteditor.cpp index 9048f5a8..928087b5 100644 --- a/src/ui/tileseteditor.cpp +++ b/src/ui/tileseteditor.cpp @@ -262,7 +262,7 @@ void TilesetEditor::restoreWindowState() { } void TilesetEditor::initMetatileHistory() { - MetatileHistoryItem *commit = new MetatileHistoryItem(0, nullptr, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(0, nullptr, new Metatile(*metatile)); metatileHistory.push(commit); } @@ -375,7 +375,7 @@ void TilesetEditor::onMetatileLayerTileChanged(int x, int y) { QPoint(4, 1), QPoint(5, 1), }; - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); QPoint dimensions = this->tileSelector->getSelectionDimensions(); QList tiles = this->tileSelector->getSelectedTiles(); int selectedTileIndex = 0; @@ -401,7 +401,8 @@ void TilesetEditor::onMetatileLayerTileChanged(int x, int y) { this->metatileLayersItem->draw(); this->hasUnsavedChanges = true; - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); } @@ -465,9 +466,10 @@ void TilesetEditor::on_checkBox_yFlip_stateChanged(int checked) void TilesetEditor::on_comboBox_metatileBehaviors_activated(const QString &metatileBehavior) { if (this->metatile) { - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); this->metatile->behavior = static_cast(project->metatileBehaviorMap[metatileBehavior]); - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); this->hasUnsavedChanges = true; } @@ -482,9 +484,10 @@ void TilesetEditor::saveMetatileLabel() { // Only commit if the field has changed. if (this->metatile && this->metatile->label != this->ui->lineEdit_metatileLabel->text()) { - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); this->metatile->label = this->ui->lineEdit_metatileLabel->text(); - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); this->hasUnsavedChanges = true; } @@ -493,9 +496,10 @@ void TilesetEditor::saveMetatileLabel() void TilesetEditor::on_comboBox_layerType_activated(int layerType) { if (this->metatile) { - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); this->metatile->layerType = static_cast(layerType); - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); this->hasUnsavedChanges = true; } @@ -504,9 +508,10 @@ void TilesetEditor::on_comboBox_layerType_activated(int layerType) void TilesetEditor::on_comboBox_encounterType_activated(int encounterType) { if (this->metatile) { - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); this->metatile->encounterType = static_cast(encounterType); - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); this->hasUnsavedChanges = true; } @@ -515,9 +520,10 @@ void TilesetEditor::on_comboBox_encounterType_activated(int encounterType) void TilesetEditor::on_comboBox_terrainType_activated(int terrainType) { if (this->metatile) { - Metatile *prevMetatile = this->metatile->copy(); + Metatile *prevMetatile = new Metatile(*this->metatile); this->metatile->terrainType = static_cast(terrainType); - MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), prevMetatile, this->metatile->copy()); + MetatileHistoryItem *commit = new MetatileHistoryItem(metatileSelector->getSelectedMetatile(), + prevMetatile, new Metatile(*this->metatile)); metatileHistory.push(commit); this->hasUnsavedChanges = true; } @@ -811,7 +817,7 @@ void TilesetEditor::on_actionUndo_triggered() Metatile *temp = Tileset::getMetatile(commit->metatileId, this->primaryTileset, this->secondaryTileset); if (temp) { this->metatile = temp; - this->metatile->copyInPlace(prev); + *this->metatile = *prev; this->metatileSelector->select(commit->metatileId); this->metatileSelector->draw(); this->metatileLayersItem->draw(); @@ -828,8 +834,8 @@ void TilesetEditor::on_actionRedo_triggered() Metatile *temp = Tileset::getMetatile(commit->metatileId, this->primaryTileset, this->secondaryTileset); if (temp) { - this->metatile = Tileset::getMetatile(commit->metatileId, this->primaryTileset, this->secondaryTileset); - this->metatile->copyInPlace(next); + this->metatile = temp; + *this->metatile = *next; this->metatileSelector->select(commit->metatileId); this->metatileSelector->draw(); this->metatileLayersItem->draw(); @@ -905,8 +911,9 @@ void TilesetEditor::importTilesetMetatiles(Tileset *tileset, bool primary) break; } - Metatile *prevMetatile = tileset->metatiles->at(i)->copy(); - MetatileHistoryItem *commit = new MetatileHistoryItem(static_cast(metatileIdBase + i), prevMetatile, metatiles->at(i)->copy()); + Metatile *prevMetatile = new Metatile(*tileset->metatiles->at(i)); + MetatileHistoryItem *commit = new MetatileHistoryItem(static_cast(metatileIdBase + i), + prevMetatile, new Metatile(*metatiles->at(i))); metatileHistory.push(commit); } From 42b56edc9d394c8b86c739d8362e0dde2a68d2bf Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 15:10:03 -0500 Subject: [PATCH 17/46] Begin refactoring Blockdata to simply inherit QVector --- include/core/block.h | 6 +- include/core/blockdata.h | 20 +----- include/core/editcommands.h | 58 ++++++++--------- src/core/block.cpp | 6 +- src/core/blockdata.cpp | 45 +------------ src/core/editcommands.cpp | 94 +++++++++------------------- src/core/map.cpp | 84 +++++++++++-------------- src/editor.cpp | 6 +- src/mainwindow.cpp | 8 +-- src/mainwindow_scriptapi.cpp | 2 +- src/project.cpp | 40 ++++++------ src/ui/bordermetatilespixmapitem.cpp | 13 ++-- src/ui/collisionpixmapitem.cpp | 24 +++---- src/ui/mappixmapitem.cpp | 56 ++++++++--------- 14 files changed, 174 insertions(+), 288 deletions(-) diff --git a/include/core/block.h b/include/core/block.h index 0f30c4da..9bb1877f 100644 --- a/include/core/block.h +++ b/include/core/block.h @@ -12,12 +12,12 @@ public: Block(uint16_t tile, uint16_t collision, uint16_t elevation); Block(const Block &); Block &operator=(const Block &); - bool operator ==(Block); - bool operator !=(Block); + bool operator ==(Block) const; + bool operator !=(Block) const; uint16_t tile:10; uint16_t collision:2; uint16_t elevation:4; - uint16_t rawValue(); + uint16_t rawValue() const; }; #endif // BLOCK_H diff --git a/include/core/blockdata.h b/include/core/blockdata.h index a8e29d36..5d434f21 100644 --- a/include/core/blockdata.h +++ b/include/core/blockdata.h @@ -4,31 +4,13 @@ #include "block.h" -#include #include #include -class Blockdata : public QObject +class Blockdata : public QVector { - Q_OBJECT public: - explicit Blockdata(QObject *parent = nullptr); - ~Blockdata() { - if (blocks) delete blocks; - } - -public: - QVector *blocks = nullptr; - void addBlock(uint16_t); - void addBlock(Block); QByteArray serialize(); - void copyFrom(Blockdata*); - Blockdata* copy(); - bool equals(Blockdata *); - -signals: - -public slots: }; #endif // BLOCKDATA_H diff --git a/include/core/editcommands.h b/include/core/editcommands.h index 8ff606f0..9b96ea3c 100644 --- a/include/core/editcommands.h +++ b/include/core/editcommands.h @@ -2,6 +2,8 @@ #ifndef EDITCOMMANDS_H #define EDITCOMMANDS_H +#include "blockdata.h" + #include #include @@ -41,9 +43,8 @@ enum CommandId { class PaintMetatile : public QUndoCommand { public: PaintMetatile(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent = nullptr); - virtual ~PaintMetatile(); void undo() override; void redo() override; @@ -54,8 +55,8 @@ public: private: Map *map; - Blockdata *newMetatiles; - Blockdata *oldMetatiles; + Blockdata newMetatiles; + Blockdata oldMetatiles; unsigned actionId; }; @@ -67,7 +68,7 @@ private: class PaintCollision : public PaintMetatile { public: PaintCollision(Map *map, - Blockdata *oldCollision, Blockdata *newCollision, + const Blockdata &oldCollision, const Blockdata &newCollision, unsigned actionId, QUndoCommand *parent = nullptr) : PaintMetatile(map, oldCollision, newCollision, actionId, parent) { setText("Paint Collision"); @@ -82,9 +83,8 @@ public: class PaintBorder : public QUndoCommand { public: PaintBorder(Map *map, - Blockdata *oldBorder, Blockdata *newBorder, + const Blockdata &oldBorder, const Blockdata &newBorder, unsigned actionId, QUndoCommand *parent = nullptr); - ~PaintBorder(); void undo() override; void redo() override; @@ -95,8 +95,8 @@ public: private: Map *map; - Blockdata *newBorder; - Blockdata *oldBorder; + Blockdata newBorder; + Blockdata oldBorder; unsigned actionId; }; @@ -108,7 +108,7 @@ private: class BucketFillMetatile : public PaintMetatile { public: BucketFillMetatile(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent = nullptr) : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { setText("Bucket Fill Metatiles"); @@ -124,7 +124,7 @@ public: class BucketFillCollision : public PaintCollision { public: BucketFillCollision(Map *map, - Blockdata *oldCollision, Blockdata *newCollision, + const Blockdata &oldCollision, const Blockdata &newCollision, QUndoCommand *parent = nullptr) : PaintCollision(map, oldCollision, newCollision, -1, parent) { setText("Flood Fill Collision"); @@ -141,7 +141,7 @@ public: class MagicFillMetatile : public PaintMetatile { public: MagicFillMetatile(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent = nullptr) : PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) { setText("Magic Fill Metatiles"); @@ -156,7 +156,7 @@ public: class MagicFillCollision : public PaintCollision { public: MagicFillCollision(Map *map, - Blockdata *oldCollision, Blockdata *newCollision, + const Blockdata &oldCollision, const Blockdata &newCollision, QUndoCommand *parent = nullptr) : PaintCollision(map, oldCollision, newCollision, -1, parent) { setText("Magic Fill Collision"); @@ -172,9 +172,8 @@ public: class ShiftMetatiles : public QUndoCommand { public: ShiftMetatiles(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent = nullptr); - ~ShiftMetatiles(); void undo() override; void redo() override; @@ -185,8 +184,8 @@ public: private: Map *map; - Blockdata *newMetatiles; - Blockdata *oldMetatiles; + Blockdata newMetatiles; + Blockdata oldMetatiles; unsigned actionId; }; @@ -197,11 +196,10 @@ private: class ResizeMap : public QUndoCommand { public: ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, QSize oldBorderDimensions, QSize newBorderDimensions, - Blockdata *oldBorder, Blockdata *newBorder, + const Blockdata &oldBorder, const Blockdata &newBorder, QUndoCommand *parent = nullptr); - ~ResizeMap(); void undo() override; void redo() override; @@ -222,11 +220,11 @@ private: int newBorderWidth; int newBorderHeight; - Blockdata *newMetatiles; - Blockdata *oldMetatiles; + Blockdata newMetatiles; + Blockdata oldMetatiles; - Blockdata *newBorder; - Blockdata *oldBorder; + Blockdata newBorder; + Blockdata oldBorder; }; @@ -238,7 +236,6 @@ public: EventMove(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand *parent = nullptr); - ~EventMove(); void undo() override; void redo() override; @@ -262,7 +259,6 @@ public: EventShift(QList events, int deltaX, int deltaY, unsigned actionId, QUndoCommand *parent = nullptr); - ~EventShift(); int id() const override; private: QList events; @@ -276,7 +272,6 @@ class EventCreate : public QUndoCommand { public: EventCreate(Editor *editor, Map *map, Event *event, QUndoCommand *parent = nullptr); - ~EventCreate(); void undo() override; void redo() override; @@ -299,7 +294,6 @@ public: EventDelete(Editor *editor, Map *map, QList selectedEvents, Event *nextSelectedEvent, QUndoCommand *parent = nullptr); - ~EventDelete(); void undo() override; void redo() override; @@ -321,7 +315,6 @@ class EventDuplicate : public QUndoCommand { public: EventDuplicate(Editor *editor, Map *map, QList selectedEvents, QUndoCommand *parent = nullptr); - ~EventDuplicate(); void undo() override; void redo() override; @@ -343,9 +336,8 @@ class ScriptEditMap : public QUndoCommand { public: ScriptEditMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, QUndoCommand *parent = nullptr); - ~ScriptEditMap(); void undo() override; void redo() override; @@ -356,8 +348,8 @@ public: private: Map *map; - Blockdata *newMetatiles; - Blockdata *oldMetatiles; + Blockdata newMetatiles; + Blockdata oldMetatiles; int oldMapWidth; int oldMapHeight; diff --git a/src/core/block.cpp b/src/core/block.cpp index 1479ed10..680384fd 100644 --- a/src/core/block.cpp +++ b/src/core/block.cpp @@ -27,17 +27,17 @@ Block &Block::operator=(const Block &other) { return *this; } -uint16_t Block::rawValue() { +uint16_t Block::rawValue() const { return static_cast( (tile & 0x3ff) + ((collision & 0x3) << 10) + ((elevation & 0xf) << 12)); } -bool Block::operator ==(Block other) { +bool Block::operator ==(Block other) const { return (tile == other.tile) && (collision == other.collision) && (elevation == other.elevation); } -bool Block::operator !=(Block other) { +bool Block::operator !=(Block other) const { return !(operator ==(other)); } diff --git a/src/core/blockdata.cpp b/src/core/blockdata.cpp index 77239add..ab42b888 100644 --- a/src/core/blockdata.cpp +++ b/src/core/blockdata.cpp @@ -1,54 +1,11 @@ #include "blockdata.h" -Blockdata::Blockdata(QObject *parent) : QObject(parent) -{ - blocks = new QVector; -} - -void Blockdata::addBlock(uint16_t word) { - Block block(word); - blocks->append(block); -} - -void Blockdata::addBlock(Block block) { - blocks->append(block); -} - QByteArray Blockdata::serialize() { QByteArray data; - for (int i = 0; i < blocks->length(); i++) { - Block block = blocks->value(i); + for (const auto &block : *this) { uint16_t word = block.rawValue(); data.append(static_cast(word & 0xff)); data.append(static_cast((word >> 8) & 0xff)); } return data; } - -void Blockdata::copyFrom(Blockdata* other) { - blocks->clear(); - for (int i = 0; i < other->blocks->length(); i++) { - addBlock(other->blocks->value(i)); - } -} - -Blockdata* Blockdata::copy() { - Blockdata* blockdata = new Blockdata; - blockdata->copyFrom(this); - return blockdata; -} - -bool Blockdata::equals(Blockdata *other) { - if (!other) { - return false; - } - if (blocks->length() != other->blocks->length()) { - return false; - } - for (int i = 0; i < blocks->length(); i++) { - if (blocks->value(i) != other->blocks->value(i)) { - return false; - } - } - return true; -} diff --git a/src/core/editcommands.cpp b/src/core/editcommands.cpp index 05ecc22a..efc30d25 100644 --- a/src/core/editcommands.cpp +++ b/src/core/editcommands.cpp @@ -31,8 +31,9 @@ void renderMapBlocks(Map *map, bool ignoreCache = false) { map->mapItem->draw(ignoreCache); map->collisionItem->draw(ignoreCache); } + PaintMetatile::PaintMetatile(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { setText("Paint Metatiles"); @@ -43,21 +44,16 @@ PaintMetatile::PaintMetatile(Map *map, this->actionId = actionId; } -PaintMetatile::~PaintMetatile() { - if (newMetatiles) delete newMetatiles; - if (oldMetatiles) delete oldMetatiles; -} - void PaintMetatile::redo() { QUndoCommand::redo(); if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(newMetatiles); + *map->layout->blockdata = newMetatiles; } - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; renderMapBlocks(map); } @@ -66,10 +62,10 @@ void PaintMetatile::undo() { if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(oldMetatiles); + *map->layout->blockdata = oldMetatiles; } - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; renderMapBlocks(map); @@ -79,13 +75,13 @@ void PaintMetatile::undo() { bool PaintMetatile::mergeWith(const QUndoCommand *command) { const PaintMetatile *other = static_cast(command); - if (this->map != other->map) + if (map != other->map) return false; if (actionId != other->actionId) return false; - this->newMetatiles->copyFrom(other->newMetatiles); + newMetatiles = other->newMetatiles; return true; } @@ -95,7 +91,7 @@ bool PaintMetatile::mergeWith(const QUndoCommand *command) { ******************************************************************************/ PaintBorder::PaintBorder(Map *map, - Blockdata *oldBorder, Blockdata *newBorder, + const Blockdata &oldBorder, const Blockdata &newBorder, unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { setText("Paint Border"); @@ -106,18 +102,13 @@ PaintBorder::PaintBorder(Map *map, this->actionId = actionId; } -PaintBorder::~PaintBorder() { - if (newBorder) delete newBorder; - if (oldBorder) delete oldBorder; -} - void PaintBorder::redo() { QUndoCommand::redo(); if (!map) return; if (map->layout->border) { - map->layout->border->copyFrom(newBorder); + *map->layout->border = newBorder; } map->borderItem->draw(); @@ -127,7 +118,7 @@ void PaintBorder::undo() { if (!map) return; if (map->layout->border) { - map->layout->border->copyFrom(oldBorder); + *map->layout->border = oldBorder; } map->borderItem->draw(); @@ -140,7 +131,7 @@ void PaintBorder::undo() { ******************************************************************************/ ShiftMetatiles::ShiftMetatiles(Map *map, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) { setText("Shift Metatiles"); @@ -151,21 +142,16 @@ ShiftMetatiles::ShiftMetatiles(Map *map, this->actionId = actionId; } -ShiftMetatiles::~ShiftMetatiles() { - if (newMetatiles) delete newMetatiles; - if (oldMetatiles) delete oldMetatiles; -} - void ShiftMetatiles::redo() { QUndoCommand::redo(); if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(newMetatiles); + *map->layout->blockdata = newMetatiles; } - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; renderMapBlocks(map, true); } @@ -174,10 +160,10 @@ void ShiftMetatiles::undo() { if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(oldMetatiles); + *map->layout->blockdata = oldMetatiles; } - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; renderMapBlocks(map, true); @@ -193,7 +179,7 @@ bool ShiftMetatiles::mergeWith(const QUndoCommand *command) { if (actionId != other->actionId) return false; - this->newMetatiles->copyFrom(other->newMetatiles); + this->newMetatiles = other->newMetatiles; return true; } @@ -203,9 +189,9 @@ bool ShiftMetatiles::mergeWith(const QUndoCommand *command) { ******************************************************************************/ ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, QSize oldBorderDimensions, QSize newBorderDimensions, - Blockdata *oldBorder, Blockdata *newBorder, + const Blockdata &oldBorder, const Blockdata &newBorder, QUndoCommand *parent) : QUndoCommand(parent) { setText("Resize Map"); @@ -230,23 +216,18 @@ ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, this->newBorder = newBorder; } -ResizeMap::~ResizeMap() { - if (newMetatiles) delete newMetatiles; - if (oldMetatiles) delete oldMetatiles; -} - void ResizeMap::redo() { QUndoCommand::redo(); if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(newMetatiles); + *map->layout->blockdata = newMetatiles; map->setDimensions(newMapWidth, newMapHeight, false); } if (map->layout->border) { - map->layout->border->copyFrom(newBorder); + *map->layout->border = newBorder; map->setBorderDimensions(newBorderWidth, newBorderHeight, false); } @@ -259,12 +240,12 @@ void ResizeMap::undo() { if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(oldMetatiles); + *map->layout->blockdata = oldMetatiles; map->setDimensions(oldMapWidth, oldMapHeight, false); } if (map->layout->border) { - map->layout->border->copyFrom(oldBorder); + *map->layout->border = oldBorder; map->setBorderDimensions(oldBorderWidth, oldBorderHeight, false); } @@ -292,8 +273,6 @@ EventMove::EventMove(QList events, this->actionId = actionId; } -EventMove::~EventMove() {} - void EventMove::redo() { QUndoCommand::redo(); @@ -340,8 +319,6 @@ EventShift::EventShift(QList events, setText("Shift Events"); } -EventShift::~EventShift() {} - int EventShift::id() const { return CommandId::ID_EventShift | getEventTypeMask(events); } @@ -360,13 +337,11 @@ EventCreate::EventCreate(Editor *editor, Map *map, Event *event, this->event = event; } -EventCreate::~EventCreate() {} - void EventCreate::redo() { QUndoCommand::redo(); map->addEvent(event); - + editor->project->loadEventPixmaps(map->getAllEvents()); editor->addMapEvent(event); @@ -412,8 +387,6 @@ EventDelete::EventDelete(Editor *editor, Map *map, this->nextSelectedEvent = nextSelectedEvent; } -EventDelete::~EventDelete() {} - void EventDelete::redo() { QUndoCommand::redo(); @@ -435,7 +408,7 @@ void EventDelete::redo() { void EventDelete::undo() { for (Event *event : selectedEvents) { map->addEvent(event); - + editor->project->loadEventPixmaps(map->getAllEvents()); editor->addMapEvent(event); } @@ -469,8 +442,6 @@ EventDuplicate::EventDuplicate(Editor *editor, Map *map, this->selectedEvents = selectedEvents; } -EventDuplicate::~EventDuplicate() {} - void EventDuplicate::redo() { QUndoCommand::redo(); @@ -517,7 +488,7 @@ int EventDuplicate::id() const { ScriptEditMap::ScriptEditMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions, - Blockdata *oldMetatiles, Blockdata *newMetatiles, + const Blockdata &oldMetatiles, const Blockdata &newMetatiles, QUndoCommand *parent) : QUndoCommand(parent) { setText("Script Edit Map"); @@ -532,24 +503,19 @@ ScriptEditMap::ScriptEditMap(Map *map, this->newMapHeight = newMapDimensions.height(); } -ScriptEditMap::~ScriptEditMap() { - if (newMetatiles) delete newMetatiles; - if (oldMetatiles) delete oldMetatiles; -} - void ScriptEditMap::redo() { QUndoCommand::redo(); if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(newMetatiles); + *map->layout->blockdata = newMetatiles; if (newMapWidth != map->getWidth() || newMapHeight != map->getHeight()) { map->setDimensions(newMapWidth, newMapHeight, false); } } - map->layout->lastCommitMapBlocks.blocks->copyFrom(newMetatiles); + *map->layout->lastCommitMapBlocks.blocks = newMetatiles; map->layout->lastCommitMapBlocks.dimensions = QSize(newMapWidth, newMapHeight); renderMapBlocks(map); @@ -559,13 +525,13 @@ void ScriptEditMap::undo() { if (!map) return; if (map->layout->blockdata) { - map->layout->blockdata->copyFrom(oldMetatiles); + *map->layout->blockdata = oldMetatiles; if (oldMapWidth != map->getWidth() || oldMapHeight != map->getHeight()) { map->setDimensions(oldMapWidth, oldMapHeight, false); } } - map->layout->lastCommitMapBlocks.blocks->copyFrom(oldMetatiles); + *map->layout->lastCommitMapBlocks.blocks = oldMetatiles; map->layout->lastCommitMapBlocks.dimensions = QSize(oldMapWidth, oldMapHeight); renderMapBlocks(map); diff --git a/src/core/map.cpp b/src/core/map.cpp index 567c8a24..85af9a99 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -83,16 +83,12 @@ bool Map::mapBlockChanged(int i, Blockdata * cache) { return true; if (!layout->blockdata) return true; - if (!cache->blocks) + if (cache->length() <= i) return true; - if (!layout->blockdata->blocks) - return true; - if (cache->blocks->length() <= i) - return true; - if (layout->blockdata->blocks->length() <= i) + if (layout->blockdata->length() <= i) return true; - return layout->blockdata->blocks->value(i) != cache->blocks->value(i); + return layout->blockdata->value(i) != cache->value(i); } bool Map::borderBlockChanged(int i, Blockdata * cache) { @@ -100,25 +96,21 @@ bool Map::borderBlockChanged(int i, Blockdata * cache) { return true; if (!layout->border) return true; - if (!cache->blocks) + if (cache->length() <= i) return true; - if (!layout->border->blocks) - return true; - if (cache->blocks->length() <= i) - return true; - if (layout->border->blocks->length() <= i) + if (layout->border->length() <= i) return true; - return layout->border->blocks->value(i) != cache->blocks->value(i); + return layout->border->value(i) != cache->value(i); } void Map::cacheBorder() { if (layout->cached_border) delete layout->cached_border; layout->cached_border = new Blockdata; - if (layout->border && layout->border->blocks) { - for (int i = 0; i < layout->border->blocks->length(); i++) { - Block block = layout->border->blocks->value(i); - layout->cached_border->blocks->append(block); + if (layout->border) { + for (int i = 0; i < layout->border->length(); i++) { + Block block = layout->border->value(i); + layout->cached_border->append(block); } } } @@ -126,10 +118,10 @@ void Map::cacheBorder() { void Map::cacheBlockdata() { if (layout->cached_blockdata) delete layout->cached_blockdata; layout->cached_blockdata = new Blockdata; - if (layout->blockdata && layout->blockdata->blocks) { - for (int i = 0; i < layout->blockdata->blocks->length(); i++) { - Block block = layout->blockdata->blocks->value(i); - layout->cached_blockdata->blocks->append(block); + if (layout->blockdata) { + for (int i = 0; i < layout->blockdata->length(); i++) { + Block block = layout->blockdata->value(i); + layout->cached_blockdata->append(block); } } } @@ -137,10 +129,10 @@ void Map::cacheBlockdata() { void Map::cacheCollision() { if (layout->cached_collision) delete layout->cached_collision; layout->cached_collision = new Blockdata; - if (layout->blockdata && layout->blockdata->blocks) { - for (int i = 0; i < layout->blockdata->blocks->length(); i++) { - Block block = layout->blockdata->blocks->value(i); - layout->cached_collision->blocks->append(block); + if (layout->blockdata) { + for (int i = 0; i < layout->blockdata->length(); i++) { + Block block = layout->blockdata->value(i); + layout->cached_collision->append(block); } } } @@ -157,17 +149,17 @@ QPixmap Map::renderCollision(qreal opacity, bool ignoreCache) { collision_image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); changed_any = true; } - if (!(layout->blockdata && layout->blockdata->blocks && width_ && height_)) { + if (!(layout->blockdata && width_ && height_)) { collision_pixmap = collision_pixmap.fromImage(collision_image); return collision_pixmap; } QPainter painter(&collision_image); - for (int i = 0; i < layout->blockdata->blocks->length(); i++) { + for (int i = 0; i < layout->blockdata->length(); i++) { if (!ignoreCache && layout->cached_collision && !mapBlockChanged(i, layout->cached_collision)) { continue; } changed_any = true; - Block block = layout->blockdata->blocks->value(i); + Block block = layout->blockdata->value(i); QImage metatile_image = getMetatileImage(block.tile, layout->tileset_primary, layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity); QImage collision_metatile_image = getCollisionMetatileImage(block); int map_y = width_ ? i / width_ : 0; @@ -200,18 +192,18 @@ QPixmap Map::render(bool ignoreCache = false, MapLayout * fromLayout) { image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); changed_any = true; } - if (!(layout->blockdata && layout->blockdata->blocks && width_ && height_)) { + if (!(layout->blockdata && width_ && height_)) { pixmap = pixmap.fromImage(image); return pixmap; } QPainter painter(&image); - for (int i = 0; i < layout->blockdata->blocks->length(); i++) { + for (int i = 0; i < layout->blockdata->length(); i++) { if (!ignoreCache && !mapBlockChanged(i, layout->cached_blockdata)) { continue; } changed_any = true; - Block block = layout->blockdata->blocks->value(i); + Block block = layout->blockdata->value(i); QImage metatile_image = getMetatileImage( block.tile, fromLayout ? fromLayout->tileset_primary : layout->tileset_primary, @@ -245,18 +237,18 @@ QPixmap Map::renderBorder(bool ignoreCache) { layout->border_image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); border_resized = true; } - if (!(layout->border && layout->border->blocks)) { + if (!layout->border) { layout->border_pixmap = layout->border_pixmap.fromImage(layout->border_image); return layout->border_pixmap; } QPainter painter(&layout->border_image); - for (int i = 0; i < layout->border->blocks->length(); i++) { + for (int i = 0; i < layout->border->length(); i++) { if (!ignoreCache && (!border_resized && !borderBlockChanged(i, layout->cached_border))) { continue; } changed_any = true; - Block block = layout->border->blocks->value(i); + Block block = layout->border->value(i); uint16_t tile = block.tile; QImage metatile_image = getMetatileImage(tile, layout->tileset_primary, layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity); int map_y = width_ ? i / width_ : 0; @@ -316,13 +308,13 @@ void Map::setNewDimensionsBlockdata(int newWidth, int newHeight) { for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - newBlockData->addBlock(layout->blockdata->blocks->value(index)); + newBlockData->append(layout->blockdata->value(index)); } else { - newBlockData->addBlock(0); + newBlockData->append(0); } } - layout->blockdata->copyFrom(newBlockData); + *layout->blockdata = *newBlockData; } void Map::setNewBorderDimensionsBlockdata(int newWidth, int newHeight) { @@ -335,13 +327,13 @@ void Map::setNewBorderDimensionsBlockdata(int newWidth, int newHeight) { for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - newBlockData->addBlock(layout->border->blocks->value(index)); + newBlockData->append(layout->border->value(index)); } else { - newBlockData->addBlock(0); + newBlockData->append(0); } } - layout->border->copyFrom(newBlockData); + *layout->border = *newBlockData; } void Map::setDimensions(int newWidth, int newHeight, bool setNewBlockdata) { @@ -368,10 +360,10 @@ void Map::setBorderDimensions(int newWidth, int newHeight, bool setNewBlockdata) } bool Map::getBlock(int x, int y, Block *out) { - if (layout->blockdata && layout->blockdata->blocks) { + if (layout->blockdata) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { int i = y * getWidth() + x; - *out = layout->blockdata->blocks->value(i); + *out = layout->blockdata->value(i); return true; } } @@ -380,9 +372,9 @@ bool Map::getBlock(int x, int y, Block *out) { void Map::setBlock(int x, int y, Block block, bool enableScriptCallback) { int i = y * getWidth() + x; - if (layout->blockdata && layout->blockdata->blocks && i < layout->blockdata->blocks->size()) { - Block prevBlock = layout->blockdata->blocks->value(i); - layout->blockdata->blocks->replace(i, block); + if (layout->blockdata && i < layout->blockdata->size()) { + Block prevBlock = layout->blockdata->value(i); + layout->blockdata->replace(i, block); if (enableScriptCallback) { Scripting::cb_MetatileChanged(x, y, prevBlock, block); } diff --git a/src/editor.cpp b/src/editor.cpp index d2da8aca..5d7ecd93 100644 --- a/src/editor.cpp +++ b/src/editor.cpp @@ -959,7 +959,7 @@ void Editor::onHoveredMapMetatileChanged(const QPoint &pos) { if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles && pos.x() >= 0 && pos.x() < map->getWidth() && pos.y() >= 0 && pos.y() < map->getHeight()) { int blockIndex = pos.y() * map->getWidth() + pos.x(); - int metatileId = map->layout->blockdata->blocks->at(blockIndex).tile; + int metatileId = map->layout->blockdata->at(blockIndex).tile; this->ui->statusBar->showMessage(QString("X: %1, Y: %2, %3, Scale = %4x") .arg(pos.x()) .arg(pos.y()) @@ -989,8 +989,8 @@ void Editor::onHoveredMapMovementPermissionChanged(int x, int y) { if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles && x >= 0 && x < map->getWidth() && y >= 0 && y < map->getHeight()) { int blockIndex = y * map->getWidth() + x; - uint16_t collision = map->layout->blockdata->blocks->at(blockIndex).collision; - uint16_t elevation = map->layout->blockdata->blocks->at(blockIndex).elevation; + uint16_t collision = map->layout->blockdata->at(blockIndex).collision; + uint16_t elevation = map->layout->blockdata->at(blockIndex).elevation; QString message = QString("X: %1, Y: %2, %3") .arg(x) .arg(y) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 75f4494c..a878b24d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2610,8 +2610,8 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() if (dialog.exec() == QDialog::Accepted) { Map *map = editor->map; - Blockdata *oldMetatiles = map->layout->blockdata->copy(); - Blockdata *oldBorder = map->layout->border->copy(); + Blockdata *oldMetatiles = new Blockdata(*map->layout->blockdata); + Blockdata *oldBorder = new Blockdata(*map->layout->border); QSize oldMapDimensions(map->getWidth(), map->getHeight()); QSize oldBorderDimensions(map->getBorderWidth(), map->getBorderHeight()); QSize newMapDimensions(widthSpinBox->value(), heightSpinBox->value()); @@ -2621,9 +2621,9 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() editor->map->setBorderDimensions(newBorderDimensions.width(), newBorderDimensions.height()); editor->map->editHistory.push(new ResizeMap(map, oldMapDimensions, newMapDimensions, - oldMetatiles, map->layout->blockdata->copy(), + *oldMetatiles, *map->layout->blockdata, oldBorderDimensions, newBorderDimensions, - oldBorder, map->layout->border->copy() + *oldBorder, *map->layout->border )); } } diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index 494cb779..630978b3 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -26,7 +26,7 @@ void MainWindow::tryCommitMapChanges(bool commitChanges) { if (map) { map->editHistory.push(new ScriptEditMap(map, map->layout->lastCommitMapBlocks.dimensions, QSize(map->getWidth(), map->getHeight()), - map->layout->lastCommitMapBlocks.blocks->copy(), map->layout->blockdata->copy() + *map->layout->lastCommitMapBlocks.blocks, *map->layout->blockdata )); } } diff --git a/src/project.cpp b/src/project.cpp index 19df02a9..0e311c43 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1186,17 +1186,16 @@ bool Project::loadBlockdata(Map *map) { if (map->layout->lastCommitMapBlocks.blocks) { delete map->layout->lastCommitMapBlocks.blocks; } - map->layout->lastCommitMapBlocks.blocks = new Blockdata; - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); - if (map->layout->blockdata->blocks->count() != map->getWidth() * map->getHeight()) { + if (map->layout->blockdata->count() != map->getWidth() * map->getHeight()) { logWarn(QString("Layout blockdata length %1 does not match dimensions %2x%3 (should be %4). Resizing blockdata.") - .arg(map->layout->blockdata->blocks->count()) + .arg(map->layout->blockdata->count()) .arg(map->getWidth()) .arg(map->getHeight()) .arg(map->getWidth() * map->getHeight())); - map->layout->blockdata->blocks->resize(map->getWidth() * map->getHeight()); + map->layout->blockdata->resize(map->getWidth() * map->getHeight()); } return true; } @@ -1204,11 +1203,10 @@ bool Project::loadBlockdata(Map *map) { void Project::setNewMapBlockdata(Map *map) { Blockdata *blockdata = new Blockdata; for (int i = 0; i < map->getWidth() * map->getHeight(); i++) { - blockdata->addBlock(qint16(0x3001)); + blockdata->append(qint16(0x3001)); } map->layout->blockdata = blockdata; - map->layout->lastCommitMapBlocks.blocks = new Blockdata; - map->layout->lastCommitMapBlocks.blocks->copyFrom(map->layout->blockdata); + *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); } @@ -1220,11 +1218,11 @@ bool Project::loadMapBorder(Map *map) { QString path = QString("%1/%2").arg(root).arg(map->layout->border_path); map->layout->border = readBlockdata(path); int borderLength = map->getBorderWidth() * map->getBorderHeight(); - if (map->layout->border->blocks->count() != borderLength) { + if (map->layout->border->count() != borderLength) { logWarn(QString("Layout border blockdata length %1 must be %2. Resizing border blockdata.") - .arg(map->layout->border->blocks->count()) + .arg(map->layout->border->count()) .arg(borderLength)); - map->layout->border->blocks->resize(borderLength); + map->layout->border->resize(borderLength); } return true; } @@ -1233,18 +1231,18 @@ void Project::setNewMapBorder(Map *map) { Blockdata *blockdata = new Blockdata; if (map->getBorderWidth() != DEFAULT_BORDER_WIDTH || map->getBorderHeight() != DEFAULT_BORDER_HEIGHT) { for (int i = 0; i < map->getBorderWidth() * map->getBorderHeight(); i++) { - blockdata->addBlock(0); + blockdata->append(0); } } else if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) { - blockdata->addBlock(qint16(0x0014)); - blockdata->addBlock(qint16(0x0015)); - blockdata->addBlock(qint16(0x001C)); - blockdata->addBlock(qint16(0x001D)); + blockdata->append(qint16(0x0014)); + blockdata->append(qint16(0x0015)); + blockdata->append(qint16(0x001C)); + blockdata->append(qint16(0x001D)); } else { - blockdata->addBlock(qint16(0x01D4)); - blockdata->addBlock(qint16(0x01D5)); - blockdata->addBlock(qint16(0x01DC)); - blockdata->addBlock(qint16(0x01DD)); + blockdata->append(qint16(0x01D4)); + blockdata->append(qint16(0x01D5)); + blockdata->append(qint16(0x01DC)); + blockdata->append(qint16(0x01DD)); } map->layout->border = blockdata; } @@ -1709,7 +1707,7 @@ Blockdata* Project::readBlockdata(QString path) { QByteArray data = file.readAll(); for (int i = 0; (i + 1) < data.length(); i += 2) { uint16_t word = static_cast((data[i] & 0xff) + ((data[i + 1] & 0xff) << 8)); - blockdata->addBlock(word); + blockdata->append(word); } } else { logError(QString("Failed to open blockdata path '%1'").arg(path)); diff --git a/src/ui/bordermetatilespixmapitem.cpp b/src/ui/bordermetatilespixmapitem.cpp index 1c34e707..3f78a526 100644 --- a/src/ui/bordermetatilespixmapitem.cpp +++ b/src/ui/bordermetatilespixmapitem.cpp @@ -11,22 +11,22 @@ void BorderMetatilesPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event) int width = map->getBorderWidth(); int height = map->getBorderHeight(); - Blockdata *oldBorder = map->layout->border->copy(); + Blockdata *oldBorder = new Blockdata(*map->layout->border); for (int i = 0; i < selectionDimensions.x() && (i + pos.x()) < width; i++) { for (int j = 0; j < selectionDimensions.y() && (j + pos.y()) < height; j++) { int blockIndex = (j + pos.y()) * width + (i + pos.x()); uint16_t tile = selectedMetatiles->at(j * selectionDimensions.x() + i); - (*map->layout->border->blocks)[blockIndex].tile = tile; + (*map->layout->border)[blockIndex].tile = tile; } } - Blockdata *newBorder = map->layout->border->copy(); - if (newBorder->equals(oldBorder)) { + Blockdata *newBorder = new Blockdata(*map->layout->border); + if (*newBorder == *oldBorder) { delete newBorder; delete oldBorder; } else { - map->editHistory.push(new PaintBorder(map, oldBorder, newBorder, 0)); + map->editHistory.push(new PaintBorder(map, *oldBorder, *newBorder, 0)); } emit borderMetatilesChanged(); @@ -39,7 +39,6 @@ void BorderMetatilesPixmapItem::draw() { int height = map->getBorderHeight(); QImage image(16 * width, 16 * height, QImage::Format_RGBA8888); QPainter painter(&image); - QVector *blocks = map->layout->border->blocks; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { @@ -47,7 +46,7 @@ void BorderMetatilesPixmapItem::draw() { int y = j * 16; int index = j * width + i; QImage metatile_image = getMetatileImage( - blocks->value(index).tile, + map->layout->border->value(index).tile, map->layout->tileset_primary, map->layout->tileset_secondary, map->metatileLayerOrder, diff --git a/src/ui/collisionpixmapitem.cpp b/src/ui/collisionpixmapitem.cpp index 3dbeb391..2e9b3007 100644 --- a/src/ui/collisionpixmapitem.cpp +++ b/src/ui/collisionpixmapitem.cpp @@ -45,7 +45,7 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { actionId_++; } else if (map) { - Blockdata *oldCollision = map->layout->blockdata->copy(); + Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); @@ -65,12 +65,12 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { map->setBlock(pos.x(), pos.y(), block, true); } - Blockdata *newCollision = map->layout->blockdata->copy(); - if (newCollision->equals(oldCollision)) { + Blockdata *newCollision = new Blockdata(*map->layout->blockdata); + if (*newCollision == *oldCollision) { delete newCollision; delete oldCollision; } else { - map->editHistory.push(new PaintCollision(map, oldCollision, newCollision, actionId_)); + map->editHistory.push(new PaintCollision(map, *oldCollision, *newCollision, actionId_)); } } } @@ -79,19 +79,19 @@ void CollisionPixmapItem::floodFill(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { this->actionId_++; } else if (map) { - Blockdata *oldCollision = map->layout->blockdata->copy(); + Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); uint16_t collision = this->movementPermissionsSelector->getSelectedCollision(); uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->floodFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata *newCollision = map->layout->blockdata->copy(); - if (newCollision->equals(oldCollision)) { + Blockdata *newCollision = new Blockdata(*map->layout->blockdata); + if (*newCollision == *oldCollision) { delete newCollision; delete oldCollision; } else { - map->editHistory.push(new BucketFillCollision(map, oldCollision, newCollision)); + map->editHistory.push(new BucketFillCollision(map, *oldCollision, *newCollision)); } } } @@ -100,18 +100,18 @@ void CollisionPixmapItem::magicFill(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { this->actionId_++; } else if (map) { - Blockdata *oldCollision = map->layout->blockdata->copy(); + Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); uint16_t collision = this->movementPermissionsSelector->getSelectedCollision(); uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->magicFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata *newCollision = map->layout->blockdata->copy(); - if (newCollision->equals(oldCollision)) { + Blockdata *newCollision = new Blockdata(*map->layout->blockdata); + if (*newCollision == *oldCollision) { delete newCollision; delete oldCollision; } else { - map->editHistory.push(new MagicFillCollision(map, oldCollision, newCollision)); + map->editHistory.push(new MagicFillCollision(map, *oldCollision, *newCollision)); } } } diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index 5e524896..ba2618cb 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -76,7 +76,7 @@ void MapPixmapItem::shift(QGraphicsSceneMouseEvent *event) { } void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { - Blockdata *backupBlockdata = map->layout->blockdata->copy(); + Blockdata *backupBlockdata = new Blockdata(*map->layout->blockdata); for (int i = 0; i < map->getWidth(); i++) for (int j = 0; j < map->getHeight(); j++) { int destX = i + xDelta; @@ -89,17 +89,17 @@ void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { destY %= map->getHeight(); int blockIndex = j * map->getWidth() + i; - Block srcBlock = backupBlockdata->blocks->at(blockIndex); + Block srcBlock = backupBlockdata->at(blockIndex); map->setBlock(destX, destY, srcBlock); } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(backupBlockdata)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *backupBlockdata) { delete newMetatiles; delete backupBlockdata; } else { - map->editHistory.push(new ShiftMetatiles(map, backupBlockdata, newMetatiles, actionId_)); + map->editHistory.push(new ShiftMetatiles(map, *backupBlockdata, *newMetatiles, actionId_)); } } else { delete backupBlockdata; @@ -125,7 +125,7 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { // for edit history Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); + if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); for (int i = 0; i < selectionDimensions.x() && i + x < map->getWidth(); i++) for (int j = 0; j < selectionDimensions.y() && j + y < map->getHeight(); j++) { @@ -144,12 +144,12 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(oldMetatiles)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *oldMetatiles) { delete newMetatiles; delete oldMetatiles; } else { - map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); + map->editHistory.push(new PaintMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); } } } @@ -199,7 +199,7 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { // for edit history Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); + if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); // Fill the region with the open tile. for (int i = 0; i <= 1; i++) @@ -264,12 +264,12 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(oldMetatiles)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *oldMetatiles) { delete newMetatiles; delete oldMetatiles; } else { - map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); + map->editHistory.push(new PaintMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); } } } @@ -287,7 +287,7 @@ void MapPixmapItem::lockNondominantAxis(QGraphicsSceneMouseEvent *event) { this->straight_path_initial_x = pos.x(); this->straight_path_initial_y = pos.y(); } - + // Only lock an axis when the current position != initial int xDiff = pos.x() - this->straight_path_initial_x; int yDiff = pos.y() - this->straight_path_initial_y; @@ -352,7 +352,7 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) { metatiles.append(block.tile); } int blockIndex = y * map->getWidth() + x; - block = map->layout->blockdata->blocks->at(blockIndex); + block = map->layout->blockdata->at(blockIndex); auto collision = block.collision; auto elevation = block.elevation; collisions.append(QPair(collision, elevation)); @@ -422,7 +422,7 @@ void MapPixmapItem::magicFill( } Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); + if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); uint16_t tile = block.tile; @@ -447,12 +447,12 @@ void MapPixmapItem::magicFill( } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(oldMetatiles)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *oldMetatiles) { delete newMetatiles; delete oldMetatiles; } else { - map->editHistory.push(new MagicFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); + map->editHistory.push(new MagicFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); } } } @@ -482,7 +482,7 @@ void MapPixmapItem::floodFill( bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); Blockdata *oldMetatiles = nullptr; if (!fromScriptCall) { - oldMetatiles = map->layout->blockdata->copy(); + oldMetatiles = new Blockdata(*map->layout->blockdata); } QSet visited; @@ -534,12 +534,12 @@ void MapPixmapItem::floodFill( } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(oldMetatiles)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *oldMetatiles) { delete newMetatiles; delete oldMetatiles; } else { - map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); + map->editHistory.push(new BucketFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); } } } @@ -564,7 +564,7 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri } Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = map->layout->blockdata->copy(); + if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); // Flood fill the region with the open tile. QList todo; @@ -660,13 +660,13 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri } if (!fromScriptCall) { - Blockdata *newMetatiles = map->layout->blockdata->copy(); - if (newMetatiles->equals(oldMetatiles)) { + Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); + if (*newMetatiles == *oldMetatiles) { delete newMetatiles; delete oldMetatiles; } else { - map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + map->editHistory.push(new BucketFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + } } } From f09e28f06c553af6689e545f5e1c75665b4dbeb2 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 16:34:17 -0500 Subject: [PATCH 18/46] Convert usages of Blockdata pointers --- include/core/blockdata.h | 2 +- include/core/map.h | 4 +- include/core/maplayout.h | 12 +- include/project.h | 4 +- src/core/blockdata.cpp | 2 +- src/core/editcommands.cpp | 76 ++++-------- src/core/map.cpp | 177 +++++++++++---------------- src/editor.cpp | 6 +- src/mainwindow.cpp | 8 +- src/mainwindow_scriptapi.cpp | 2 +- src/project.cpp | 56 ++++----- src/ui/bordermetatilespixmapitem.cpp | 15 +-- src/ui/collisionpixmapitem.cpp | 33 ++--- src/ui/mappixmapitem.cpp | 79 ++++-------- 14 files changed, 186 insertions(+), 290 deletions(-) diff --git a/include/core/blockdata.h b/include/core/blockdata.h index 5d434f21..a1e45b63 100644 --- a/include/core/blockdata.h +++ b/include/core/blockdata.h @@ -10,7 +10,7 @@ class Blockdata : public QVector { public: - QByteArray serialize(); + QByteArray serialize() const; }; #endif // BLOCKDATA_H diff --git a/include/core/map.h b/include/core/map.h index cedb7c19..ba871317 100644 --- a/include/core/map.h +++ b/include/core/map.h @@ -75,8 +75,8 @@ public: int getBorderHeight(); QPixmap render(bool ignoreCache, MapLayout * fromLayout = nullptr); QPixmap renderCollision(qreal opacity, bool ignoreCache); - bool mapBlockChanged(int i, Blockdata * cache); - bool borderBlockChanged(int i, Blockdata * cache); + bool mapBlockChanged(int i, Blockdata cache); + bool borderBlockChanged(int i, Blockdata cache); void cacheBlockdata(); void cacheCollision(); bool getBlock(int x, int y, Block *out); diff --git a/include/core/maplayout.h b/include/core/maplayout.h index d04fbab5..38bb3f23 100644 --- a/include/core/maplayout.h +++ b/include/core/maplayout.h @@ -24,15 +24,15 @@ public: QString tileset_secondary_label; Tileset *tileset_primary = nullptr; Tileset *tileset_secondary = nullptr; - Blockdata *blockdata = nullptr; + Blockdata blockdata; QImage border_image; QPixmap border_pixmap; - Blockdata *border = nullptr; - Blockdata *cached_blockdata = nullptr; - Blockdata *cached_collision = nullptr; - Blockdata *cached_border = nullptr; + Blockdata border; + Blockdata cached_blockdata; + Blockdata cached_collision; + Blockdata cached_border; struct { - Blockdata *blocks = nullptr; + Blockdata blocks; QSize dimensions; } lastCommitMapBlocks; // to track map changes }; diff --git a/include/project.h b/include/project.h index 085cd6d1..988a8316 100644 --- a/include/project.h +++ b/include/project.h @@ -91,7 +91,7 @@ public: Tileset* getTileset(QString, bool forceLoad = false); QMap tilesetLabels; - Blockdata* readBlockdata(QString); + Blockdata readBlockdata(QString); bool loadBlockdata(Map*); void saveTextFile(QString path, QString text); @@ -129,7 +129,7 @@ public: void saveLayoutBlockdata(Map*); void saveLayoutBorder(Map*); - void writeBlockdata(QString, Blockdata*); + void writeBlockdata(QString, const Blockdata &); void saveAllMaps(); void saveMap(Map*); void saveAllDataStructures(); diff --git a/src/core/blockdata.cpp b/src/core/blockdata.cpp index ab42b888..5fcd4e32 100644 --- a/src/core/blockdata.cpp +++ b/src/core/blockdata.cpp @@ -1,6 +1,6 @@ #include "blockdata.h" -QByteArray Blockdata::serialize() { +QByteArray Blockdata::serialize() const { QByteArray data; for (const auto &block : *this) { uint16_t word = block.rawValue(); diff --git a/src/core/editcommands.cpp b/src/core/editcommands.cpp index efc30d25..e7a3d300 100644 --- a/src/core/editcommands.cpp +++ b/src/core/editcommands.cpp @@ -49,11 +49,9 @@ void PaintMetatile::redo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = newMetatiles; - } + map->layout->blockdata = newMetatiles; - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; renderMapBlocks(map); } @@ -61,11 +59,9 @@ void PaintMetatile::redo() { void PaintMetatile::undo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = oldMetatiles; - } + map->layout->blockdata = oldMetatiles; - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; renderMapBlocks(map); @@ -107,9 +103,7 @@ void PaintBorder::redo() { if (!map) return; - if (map->layout->border) { - *map->layout->border = newBorder; - } + map->layout->border = newBorder; map->borderItem->draw(); } @@ -117,9 +111,7 @@ void PaintBorder::redo() { void PaintBorder::undo() { if (!map) return; - if (map->layout->border) { - *map->layout->border = oldBorder; - } + map->layout->border = oldBorder; map->borderItem->draw(); @@ -147,11 +139,9 @@ void ShiftMetatiles::redo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = newMetatiles; - } + map->layout->blockdata = newMetatiles; - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; renderMapBlocks(map, true); } @@ -159,11 +149,9 @@ void ShiftMetatiles::redo() { void ShiftMetatiles::undo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = oldMetatiles; - } + map->layout->blockdata = oldMetatiles; - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; renderMapBlocks(map, true); @@ -221,15 +209,11 @@ void ResizeMap::redo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = newMetatiles; - map->setDimensions(newMapWidth, newMapHeight, false); - } + map->layout->blockdata = newMetatiles; + map->setDimensions(newMapWidth, newMapHeight, false); - if (map->layout->border) { - *map->layout->border = newBorder; - map->setBorderDimensions(newBorderWidth, newBorderHeight, false); - } + map->layout->border = newBorder; + map->setBorderDimensions(newBorderWidth, newBorderHeight, false); map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); @@ -239,15 +223,11 @@ void ResizeMap::redo() { void ResizeMap::undo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = oldMetatiles; - map->setDimensions(oldMapWidth, oldMapHeight, false); - } + map->layout->blockdata = oldMetatiles; + map->setDimensions(oldMapWidth, oldMapHeight, false); - if (map->layout->border) { - *map->layout->border = oldBorder; - map->setBorderDimensions(oldBorderWidth, oldBorderHeight, false); - } + map->layout->border = oldBorder; + map->setBorderDimensions(oldBorderWidth, oldBorderHeight, false); map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); @@ -508,14 +488,12 @@ void ScriptEditMap::redo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = newMetatiles; - if (newMapWidth != map->getWidth() || newMapHeight != map->getHeight()) { - map->setDimensions(newMapWidth, newMapHeight, false); - } + map->layout->blockdata = newMetatiles; + if (newMapWidth != map->getWidth() || newMapHeight != map->getHeight()) { + map->setDimensions(newMapWidth, newMapHeight, false); } - *map->layout->lastCommitMapBlocks.blocks = newMetatiles; + map->layout->lastCommitMapBlocks.blocks = newMetatiles; map->layout->lastCommitMapBlocks.dimensions = QSize(newMapWidth, newMapHeight); renderMapBlocks(map); @@ -524,14 +502,12 @@ void ScriptEditMap::redo() { void ScriptEditMap::undo() { if (!map) return; - if (map->layout->blockdata) { - *map->layout->blockdata = oldMetatiles; - if (oldMapWidth != map->getWidth() || oldMapHeight != map->getHeight()) { - map->setDimensions(oldMapWidth, oldMapHeight, false); - } + map->layout->blockdata = oldMetatiles; + if (oldMapWidth != map->getWidth() || oldMapHeight != map->getHeight()) { + map->setDimensions(oldMapWidth, oldMapHeight, false); } - *map->layout->lastCommitMapBlocks.blocks = oldMetatiles; + map->layout->lastCommitMapBlocks.blocks = oldMetatiles; map->layout->lastCommitMapBlocks.dimensions = QSize(oldMapWidth, oldMapHeight); renderMapBlocks(map); diff --git a/src/core/map.cpp b/src/core/map.cpp index 85af9a99..0f126fa8 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -78,88 +78,61 @@ int Map::getBorderHeight() { return layout->border_height.toInt(nullptr, 0); } -bool Map::mapBlockChanged(int i, Blockdata * cache) { - if (!cache) +bool Map::mapBlockChanged(int i, Blockdata cache) { + if (cache.length() <= i) return true; - if (!layout->blockdata) - return true; - if (cache->length() <= i) - return true; - if (layout->blockdata->length() <= i) + if (layout->blockdata.length() <= i) return true; - return layout->blockdata->value(i) != cache->value(i); + return layout->blockdata.at(i) != cache.at(i); } -bool Map::borderBlockChanged(int i, Blockdata * cache) { - if (!cache) +bool Map::borderBlockChanged(int i, Blockdata cache) { + if (cache.length() <= i) return true; - if (!layout->border) - return true; - if (cache->length() <= i) - return true; - if (layout->border->length() <= i) + if (layout->border.length() <= i) return true; - return layout->border->value(i) != cache->value(i); + return layout->border.at(i) != cache.at(i); } void Map::cacheBorder() { - if (layout->cached_border) delete layout->cached_border; - layout->cached_border = new Blockdata; - if (layout->border) { - for (int i = 0; i < layout->border->length(); i++) { - Block block = layout->border->value(i); - layout->cached_border->append(block); - } - } + layout->cached_border.clear(); + for (const auto &block : layout->border) + layout->cached_border.append(block); } void Map::cacheBlockdata() { - if (layout->cached_blockdata) delete layout->cached_blockdata; - layout->cached_blockdata = new Blockdata; - if (layout->blockdata) { - for (int i = 0; i < layout->blockdata->length(); i++) { - Block block = layout->blockdata->value(i); - layout->cached_blockdata->append(block); - } - } + layout->cached_blockdata.clear(); + for (const auto &block : layout->blockdata) + layout->cached_blockdata.append(block); } void Map::cacheCollision() { - if (layout->cached_collision) delete layout->cached_collision; - layout->cached_collision = new Blockdata; - if (layout->blockdata) { - for (int i = 0; i < layout->blockdata->length(); i++) { - Block block = layout->blockdata->value(i); - layout->cached_collision->append(block); - } - } + layout->cached_collision.clear(); + for (const auto &block : layout->blockdata) + layout->cached_collision.append(block); } QPixmap Map::renderCollision(qreal opacity, bool ignoreCache) { bool changed_any = false; int width_ = getWidth(); int height_ = getHeight(); - if ( - collision_image.isNull() - || collision_image.width() != width_ * 16 - || collision_image.height() != height_ * 16 - ) { + if (collision_image.isNull() || collision_image.width() != width_ * 16 || collision_image.height() != height_ * 16) { collision_image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); changed_any = true; } - if (!(layout->blockdata && width_ && height_)) { + if (layout->blockdata.isEmpty() || !width_ || !height_) { collision_pixmap = collision_pixmap.fromImage(collision_image); return collision_pixmap; } QPainter painter(&collision_image); - for (int i = 0; i < layout->blockdata->length(); i++) { - if (!ignoreCache && layout->cached_collision && !mapBlockChanged(i, layout->cached_collision)) { + for (int i = 0; i < layout->blockdata.length(); i++) { + if (!ignoreCache && !mapBlockChanged(i, layout->cached_collision)) { continue; } changed_any = true; - Block block = layout->blockdata->value(i); + Block block = layout->blockdata.at(i); QImage metatile_image = getMetatileImage(block.tile, layout->tileset_primary, layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity); QImage collision_metatile_image = getCollisionMetatileImage(block); int map_y = width_ ? i / width_ : 0; @@ -184,26 +157,22 @@ QPixmap Map::render(bool ignoreCache = false, MapLayout * fromLayout) { bool changed_any = false; int width_ = getWidth(); int height_ = getHeight(); - if ( - image.isNull() - || image.width() != width_ * 16 - || image.height() != height_ * 16 - ) { + if (image.isNull() || image.width() != width_ * 16 || image.height() != height_ * 16) { image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); changed_any = true; } - if (!(layout->blockdata && width_ && height_)) { + if (layout->blockdata.isEmpty() || !width_ || !height_) { pixmap = pixmap.fromImage(image); return pixmap; } QPainter painter(&image); - for (int i = 0; i < layout->blockdata->length(); i++) { + for (int i = 0; i < layout->blockdata.length(); i++) { if (!ignoreCache && !mapBlockChanged(i, layout->cached_blockdata)) { continue; } changed_any = true; - Block block = layout->blockdata->value(i); + Block block = layout->blockdata.at(i); QImage metatile_image = getMetatileImage( block.tile, fromLayout ? fromLayout->tileset_primary : layout->tileset_primary, @@ -237,18 +206,18 @@ QPixmap Map::renderBorder(bool ignoreCache) { layout->border_image = QImage(width_ * 16, height_ * 16, QImage::Format_RGBA8888); border_resized = true; } - if (!layout->border) { + if (layout->border.isEmpty()) { layout->border_pixmap = layout->border_pixmap.fromImage(layout->border_image); return layout->border_pixmap; } QPainter painter(&layout->border_image); - for (int i = 0; i < layout->border->length(); i++) { + for (int i = 0; i < layout->border.length(); i++) { if (!ignoreCache && (!border_resized && !borderBlockChanged(i, layout->cached_border))) { continue; } changed_any = true; - Block block = layout->border->value(i); + Block block = layout->border.at(i); uint16_t tile = block.tile; QImage metatile_image = getMetatileImage(tile, layout->tileset_primary, layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity); int map_y = width_ ? i / width_ : 0; @@ -302,38 +271,34 @@ void Map::setNewDimensionsBlockdata(int newWidth, int newHeight) { int oldWidth = getWidth(); int oldHeight = getHeight(); - Blockdata* newBlockData = new Blockdata; + layout->blockdata.clear(); for (int y = 0; y < newHeight; y++) for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - newBlockData->append(layout->blockdata->value(index)); + layout->blockdata.append(layout->blockdata.value(index)); } else { - newBlockData->append(0); + layout->blockdata.append(0); } } - - *layout->blockdata = *newBlockData; } void Map::setNewBorderDimensionsBlockdata(int newWidth, int newHeight) { int oldWidth = getBorderWidth(); int oldHeight = getBorderHeight(); - Blockdata* newBlockData = new Blockdata; + layout->border.clear(); for (int y = 0; y < newHeight; y++) for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - newBlockData->append(layout->border->value(index)); + layout->border.append(layout->border.value(index)); } else { - newBlockData->append(0); + layout->border.append(0); } } - - *layout->border = *newBlockData; } void Map::setDimensions(int newWidth, int newHeight, bool setNewBlockdata) { @@ -360,21 +325,19 @@ void Map::setBorderDimensions(int newWidth, int newHeight, bool setNewBlockdata) } bool Map::getBlock(int x, int y, Block *out) { - if (layout->blockdata) { - if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { - int i = y * getWidth() + x; - *out = layout->blockdata->value(i); - return true; - } + if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { + int i = y * getWidth() + x; + *out = layout->blockdata.value(i); + return true; } return false; } void Map::setBlock(int x, int y, Block block, bool enableScriptCallback) { int i = y * getWidth() + x; - if (layout->blockdata && i < layout->blockdata->size()) { - Block prevBlock = layout->blockdata->value(i); - layout->blockdata->replace(i, block); + if (i < layout->blockdata.size()) { + Block prevBlock = layout->blockdata.at(i); + layout->blockdata.replace(i, block); if (enableScriptCallback) { Scripting::cb_MetatileChanged(x, y, prevBlock, block); } @@ -385,40 +348,40 @@ void Map::_floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_ QList todo; todo.append(QPoint(x, y)); while (todo.length()) { - QPoint point = todo.takeAt(0); - x = point.x(); - y = point.y(); - Block block; - if (!getBlock(x, y, &block)) { - continue; - } + QPoint point = todo.takeAt(0); + x = point.x(); + y = point.y(); + Block block; + if (!getBlock(x, y, &block)) { + continue; + } - uint old_coll = block.collision; - uint old_elev = block.elevation; - if (old_coll == collision && old_elev == elevation) { - continue; - } + uint old_coll = block.collision; + uint old_elev = block.elevation; + if (old_coll == collision && old_elev == elevation) { + continue; + } - block.collision = collision; - block.elevation = elevation; - setBlock(x, y, block, true); - if (getBlock(x + 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { - todo.append(QPoint(x + 1, y)); - } - if (getBlock(x - 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { - todo.append(QPoint(x - 1, y)); - } - if (getBlock(x, y + 1, &block) && block.collision == old_coll && block.elevation == old_elev) { - todo.append(QPoint(x, y + 1)); - } - if (getBlock(x, y - 1, &block) && block.collision == old_coll && block.elevation == old_elev) { - todo.append(QPoint(x, y - 1)); - } + block.collision = collision; + block.elevation = elevation; + setBlock(x, y, block, true); + if (getBlock(x + 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { + todo.append(QPoint(x + 1, y)); + } + if (getBlock(x - 1, y, &block) && block.collision == old_coll && block.elevation == old_elev) { + todo.append(QPoint(x - 1, y)); + } + if (getBlock(x, y + 1, &block) && block.collision == old_coll && block.elevation == old_elev) { + todo.append(QPoint(x, y + 1)); + } + if (getBlock(x, y - 1, &block) && block.collision == old_coll && block.elevation == old_elev) { + todo.append(QPoint(x, y - 1)); + } } } void Map::floodFillCollisionElevation(int x, int y, uint16_t collision, uint16_t elevation) { - Block block;; + Block block; if (getBlock(x, y, &block) && (block.collision != collision || block.elevation != elevation)) { _floodFillCollisionElevation(x, y, collision, elevation); } diff --git a/src/editor.cpp b/src/editor.cpp index 5d7ecd93..f855d9f3 100644 --- a/src/editor.cpp +++ b/src/editor.cpp @@ -959,7 +959,7 @@ void Editor::onHoveredMapMetatileChanged(const QPoint &pos) { if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles && pos.x() >= 0 && pos.x() < map->getWidth() && pos.y() >= 0 && pos.y() < map->getHeight()) { int blockIndex = pos.y() * map->getWidth() + pos.x(); - int metatileId = map->layout->blockdata->at(blockIndex).tile; + int metatileId = map->layout->blockdata.at(blockIndex).tile; this->ui->statusBar->showMessage(QString("X: %1, Y: %2, %3, Scale = %4x") .arg(pos.x()) .arg(pos.y()) @@ -989,8 +989,8 @@ void Editor::onHoveredMapMovementPermissionChanged(int x, int y) { if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles && x >= 0 && x < map->getWidth() && y >= 0 && y < map->getHeight()) { int blockIndex = y * map->getWidth() + x; - uint16_t collision = map->layout->blockdata->at(blockIndex).collision; - uint16_t elevation = map->layout->blockdata->at(blockIndex).elevation; + uint16_t collision = map->layout->blockdata.at(blockIndex).collision; + uint16_t elevation = map->layout->blockdata.at(blockIndex).elevation; QString message = QString("X: %1, Y: %2, %3") .arg(x) .arg(y) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index a878b24d..22df6d71 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2610,8 +2610,8 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() if (dialog.exec() == QDialog::Accepted) { Map *map = editor->map; - Blockdata *oldMetatiles = new Blockdata(*map->layout->blockdata); - Blockdata *oldBorder = new Blockdata(*map->layout->border); + Blockdata oldMetatiles = map->layout->blockdata; + Blockdata oldBorder = map->layout->border; QSize oldMapDimensions(map->getWidth(), map->getHeight()); QSize oldBorderDimensions(map->getBorderWidth(), map->getBorderHeight()); QSize newMapDimensions(widthSpinBox->value(), heightSpinBox->value()); @@ -2621,9 +2621,9 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() editor->map->setBorderDimensions(newBorderDimensions.width(), newBorderDimensions.height()); editor->map->editHistory.push(new ResizeMap(map, oldMapDimensions, newMapDimensions, - *oldMetatiles, *map->layout->blockdata, + oldMetatiles, map->layout->blockdata, oldBorderDimensions, newBorderDimensions, - *oldBorder, *map->layout->border + oldBorder, map->layout->border )); } } diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index 630978b3..43d0bfc1 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -26,7 +26,7 @@ void MainWindow::tryCommitMapChanges(bool commitChanges) { if (map) { map->editHistory.push(new ScriptEditMap(map, map->layout->lastCommitMapBlocks.dimensions, QSize(map->getWidth(), map->getHeight()), - *map->layout->lastCommitMapBlocks.blocks, *map->layout->blockdata + map->layout->lastCommitMapBlocks.blocks, map->layout->blockdata )); } } diff --git a/src/project.cpp b/src/project.cpp index 0e311c43..ee041654 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1183,30 +1183,27 @@ bool Project::loadBlockdata(Map *map) { QString path = QString("%1/%2").arg(root).arg(map->layout->blockdata_path); map->layout->blockdata = readBlockdata(path); - if (map->layout->lastCommitMapBlocks.blocks) { - delete map->layout->lastCommitMapBlocks.blocks; - } - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks.clear(); + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); - if (map->layout->blockdata->count() != map->getWidth() * map->getHeight()) { + if (map->layout->blockdata.count() != map->getWidth() * map->getHeight()) { logWarn(QString("Layout blockdata length %1 does not match dimensions %2x%3 (should be %4). Resizing blockdata.") - .arg(map->layout->blockdata->count()) + .arg(map->layout->blockdata.count()) .arg(map->getWidth()) .arg(map->getHeight()) .arg(map->getWidth() * map->getHeight())); - map->layout->blockdata->resize(map->getWidth() * map->getHeight()); + map->layout->blockdata.resize(map->getWidth() * map->getHeight()); } return true; } void Project::setNewMapBlockdata(Map *map) { - Blockdata *blockdata = new Blockdata; + map->layout->blockdata.clear(); for (int i = 0; i < map->getWidth() * map->getHeight(); i++) { - blockdata->append(qint16(0x3001)); + map->layout->blockdata.append(qint16(0x3001)); } - map->layout->blockdata = blockdata; - *map->layout->lastCommitMapBlocks.blocks = *map->layout->blockdata; + map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); } @@ -1218,33 +1215,32 @@ bool Project::loadMapBorder(Map *map) { QString path = QString("%1/%2").arg(root).arg(map->layout->border_path); map->layout->border = readBlockdata(path); int borderLength = map->getBorderWidth() * map->getBorderHeight(); - if (map->layout->border->count() != borderLength) { + if (map->layout->border.count() != borderLength) { logWarn(QString("Layout border blockdata length %1 must be %2. Resizing border blockdata.") - .arg(map->layout->border->count()) + .arg(map->layout->border.count()) .arg(borderLength)); - map->layout->border->resize(borderLength); + map->layout->border.resize(borderLength); } return true; } void Project::setNewMapBorder(Map *map) { - Blockdata *blockdata = new Blockdata; + map->layout->border.clear(); if (map->getBorderWidth() != DEFAULT_BORDER_WIDTH || map->getBorderHeight() != DEFAULT_BORDER_HEIGHT) { for (int i = 0; i < map->getBorderWidth() * map->getBorderHeight(); i++) { - blockdata->append(0); + map->layout->border.append(0); } } else if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) { - blockdata->append(qint16(0x0014)); - blockdata->append(qint16(0x0015)); - blockdata->append(qint16(0x001C)); - blockdata->append(qint16(0x001D)); + map->layout->border.append(qint16(0x0014)); + map->layout->border.append(qint16(0x0015)); + map->layout->border.append(qint16(0x001C)); + map->layout->border.append(qint16(0x001D)); } else { - blockdata->append(qint16(0x01D4)); - blockdata->append(qint16(0x01D5)); - blockdata->append(qint16(0x01DC)); - blockdata->append(qint16(0x01DD)); + map->layout->border.append(qint16(0x01D4)); + map->layout->border.append(qint16(0x01D5)); + map->layout->border.append(qint16(0x01DC)); + map->layout->border.append(qint16(0x01DD)); } - map->layout->border = blockdata; } void Project::saveLayoutBorder(Map *map) { @@ -1257,10 +1253,10 @@ void Project::saveLayoutBlockdata(Map* map) { writeBlockdata(path, map->layout->blockdata); } -void Project::writeBlockdata(QString path, Blockdata *blockdata) { +void Project::writeBlockdata(QString path, const Blockdata &blockdata) { QFile file(path); if (file.open(QIODevice::WriteOnly)) { - QByteArray data = blockdata->serialize(); + QByteArray data = blockdata.serialize(); file.write(data); } else { logError(QString("Failed to open blockdata file for writing: '%1'").arg(path)); @@ -1700,14 +1696,14 @@ void Project::loadTilesetMetatileLabels(Tileset* tileset) { } } -Blockdata* Project::readBlockdata(QString path) { - Blockdata *blockdata = new Blockdata; +Blockdata Project::readBlockdata(QString path) { + Blockdata blockdata; QFile file(path); if (file.open(QIODevice::ReadOnly)) { QByteArray data = file.readAll(); for (int i = 0; (i + 1) < data.length(); i += 2) { uint16_t word = static_cast((data[i] & 0xff) + ((data[i + 1] & 0xff) << 8)); - blockdata->append(word); + blockdata.append(word); } } else { logError(QString("Failed to open blockdata path '%1'").arg(path)); diff --git a/src/ui/bordermetatilespixmapitem.cpp b/src/ui/bordermetatilespixmapitem.cpp index 3f78a526..89558978 100644 --- a/src/ui/bordermetatilespixmapitem.cpp +++ b/src/ui/bordermetatilespixmapitem.cpp @@ -11,22 +11,19 @@ void BorderMetatilesPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event) int width = map->getBorderWidth(); int height = map->getBorderHeight(); - Blockdata *oldBorder = new Blockdata(*map->layout->border); + Blockdata oldBorder = map->layout->border; for (int i = 0; i < selectionDimensions.x() && (i + pos.x()) < width; i++) { for (int j = 0; j < selectionDimensions.y() && (j + pos.y()) < height; j++) { int blockIndex = (j + pos.y()) * width + (i + pos.x()); uint16_t tile = selectedMetatiles->at(j * selectionDimensions.x() + i); - (*map->layout->border)[blockIndex].tile = tile; + map->layout->border[blockIndex].tile = tile; } } - Blockdata *newBorder = new Blockdata(*map->layout->border); - if (*newBorder == *oldBorder) { - delete newBorder; - delete oldBorder; - } else { - map->editHistory.push(new PaintBorder(map, *oldBorder, *newBorder, 0)); + Blockdata newBorder = map->layout->border; + if (newBorder != oldBorder) { + map->editHistory.push(new PaintBorder(map, oldBorder, newBorder, 0)); } emit borderMetatilesChanged(); @@ -46,7 +43,7 @@ void BorderMetatilesPixmapItem::draw() { int y = j * 16; int index = j * width + i; QImage metatile_image = getMetatileImage( - map->layout->border->value(index).tile, + map->layout->border.value(index).tile, map->layout->tileset_primary, map->layout->tileset_secondary, map->metatileLayerOrder, diff --git a/src/ui/collisionpixmapitem.cpp b/src/ui/collisionpixmapitem.cpp index 2e9b3007..b4ef78a5 100644 --- a/src/ui/collisionpixmapitem.cpp +++ b/src/ui/collisionpixmapitem.cpp @@ -45,7 +45,7 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { actionId_++; } else if (map) { - Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); + Blockdata oldCollision = map->layout->blockdata; QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); @@ -65,12 +65,9 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { map->setBlock(pos.x(), pos.y(), block, true); } - Blockdata *newCollision = new Blockdata(*map->layout->blockdata); - if (*newCollision == *oldCollision) { - delete newCollision; - delete oldCollision; - } else { - map->editHistory.push(new PaintCollision(map, *oldCollision, *newCollision, actionId_)); + Blockdata newCollision = map->layout->blockdata; + if (newCollision != oldCollision) { + map->editHistory.push(new PaintCollision(map, oldCollision, newCollision, actionId_)); } } } @@ -79,19 +76,16 @@ void CollisionPixmapItem::floodFill(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { this->actionId_++; } else if (map) { - Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); + Blockdata oldCollision = map->layout->blockdata; QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); uint16_t collision = this->movementPermissionsSelector->getSelectedCollision(); uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->floodFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata *newCollision = new Blockdata(*map->layout->blockdata); - if (*newCollision == *oldCollision) { - delete newCollision; - delete oldCollision; - } else { - map->editHistory.push(new BucketFillCollision(map, *oldCollision, *newCollision)); + Blockdata newCollision = map->layout->blockdata; + if (newCollision != oldCollision) { + map->editHistory.push(new BucketFillCollision(map, oldCollision, newCollision)); } } } @@ -100,18 +94,15 @@ void CollisionPixmapItem::magicFill(QGraphicsSceneMouseEvent *event) { if (event->type() == QEvent::GraphicsSceneMouseRelease) { this->actionId_++; } else if (map) { - Blockdata *oldCollision = new Blockdata(*map->layout->blockdata); + Blockdata oldCollision = map->layout->blockdata; QPoint pos = Metatile::coordFromPixmapCoord(event->pos()); uint16_t collision = this->movementPermissionsSelector->getSelectedCollision(); uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->magicFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata *newCollision = new Blockdata(*map->layout->blockdata); - if (*newCollision == *oldCollision) { - delete newCollision; - delete oldCollision; - } else { - map->editHistory.push(new MagicFillCollision(map, *oldCollision, *newCollision)); + Blockdata newCollision = map->layout->blockdata; + if (newCollision != oldCollision) { + map->editHistory.push(new MagicFillCollision(map, oldCollision, newCollision)); } } } diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index ba2618cb..5bcda7cf 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -76,7 +76,7 @@ void MapPixmapItem::shift(QGraphicsSceneMouseEvent *event) { } void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { - Blockdata *backupBlockdata = new Blockdata(*map->layout->blockdata); + Blockdata backupBlockdata = map->layout->blockdata; for (int i = 0; i < map->getWidth(); i++) for (int j = 0; j < map->getHeight(); j++) { int destX = i + xDelta; @@ -89,20 +89,15 @@ void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { destY %= map->getHeight(); int blockIndex = j * map->getWidth() + i; - Block srcBlock = backupBlockdata->at(blockIndex); + Block srcBlock = backupBlockdata.at(blockIndex); map->setBlock(destX, destY, srcBlock); } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *backupBlockdata) { - delete newMetatiles; - delete backupBlockdata; - } else { - map->editHistory.push(new ShiftMetatiles(map, *backupBlockdata, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != backupBlockdata) { + map->editHistory.push(new ShiftMetatiles(map, backupBlockdata, newMetatiles, actionId_)); } - } else { - delete backupBlockdata; } } @@ -124,8 +119,7 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { y = initialY + (yDiff / selectionDimensions.y()) * selectionDimensions.y(); // for edit history - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); for (int i = 0; i < selectionDimensions.x() && i + x < map->getWidth(); i++) for (int j = 0; j < selectionDimensions.y() && j + y < map->getHeight(); j++) { @@ -144,12 +138,9 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *oldMetatiles) { - delete newMetatiles; - delete oldMetatiles; - } else { - map->editHistory.push(new PaintMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != oldMetatiles) { + map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } } @@ -198,8 +189,7 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { } // for edit history - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); // Fill the region with the open tile. for (int i = 0; i <= 1; i++) @@ -264,12 +254,9 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *oldMetatiles) { - delete newMetatiles; - delete oldMetatiles; - } else { - map->editHistory.push(new PaintMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != oldMetatiles) { + map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } } @@ -352,7 +339,7 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) { metatiles.append(block.tile); } int blockIndex = y * map->getWidth() + x; - block = map->layout->blockdata->at(blockIndex); + block = map->layout->blockdata.at(blockIndex); auto collision = block.collision; auto elevation = block.elevation; collisions.append(QPair(collision, elevation)); @@ -421,8 +408,7 @@ void MapPixmapItem::magicFill( return; } - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); uint16_t tile = block.tile; @@ -447,12 +433,9 @@ void MapPixmapItem::magicFill( } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *oldMetatiles) { - delete newMetatiles; - delete oldMetatiles; - } else { - map->editHistory.push(new MagicFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != oldMetatiles) { + map->editHistory.push(new MagicFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } } @@ -480,10 +463,7 @@ void MapPixmapItem::floodFill( QList> *selectedCollisions, bool fromScriptCall) { bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length(); - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) { - oldMetatiles = new Blockdata(*map->layout->blockdata); - } + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); QSet visited; QList todo; @@ -534,12 +514,9 @@ void MapPixmapItem::floodFill( } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *oldMetatiles) { - delete newMetatiles; - delete oldMetatiles; - } else { - map->editHistory.push(new BucketFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != oldMetatiles) { + map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } } @@ -563,8 +540,7 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri setCollisions = true; } - Blockdata *oldMetatiles = nullptr; - if (!fromScriptCall) oldMetatiles = new Blockdata(*map->layout->blockdata); + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); // Flood fill the region with the open tile. QList todo; @@ -660,12 +636,9 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri } if (!fromScriptCall) { - Blockdata *newMetatiles = new Blockdata(*map->layout->blockdata); - if (*newMetatiles == *oldMetatiles) { - delete newMetatiles; - delete oldMetatiles; - } else { - map->editHistory.push(new BucketFillMetatile(map, *oldMetatiles, *newMetatiles, actionId_)); + Blockdata newMetatiles = map->layout->blockdata; + if (newMetatiles != oldMetatiles) { + map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); } } } From a3326a764bd5d26bfb41743329af1971e99affce Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 16:56:23 -0500 Subject: [PATCH 19/46] Simplify some usages of Blockdata --- include/core/map.h | 4 +-- src/core/map.cpp | 4 +-- src/ui/bordermetatilespixmapitem.cpp | 5 ++- src/ui/collisionpixmapitem.cpp | 15 ++++----- src/ui/mappixmapitem.cpp | 47 +++++++++------------------- 5 files changed, 27 insertions(+), 48 deletions(-) diff --git a/include/core/map.h b/include/core/map.h index ba871317..dd6256cd 100644 --- a/include/core/map.h +++ b/include/core/map.h @@ -75,8 +75,8 @@ public: int getBorderHeight(); QPixmap render(bool ignoreCache, MapLayout * fromLayout = nullptr); QPixmap renderCollision(qreal opacity, bool ignoreCache); - bool mapBlockChanged(int i, Blockdata cache); - bool borderBlockChanged(int i, Blockdata cache); + bool mapBlockChanged(int i, const Blockdata &cache); + bool borderBlockChanged(int i, const Blockdata &cache); void cacheBlockdata(); void cacheCollision(); bool getBlock(int x, int y, Block *out); diff --git a/src/core/map.cpp b/src/core/map.cpp index 0f126fa8..e3bf2012 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -78,7 +78,7 @@ int Map::getBorderHeight() { return layout->border_height.toInt(nullptr, 0); } -bool Map::mapBlockChanged(int i, Blockdata cache) { +bool Map::mapBlockChanged(int i, const Blockdata &cache) { if (cache.length() <= i) return true; if (layout->blockdata.length() <= i) @@ -87,7 +87,7 @@ bool Map::mapBlockChanged(int i, Blockdata cache) { return layout->blockdata.at(i) != cache.at(i); } -bool Map::borderBlockChanged(int i, Blockdata cache) { +bool Map::borderBlockChanged(int i, const Blockdata &cache) { if (cache.length() <= i) return true; if (layout->border.length() <= i) diff --git a/src/ui/bordermetatilespixmapitem.cpp b/src/ui/bordermetatilespixmapitem.cpp index 89558978..8b3592f2 100644 --- a/src/ui/bordermetatilespixmapitem.cpp +++ b/src/ui/bordermetatilespixmapitem.cpp @@ -21,9 +21,8 @@ void BorderMetatilesPixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event) } } - Blockdata newBorder = map->layout->border; - if (newBorder != oldBorder) { - map->editHistory.push(new PaintBorder(map, oldBorder, newBorder, 0)); + if (map->layout->border != oldBorder) { + map->editHistory.push(new PaintBorder(map, oldBorder, map->layout->border, 0)); } emit borderMetatilesChanged(); diff --git a/src/ui/collisionpixmapitem.cpp b/src/ui/collisionpixmapitem.cpp index b4ef78a5..5c658bca 100644 --- a/src/ui/collisionpixmapitem.cpp +++ b/src/ui/collisionpixmapitem.cpp @@ -65,9 +65,8 @@ void CollisionPixmapItem::paint(QGraphicsSceneMouseEvent *event) { map->setBlock(pos.x(), pos.y(), block, true); } - Blockdata newCollision = map->layout->blockdata; - if (newCollision != oldCollision) { - map->editHistory.push(new PaintCollision(map, oldCollision, newCollision, actionId_)); + if (map->layout->blockdata != oldCollision) { + map->editHistory.push(new PaintCollision(map, oldCollision, map->layout->blockdata, actionId_)); } } } @@ -83,9 +82,8 @@ void CollisionPixmapItem::floodFill(QGraphicsSceneMouseEvent *event) { uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->floodFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata newCollision = map->layout->blockdata; - if (newCollision != oldCollision) { - map->editHistory.push(new BucketFillCollision(map, oldCollision, newCollision)); + if (map->layout->blockdata != oldCollision) { + map->editHistory.push(new BucketFillCollision(map, oldCollision, map->layout->blockdata)); } } } @@ -100,9 +98,8 @@ void CollisionPixmapItem::magicFill(QGraphicsSceneMouseEvent *event) { uint16_t elevation = this->movementPermissionsSelector->getSelectedElevation(); map->magicFillCollisionElevation(pos.x(), pos.y(), collision, elevation); - Blockdata newCollision = map->layout->blockdata; - if (newCollision != oldCollision) { - map->editHistory.push(new MagicFillCollision(map, oldCollision, newCollision)); + if (map->layout->blockdata != oldCollision) { + map->editHistory.push(new MagicFillCollision(map, oldCollision, map->layout->blockdata)); } } } diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index 5bcda7cf..35aa9e10 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -76,7 +76,8 @@ void MapPixmapItem::shift(QGraphicsSceneMouseEvent *event) { } void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { - Blockdata backupBlockdata = map->layout->blockdata; + Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); + for (int i = 0; i < map->getWidth(); i++) for (int j = 0; j < map->getHeight(); j++) { int destX = i + xDelta; @@ -89,15 +90,12 @@ void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { destY %= map->getHeight(); int blockIndex = j * map->getWidth() + i; - Block srcBlock = backupBlockdata.at(blockIndex); + Block srcBlock = oldMetatiles.at(blockIndex); map->setBlock(destX, destY, srcBlock); } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != backupBlockdata) { - map->editHistory.push(new ShiftMetatiles(map, backupBlockdata, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new ShiftMetatiles(map, oldMetatiles, map->layout->blockdata, actionId_)); } } @@ -137,11 +135,8 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) { } } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != oldMetatiles) { - map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new PaintMetatile(map, oldMetatiles, map->layout->blockdata, actionId_)); } } @@ -253,11 +248,8 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) { map->setBlock(actualX, actualY, block, !fromScriptCall); } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != oldMetatiles) { - map->editHistory.push(new PaintMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new PaintMetatile(map, oldMetatiles, map->layout->blockdata, actionId_)); } } @@ -432,11 +424,8 @@ void MapPixmapItem::magicFill( } } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != oldMetatiles) { - map->editHistory.push(new MagicFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new MagicFillMetatile(map, oldMetatiles, map->layout->blockdata, actionId_)); } } } @@ -513,11 +502,8 @@ void MapPixmapItem::floodFill( } } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != oldMetatiles) { - map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, map->layout->blockdata, actionId_)); } } @@ -635,11 +621,8 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri } } - if (!fromScriptCall) { - Blockdata newMetatiles = map->layout->blockdata; - if (newMetatiles != oldMetatiles) { - map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, newMetatiles, actionId_)); - } + if (!fromScriptCall && map->layout->blockdata != oldMetatiles) { + map->editHistory.push(new BucketFillMetatile(map, oldMetatiles, map->layout->blockdata, actionId_)); } } From 107ef528e25753e1d9cd877b56e181e6499a10ae Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 18:14:04 -0500 Subject: [PATCH 20/46] Fix map resizing (broke from Blockdata refactoring) --- src/core/map.cpp | 16 ++++++++++------ src/mainwindow.cpp | 2 +- src/project.cpp | 1 - 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/core/map.cpp b/src/core/map.cpp index e3bf2012..3d839ecc 100644 --- a/src/core/map.cpp +++ b/src/core/map.cpp @@ -271,34 +271,38 @@ void Map::setNewDimensionsBlockdata(int newWidth, int newHeight) { int oldWidth = getWidth(); int oldHeight = getHeight(); - layout->blockdata.clear(); + Blockdata newBlockdata; for (int y = 0; y < newHeight; y++) for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - layout->blockdata.append(layout->blockdata.value(index)); + newBlockdata.append(layout->blockdata.value(index)); } else { - layout->blockdata.append(0); + newBlockdata.append(0); } } + + layout->blockdata = newBlockdata; } void Map::setNewBorderDimensionsBlockdata(int newWidth, int newHeight) { int oldWidth = getBorderWidth(); int oldHeight = getBorderHeight(); - layout->border.clear(); + Blockdata newBlockdata; for (int y = 0; y < newHeight; y++) for (int x = 0; x < newWidth; x++) { if (x < oldWidth && y < oldHeight) { int index = y * oldWidth + x; - layout->border.append(layout->border.value(index)); + newBlockdata.append(layout->border.value(index)); } else { - layout->border.append(0); + newBlockdata.append(0); } } + + layout->border = newBlockdata; } void Map::setDimensions(int newWidth, int newHeight, bool setNewBlockdata) { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 22df6d71..508eb085 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2619,7 +2619,7 @@ void MainWindow::on_pushButton_ChangeDimensions_clicked() if (oldMapDimensions != newMapDimensions || oldBorderDimensions != newBorderDimensions) { editor->map->setDimensions(newMapDimensions.width(), newMapDimensions.height()); editor->map->setBorderDimensions(newBorderDimensions.width(), newBorderDimensions.height()); - editor->map->editHistory.push(new ResizeMap(map, + editor->map->editHistory.push(new ResizeMap(map, oldMapDimensions, newMapDimensions, oldMetatiles, map->layout->blockdata, oldBorderDimensions, newBorderDimensions, diff --git a/src/project.cpp b/src/project.cpp index ee041654..dc24259d 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1183,7 +1183,6 @@ bool Project::loadBlockdata(Map *map) { QString path = QString("%1/%2").arg(root).arg(map->layout->blockdata_path); map->layout->blockdata = readBlockdata(path); - map->layout->lastCommitMapBlocks.blocks.clear(); map->layout->lastCommitMapBlocks.blocks = map->layout->blockdata; map->layout->lastCommitMapBlocks.dimensions = QSize(map->getWidth(), map->getHeight()); From c1303d98c3f73a9911d2b456300db33e98a38aff Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 21:21:07 -0500 Subject: [PATCH 21/46] Scriptapi: fix segfault in shift(), add missing flag to the caller of shift() --- src/mainwindow_scriptapi.cpp | 2 +- src/ui/mappixmapitem.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index 43d0bfc1..6fa61340 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -149,7 +149,7 @@ void MainWindow::magicFillFromSelection(int x, int y, bool forceRedraw, bool com void MainWindow::shift(int xDelta, int yDelta, bool forceRedraw, bool commitChanges) { if (!this->editor || !this->editor->map) return; - this->editor->map_item->shift(xDelta, yDelta); + this->editor->map_item->shift(xDelta, yDelta, true); this->tryCommitMapChanges(commitChanges); this->tryRedrawMapArea(forceRedraw); } diff --git a/src/ui/mappixmapitem.cpp b/src/ui/mappixmapitem.cpp index 35aa9e10..e7f82bb0 100644 --- a/src/ui/mappixmapitem.cpp +++ b/src/ui/mappixmapitem.cpp @@ -76,7 +76,7 @@ void MapPixmapItem::shift(QGraphicsSceneMouseEvent *event) { } void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) { - Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata(); + Blockdata oldMetatiles = map->layout->blockdata; for (int i = 0; i < map->getWidth(); i++) for (int j = 0; j < map->getHeight(); j++) { From cc7a5f5819bd9c31c58a6de8d1efe75e28cae53d Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 21:45:54 -0500 Subject: [PATCH 22/46] Fix memory leaks in Tileset --- include/core/metatileparser.h | 2 +- include/core/tile.h | 16 +++++- include/core/tileset.h | 17 ++++--- include/mainwindow.h | 4 +- src/core/metatileparser.cpp | 18 +++---- src/core/tile.cpp | 9 ---- src/core/tileset.cpp | 65 +++--------------------- src/mainwindow.cpp | 27 ++++------ src/mainwindow_scriptapi.cpp | 23 ++++----- src/project.cpp | 56 ++++++++++---------- src/ui/imageproviders.cpp | 4 +- src/ui/metatileselector.cpp | 15 +++--- src/ui/paletteeditor.cpp | 24 ++++----- src/ui/tileseteditor.cpp | 48 +++++++---------- src/ui/tileseteditormetatileselector.cpp | 17 +++---- src/ui/tileseteditortileselector.cpp | 17 +++---- 16 files changed, 147 insertions(+), 215 deletions(-) delete mode 100644 src/core/tile.cpp diff --git a/include/core/metatileparser.h b/include/core/metatileparser.h index 7bf0b096..2008d60f 100644 --- a/include/core/metatileparser.h +++ b/include/core/metatileparser.h @@ -10,7 +10,7 @@ class MetatileParser { public: MetatileParser(); - QList *parse(QString filepath, bool *error, bool primaryTileset); + QList parse(QString filepath, bool *error, bool primaryTileset); }; #endif // METATILEPARSER_H diff --git a/include/core/tile.h b/include/core/tile.h index e2b1ec4d..dfcb7117 100644 --- a/include/core/tile.h +++ b/include/core/tile.h @@ -6,8 +6,20 @@ class Tile { public: - Tile() {} - Tile(int tile, bool xflip, bool yflip, int palette); + Tile() : + tile(0), + xflip(false), + yflip(false), + palette(0) + { } + + Tile(int tile, bool xflip, bool yflip, int palette) : + tile(tile), + xflip(xflip), + yflip(yflip), + palette(palette) + { } + public: int tile; bool xflip; diff --git a/include/core/tileset.h b/include/core/tileset.h index c6349cfe..2ffeea85 100644 --- a/include/core/tileset.h +++ b/include/core/tileset.h @@ -9,7 +9,10 @@ class Tileset { public: - Tileset(); + Tileset() = default; + Tileset(const Tileset &other) = default; + Tileset &operator=(const Tileset &other) = default; + public: QString name; QString is_compressed; @@ -24,14 +27,12 @@ public: QString metatile_attrs_path; QString tilesImagePath; QImage tilesImage; - QList palettePaths; + QStringList palettePaths; - QList *tiles = nullptr; - QList *metatiles = nullptr; - QList> *palettes = nullptr; - QList> *palettePreviews = nullptr; - - Tileset* copy(); + QList tiles; + QList metatiles; + QList> palettes; + QList> palettePreviews; static Tileset* getBlockTileset(int, Tileset*, Tileset*); static Metatile* getMetatile(int, Tileset*, Tileset*); diff --git a/include/mainwindow.h b/include/mainwindow.h index 4d333e5c..63d430a7 100644 --- a/include/mainwindow.h +++ b/include/mainwindow.h @@ -77,8 +77,8 @@ public: Q_INVOKABLE void setPrimaryTilesetPalettes(QList>> palettes); Q_INVOKABLE void setSecondaryTilesetPalette(int paletteIndex, QList> colors); Q_INVOKABLE void setSecondaryTilesetPalettes(QList>> palettes); - QJSValue getTilesetPalette(QList> *palettes, int paletteIndex); - QJSValue getTilesetPalettes(QList> *palettes); + QJSValue getTilesetPalette(const QList> &palettes, int paletteIndex); + QJSValue getTilesetPalettes(const QList> &palettes); Q_INVOKABLE QJSValue getPrimaryTilesetPalette(int paletteIndex); Q_INVOKABLE QJSValue getPrimaryTilesetPalettes(); Q_INVOKABLE QJSValue getSecondaryTilesetPalette(int paletteIndex); diff --git a/src/core/metatileparser.cpp b/src/core/metatileparser.cpp index 2fef6dc0..3bbed668 100644 --- a/src/core/metatileparser.cpp +++ b/src/core/metatileparser.cpp @@ -8,13 +8,13 @@ MetatileParser::MetatileParser() } -QList *MetatileParser::parse(QString filepath, bool *error, bool primaryTileset) +QList MetatileParser::parse(QString filepath, bool *error, bool primaryTileset) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { *error = true; logError(QString("Could not open Advance Map 1.92 Metatile .bvd file '%1': ").arg(filepath) + file.errorString()); - return nullptr; + return { }; } QByteArray in = file.readAll(); @@ -23,7 +23,7 @@ QList *MetatileParser::parse(QString filepath, bool *error, bool prim if (in.length() < 9 || in.length() % 2 != 0) { *error = true; logError(QString("Advance Map 1.92 Metatile .bvd file '%1' is an unexpected size.").arg(filepath)); - return nullptr; + return { }; } int projIdOffset = in.length() - 4; @@ -46,7 +46,7 @@ QList *MetatileParser::parse(QString filepath, bool *error, bool prim } else { *error = true; logError(QString("Detected unsupported game type from .bvd file. Last 4 bytes of file must be 'RSE ' or 'FRLG'.")); - return nullptr; + return { }; } int maxMetatiles = primaryTileset ? Project::getNumMetatilesPrimary() : Project::getNumMetatilesTotal() - Project::getNumMetatilesPrimary(); @@ -57,22 +57,22 @@ QList *MetatileParser::parse(QString filepath, bool *error, bool prim if (numMetatiles > maxMetatiles) { *error = true; logError(QString(".bvd file contains data for %1 metatiles, but the maximum number of metatiles is %2.").arg(numMetatiles).arg(maxMetatiles)); - return nullptr; + return { }; } if (numMetatiles < 1) { *error = true; logError(QString(".bvd file contains no data for metatiles.")); - return nullptr; + return { }; } int expectedFileSize = 4 + (metatileSize * numMetatiles) + (attrSize * numMetatiles) + 4; if (in.length() != expectedFileSize) { *error = true; logError(QString(".bvd file is an unexpected size. Expected %1 bytes, but it has %2 bytes.").arg(expectedFileSize).arg(in.length())); - return nullptr; + return { }; } - QList *metatiles = new QList(); + QList metatiles; for (int i = 0; i < numMetatiles; i++) { Metatile *metatile = new Metatile(); QList tiles; @@ -104,7 +104,7 @@ QList *MetatileParser::parse(QString filepath, bool *error, bool prim metatile->terrainType = 0; } metatile->tiles = tiles; - metatiles->append(metatile); + metatiles.append(metatile); } return metatiles; diff --git a/src/core/tile.cpp b/src/core/tile.cpp deleted file mode 100644 index 1077f98f..00000000 --- a/src/core/tile.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "tile.h" - -Tile::Tile(int tile, bool xflip, bool yflip, int palette) -{ - this->tile = tile; - this->xflip = xflip; - this->yflip = yflip; - this->palette = palette; -} diff --git a/src/core/tileset.cpp b/src/core/tileset.cpp index 03b0fb7c..f710f165 100644 --- a/src/core/tileset.cpp +++ b/src/core/tileset.cpp @@ -7,55 +7,6 @@ #include #include -Tileset::Tileset() -{ - -} - -Tileset* Tileset::copy() { - Tileset *copy = new Tileset; - copy->name = this->name; - copy->is_compressed = this->is_compressed; - copy->is_secondary = this->is_secondary; - copy->padding = this->padding; - copy->tiles_label = this->tiles_label; - copy->palettes_label = this->palettes_label; - copy->metatiles_label = this->metatiles_label; - copy->metatiles_path = this->metatiles_path; - copy->callback_label = this->callback_label; - copy->metatile_attrs_label = this->metatile_attrs_label; - copy->metatile_attrs_path = this->metatile_attrs_path; - copy->tilesImage = this->tilesImage.copy(); - copy->tilesImagePath = this->tilesImagePath; - for (int i = 0; i < this->palettePaths.length(); i++) { - copy->palettePaths.append(this->palettePaths.at(i)); - } - copy->tiles = new QList; - for (QImage tile : *this->tiles) { - copy->tiles->append(tile.copy()); - } - copy->metatiles = new QList; - for (Metatile *metatile : *this->metatiles) { - copy->metatiles->append(new Metatile(*metatile)); - } - copy->palettes = new QList>; - for (QList palette : *this->palettes) { - QList copyPalette; - for (QRgb color : palette) { - copyPalette.append(color); - } - copy->palettes->append(copyPalette); - } - copy->palettePreviews = new QList>; - for (QList palette : *this->palettePreviews) { - QList copyPalette; - for (QRgb color : palette) { - copyPalette.append(color); - } - copy->palettePreviews->append(copyPalette); - } - return copy; -} Tileset* Tileset::getBlockTileset(int metatile_index, Tileset *primaryTileset, Tileset *secondaryTileset) { if (metatile_index < Project::getNumMetatilesPrimary()) { @@ -68,20 +19,20 @@ Tileset* Tileset::getBlockTileset(int metatile_index, Tileset *primaryTileset, T Metatile* Tileset::getMetatile(int index, Tileset *primaryTileset, Tileset *secondaryTileset) { Tileset *tileset = Tileset::getBlockTileset(index, primaryTileset, secondaryTileset); int local_index = Metatile::getBlockIndex(index); - if (!tileset || !tileset->metatiles) { + if (!tileset) { return nullptr; } - return tileset->metatiles->value(local_index, nullptr); + return tileset->metatiles.value(local_index, nullptr); } bool Tileset::metatileIsValid(uint16_t metatileId, Tileset *primaryTileset, Tileset *secondaryTileset) { if (metatileId >= Project::getNumMetatilesTotal()) return false; - if (metatileId < Project::getNumMetatilesPrimary() && metatileId >= primaryTileset->metatiles->length()) + if (metatileId < Project::getNumMetatilesPrimary() && metatileId >= primaryTileset->metatiles.length()) return false; - if (metatileId >= Project::getNumMetatilesPrimary() + secondaryTileset->metatiles->length()) + if (metatileId >= Project::getNumMetatilesPrimary() + secondaryTileset->metatiles.length()) return false; return true; @@ -91,11 +42,11 @@ QList> Tileset::getBlockPalettes(Tileset *primaryTileset, Tileset *s QList> palettes; auto primaryPalettes = useTruePalettes ? primaryTileset->palettes : primaryTileset->palettePreviews; for (int i = 0; i < Project::getNumPalettesPrimary(); i++) { - palettes.append(primaryPalettes->at(i)); + palettes.append(primaryPalettes.at(i)); } auto secondaryPalettes = useTruePalettes ? secondaryTileset->palettes : secondaryTileset->palettePreviews; for (int i = Project::getNumPalettesPrimary(); i < Project::getNumPalettesTotal(); i++) { - palettes.append(secondaryPalettes->at(i)); + palettes.append(secondaryPalettes.at(i)); } return palettes; } @@ -106,8 +57,8 @@ QList Tileset::getPalette(int paletteId, Tileset *primaryTileset, Tileset ? primaryTileset : secondaryTileset; auto palettes = useTruePalettes ? tileset->palettes : tileset->palettePreviews; - for (int i = 0; i < palettes->at(paletteId).length(); i++) { - paletteTable.append(palettes->at(paletteId).at(i)); + for (int i = 0; i < palettes.at(paletteId).length(); i++) { + paletteTable.append(palettes.at(paletteId).at(i)); } return paletteTable; } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 5d1740fc..4d3d5757 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1212,22 +1212,18 @@ void MainWindow::on_actionNew_Tileset_triggered() { newSet->metatile_attrs_path = fullDirectoryPath + "/metatile_attributes.bin"; newSet->is_secondary = createTilesetDialog->isSecondary ? "TRUE" : "FALSE"; int numMetaTiles = createTilesetDialog->isSecondary ? (Project::getNumTilesTotal() - Project::getNumTilesPrimary()) : Project::getNumTilesPrimary(); - QImage *tilesImage = new QImage(":/images/blank_tileset.png"); - editor->project->loadTilesetTiles(newSet, *tilesImage); - newSet->metatiles = new QList(); + QImage tilesImage(":/images/blank_tileset.png"); + editor->project->loadTilesetTiles(newSet, tilesImage); for(int i = 0; i < numMetaTiles; ++i) { int tilesPerMetatile = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8; Metatile *mt = new Metatile(); for(int j = 0; j < tilesPerMetatile; ++j){ - Tile tile; + Tile tile(0, false, false, 0); //Create a checkerboard-style dummy tileset if(((i / 8) % 2) == 0) tile.tile = ((i % 2) == 0) ? 1 : 2; else tile.tile = ((i % 2) == 1) ? 1 : 2; - tile.xflip = false; - tile.yflip = false; - tile.palette = 0; mt->tiles.append(tile); } mt->behavior = 0; @@ -1235,23 +1231,20 @@ void MainWindow::on_actionNew_Tileset_triggered() { mt->encounterType = 0; mt->terrainType = 0; - newSet->metatiles->append(mt); + newSet->metatiles.append(mt); } - newSet->palettes = new QList>(); - newSet->palettePreviews = new QList>(); - newSet->palettePaths.clear(); for(int i = 0; i < 16; ++i) { - QList *currentPal = new QList(); + QList currentPal; for(int i = 0; i < 16;++i) { - currentPal->append(qRgb(0,0,0)); + currentPal.append(qRgb(0,0,0)); } - newSet->palettes->append(*currentPal); - newSet->palettePreviews->append(*currentPal); + newSet->palettes.append(currentPal); + newSet->palettePreviews.append(currentPal); QString fileName = QString("%1.pal").arg(i, 2, 10, QLatin1Char('0')); newSet->palettePaths.append(fullDirectoryPath+"/palettes/" + fileName); } - (*newSet->palettes)[0][1] = qRgb(255,0,255); - (*newSet->palettePreviews)[0][1] = qRgb(255,0,255); + newSet->palettes[0][1] = qRgb(255,0,255); + newSet->palettePreviews[0][1] = qRgb(255,0,255); newSet->is_compressed = "TRUE"; newSet->padding = "0"; editor->project->saveTilesetTilesImage(newSet); diff --git a/src/mainwindow_scriptapi.cpp b/src/mainwindow_scriptapi.cpp index 494cb779..7a425e07 100644 --- a/src/mainwindow_scriptapi.cpp +++ b/src/mainwindow_scriptapi.cpp @@ -260,7 +260,7 @@ void MainWindow::refreshAfterPaletteChange(Tileset *tileset) { void MainWindow::setTilesetPalette(Tileset *tileset, int paletteIndex, QList> colors) { if (!this->editor || !this->editor->map || !this->editor->map->layout) return; - if (paletteIndex >= tileset->palettes->size()) + if (paletteIndex >= tileset->palettes.size()) return; if (colors.size() != 16) return; @@ -268,8 +268,8 @@ void MainWindow::setTilesetPalette(Tileset *tileset, int paletteIndex, QListpalettes)[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); - (*tileset->palettePreviews)[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); + tileset->palettes[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); + tileset->palettePreviews[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); } } @@ -305,22 +305,22 @@ void MainWindow::setSecondaryTilesetPalettes(QList>> palettes) this->refreshAfterPaletteChange(this->editor->map->layout->tileset_secondary); } -QJSValue MainWindow::getTilesetPalette(QList> *palettes, int paletteIndex) { - if (paletteIndex >= palettes->size()) +QJSValue MainWindow::getTilesetPalette(const QList> &palettes, int paletteIndex) { + if (paletteIndex >= palettes.size()) return QJSValue(); QList> palette; - for (auto color : palettes->value(paletteIndex)) { + for (auto color : palettes.value(paletteIndex)) { palette.append(QList({qRed(color), qGreen(color), qBlue(color)})); } return Scripting::getEngine()->toScriptValue(palette); } -QJSValue MainWindow::getTilesetPalettes(QList> *palettes) { +QJSValue MainWindow::getTilesetPalettes(const QList> &palettes) { QList>> outPalettes; - for (int i = 0; i < palettes->size(); i++) { + for (int i = 0; i < palettes.size(); i++) { QList> colors; - for (auto color : palettes->value(i)) { + for (auto color : palettes.value(i)) { colors.append(QList({qRed(color), qGreen(color), qBlue(color)})); } outPalettes.append(colors); @@ -363,7 +363,7 @@ void MainWindow::refreshAfterPalettePreviewChange() { void MainWindow::setTilesetPalettePreview(Tileset *tileset, int paletteIndex, QList> colors) { if (!this->editor || !this->editor->map || !this->editor->map->layout) return; - if (paletteIndex >= tileset->palettePreviews->size()) + if (paletteIndex >= tileset->palettePreviews.size()) return; if (colors.size() != 16) return; @@ -371,8 +371,7 @@ void MainWindow::setTilesetPalettePreview(Tileset *tileset, int paletteIndex, QL for (int i = 0; i < 16; i++) { if (colors[i].size() != 3) continue; - auto palettes = tileset->palettePreviews; - (*palettes)[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); + tileset->palettePreviews[paletteIndex][i] = qRgb(colors[i][0], colors[i][1], colors[i][2]); } } diff --git a/src/project.cpp b/src/project.cpp index 710e4edc..021f3d49 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -995,16 +995,16 @@ void Project::saveTilesetMetatileLabels(Tileset *primaryTileset, Tileset *second } // Add the new labels. - for (int i = 0; i < primaryTileset->metatiles->size(); i++) { - Metatile *metatile = primaryTileset->metatiles->at(i); + for (int i = 0; i < primaryTileset->metatiles.size(); i++) { + Metatile *metatile = primaryTileset->metatiles.at(i); if (metatile->label.size() != 0) { QString defineName = QString("%1%2").arg(primaryPrefix, metatile->label); defines.insert(defineName, i); definesFileModified = true; } } - for (int i = 0; i < secondaryTileset->metatiles->size(); i++) { - Metatile *metatile = secondaryTileset->metatiles->at(i); + for (int i = 0; i < secondaryTileset->metatiles.size(); i++) { + Metatile *metatile = secondaryTileset->metatiles.at(i); if (metatile->label.size() != 0) { QString defineName = QString("%1%2").arg(secondaryPrefix, metatile->label); defines.insert(defineName, i + Project::num_tiles_primary); @@ -1061,7 +1061,7 @@ void Project::saveTilesetMetatileAttributes(Tileset *tileset) { QByteArray data; if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) { - for (Metatile *metatile : *tileset->metatiles) { + for (Metatile *metatile : tileset->metatiles) { data.append(static_cast(metatile->behavior)); data.append(static_cast(metatile->behavior >> 8) | static_cast(metatile->terrainType << 1)); @@ -1070,7 +1070,7 @@ void Project::saveTilesetMetatileAttributes(Tileset *tileset) { static_cast(metatile->layerType << 5)); } } else { - for (Metatile *metatile : *tileset->metatiles) { + for (Metatile *metatile : tileset->metatiles) { data.append(static_cast(metatile->behavior)); data.append(static_cast((metatile->layerType << 4) & 0xF0)); } @@ -1085,7 +1085,7 @@ void Project::saveTilesetMetatiles(Tileset *tileset) { QFile metatiles_file(tileset->metatiles_path); if (metatiles_file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QByteArray data; - for (Metatile *metatile : *tileset->metatiles) { + for (Metatile *metatile : tileset->metatiles) { int numTiles = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8; for (int i = 0; i < numTiles; i++) { Tile tile = metatile->tiles.at(i); @@ -1099,7 +1099,7 @@ void Project::saveTilesetMetatiles(Tileset *tileset) { } metatiles_file.write(data); } else { - tileset->metatiles = new QList; + tileset->metatiles.clear(); logError(QString("Could not open tileset metatiles file '%1'").arg(tileset->metatiles_path)); } } @@ -1112,7 +1112,7 @@ void Project::saveTilesetPalettes(Tileset *tileset) { PaletteUtil paletteParser; for (int i = 0; i < Project::getNumPalettesTotal(); i++) { QString filepath = tileset->palettePaths.at(i); - paletteParser.writeJASC(filepath, tileset->palettes->at(i).toVector(), 0, 16); + paletteParser.writeJASC(filepath, tileset->palettes.at(i).toVector(), 0, 16); } } @@ -1552,8 +1552,8 @@ void Project::loadTilesetAssets(Tileset* tileset) { this->loadTilesetMetatileLabels(tileset); // palettes - QList> *palettes = new QList>; - QList> *palettePreviews = new QList>; + QList> palettes; + QList> palettePreviews; for (int i = 0; i < tileset->palettePaths.length(); i++) { QList palette; QString path = tileset->palettePaths.value(i); @@ -1587,21 +1587,21 @@ void Project::loadTilesetAssets(Tileset* tileset) { logError(QString("Could not open tileset palette path '%1'").arg(path)); } - palettes->append(palette); - palettePreviews->append(palette); + palettes.append(palette); + palettePreviews.append(palette); } tileset->palettes = palettes; tileset->palettePreviews = palettePreviews; } void Project::loadTilesetTiles(Tileset *tileset, QImage image) { - QList *tiles = new QList; + QList tiles; int w = 8; int h = 8; for (int y = 0; y < image.height(); y += h) for (int x = 0; x < image.width(); x += w) { QImage tile = image.copy(x, y, w, h); - tiles->append(tile); + tiles.append(tile); } tileset->tilesImage = image; tileset->tiles = tiles; @@ -1614,7 +1614,7 @@ void Project::loadTilesetMetatiles(Tileset* tileset) { int metatile_data_length = projectConfig.getTripleLayerMetatilesEnabled() ? 24 : 16; int num_metatiles = data.length() / metatile_data_length; int num_layers = projectConfig.getTripleLayerMetatilesEnabled() ? 3 : 2; - QList *metatiles = new QList; + QList metatiles; for (int i = 0; i < num_metatiles; i++) { Metatile *metatile = new Metatile; int index = i * (2 * 4 * num_layers); @@ -1628,18 +1628,18 @@ void Project::loadTilesetMetatiles(Tileset* tileset) { tile.palette = (word >> 12) & 0xf; metatile->tiles.append(tile); } - metatiles->append(metatile); + metatiles.append(metatile); } tileset->metatiles = metatiles; } else { - tileset->metatiles = new QList; + tileset->metatiles.clear(); logError(QString("Could not open tileset metatiles file '%1'").arg(tileset->metatiles_path)); } QFile attrs_file(tileset->metatile_attrs_path); if (attrs_file.open(QIODevice::ReadOnly)) { QByteArray data = attrs_file.readAll(); - int num_metatiles = tileset->metatiles->count(); + int num_metatiles = tileset->metatiles.count(); if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) { int num_metatileAttrs = data.length() / 4; @@ -1654,10 +1654,10 @@ void Project::loadTilesetMetatiles(Tileset* tileset) { (static_cast(data.at(i * 4 + 2)) << 16) | (static_cast(data.at(i * 4 + 1)) << 8) | (static_cast(data.at(i * 4 + 0))); - tileset->metatiles->at(i)->behavior = value & 0x1FF; - tileset->metatiles->at(i)->terrainType = (value & 0x3E00) >> 9; - tileset->metatiles->at(i)->encounterType = (value & 0x7000000) >> 24; - tileset->metatiles->at(i)->layerType = (value & 0x60000000) >> 29; + tileset->metatiles.at(i)->behavior = value & 0x1FF; + tileset->metatiles.at(i)->terrainType = (value & 0x3E00) >> 9; + tileset->metatiles.at(i)->encounterType = (value & 0x7000000) >> 24; + tileset->metatiles.at(i)->layerType = (value & 0x60000000) >> 29; if (value & ~(0x67003FFF)) unusedAttribute = true; } @@ -1672,10 +1672,10 @@ void Project::loadTilesetMetatiles(Tileset* tileset) { } for (int i = 0; i < num_metatileAttrs; i++) { int value = (static_cast(data.at(i * 2 + 1)) << 8) | static_cast(data.at(i * 2)); - tileset->metatiles->at(i)->behavior = value & 0xFF; - tileset->metatiles->at(i)->layerType = (value & 0xF000) >> 12; - tileset->metatiles->at(i)->encounterType = 0; - tileset->metatiles->at(i)->terrainType = 0; + tileset->metatiles.at(i)->behavior = value & 0xFF; + tileset->metatiles.at(i)->layerType = (value & 0xF000) >> 12; + tileset->metatiles.at(i)->encounterType = 0; + tileset->metatiles.at(i)->terrainType = 0; } } } else { @@ -1734,7 +1734,7 @@ Tileset* Project::getTileset(QString label, bool forceLoad) { } if (existingTileset && !forceLoad) { - return tilesetCache->value(label); + return existingTileset; } else { Tileset *tileset = loadTileset(label, existingTileset); return tileset; diff --git a/src/ui/imageproviders.cpp b/src/ui/imageproviders.cpp index 4c37206e..44a7e4f2 100644 --- a/src/ui/imageproviders.cpp +++ b/src/ui/imageproviders.cpp @@ -97,10 +97,10 @@ QImage getMetatileImage( QImage getTileImage(uint16_t tile, Tileset *primaryTileset, Tileset *secondaryTileset) { Tileset *tileset = Tileset::getBlockTileset(tile, primaryTileset, secondaryTileset); int local_index = Metatile::getBlockIndex(tile); - if (!tileset || !tileset->tiles) { + if (!tileset) { return QImage(); } - return tileset->tiles->value(local_index, QImage()); + return tileset->tiles.value(local_index, QImage()); } QImage getColoredTileImage(uint16_t tile, Tileset *primaryTileset, Tileset *secondaryTileset, QList palette) { diff --git a/src/ui/metatileselector.cpp b/src/ui/metatileselector.cpp index c360da5f..80f05c59 100644 --- a/src/ui/metatileselector.cpp +++ b/src/ui/metatileselector.cpp @@ -12,13 +12,12 @@ QPoint MetatileSelector::getSelectionDimensions() { } void MetatileSelector::draw() { - if (!this->primaryTileset || !this->primaryTileset->metatiles - || !this->secondaryTileset || !this->secondaryTileset->metatiles) { + if (!this->primaryTileset || !this->secondaryTileset) { this->setPixmap(QPixmap()); } - int primaryLength = this->primaryTileset->metatiles->length(); - int length_ = primaryLength + this->secondaryTileset->metatiles->length(); + int primaryLength = this->primaryTileset->metatiles.length(); + int length_ = primaryLength + this->secondaryTileset->metatiles.length(); int height_ = length_ / this->numMetatilesWide; if (length_ % this->numMetatilesWide != 0) { height_++; @@ -69,7 +68,7 @@ void MetatileSelector::setTilesets(Tileset *primaryTileset, Tileset *secondaryTi if (this->externalSelection) { this->select(0); } else { - this->select(Project::getNumMetatilesPrimary() + this->secondaryTileset->metatiles->length() - 1); + this->select(Project::getNumMetatilesPrimary() + this->secondaryTileset->metatiles.length() - 1); } } else if (this->externalSelection) { emit selectedMetatilesChanged(); @@ -181,10 +180,10 @@ bool MetatileSelector::selectionIsValid() { uint16_t MetatileSelector::getMetatileId(int x, int y) { int index = y * this->numMetatilesWide + x; - if (index < this->primaryTileset->metatiles->length()) { + if (index < this->primaryTileset->metatiles.length()) { return static_cast(index); } else { - return static_cast(Project::getNumMetatilesPrimary() + index - this->primaryTileset->metatiles->length()); + return static_cast(Project::getNumMetatilesPrimary() + index - this->primaryTileset->metatiles.length()); } } @@ -197,7 +196,7 @@ QPoint MetatileSelector::getMetatileIdCoords(uint16_t metatileId) { int index = metatileId < Project::getNumMetatilesPrimary() ? metatileId - : metatileId - Project::getNumMetatilesPrimary() + this->primaryTileset->metatiles->length(); + : metatileId - Project::getNumMetatilesPrimary() + this->primaryTileset->metatiles.length(); return QPoint(index % this->numMetatilesWide, index / this->numMetatilesWide); } diff --git a/src/ui/paletteeditor.cpp b/src/ui/paletteeditor.cpp index 0e1366e6..f376dc3b 100644 --- a/src/ui/paletteeditor.cpp +++ b/src/ui/paletteeditor.cpp @@ -151,9 +151,9 @@ void PaletteEditor::refreshColorSliders() { for (int i = 0; i < 16; i++) { QRgb color; if (paletteNum < Project::getNumPalettesPrimary()) { - color = this->primaryTileset->palettes->at(paletteNum).at(i); + color = this->primaryTileset->palettes.at(paletteNum).at(i); } else { - color = this->secondaryTileset->palettes->at(paletteNum).at(i); + color = this->secondaryTileset->palettes.at(paletteNum).at(i); } this->sliders[i][0]->setValue(qRed(color) / 8); @@ -204,8 +204,8 @@ void PaletteEditor::setColor(int colorIndex) { Tileset *tileset = paletteNum < Project::getNumPalettesPrimary() ? this->primaryTileset : this->secondaryTileset; - (*tileset->palettes)[paletteNum][colorIndex] = qRgb(red, green, blue); - (*tileset->palettePreviews)[paletteNum][colorIndex] = qRgb(red, green, blue); + tileset->palettes[paletteNum][colorIndex] = qRgb(red, green, blue); + tileset->palettePreviews[paletteNum][colorIndex] = qRgb(red, green, blue); this->refreshColor(colorIndex); this->commitEditHistory(paletteNum); emit this->changedPaletteColor(); @@ -255,11 +255,11 @@ void PaletteEditor::setColorsFromHistory(PaletteHistoryItem *history, int palett for (int i = 0; i < 16; i++) { if (paletteId < Project::getNumPalettesPrimary()) { - (*this->primaryTileset->palettes)[paletteId][i] = history->colors.at(i); - (*this->primaryTileset->palettePreviews)[paletteId][i] = history->colors.at(i); + this->primaryTileset->palettes[paletteId][i] = history->colors.at(i); + this->primaryTileset->palettePreviews[paletteId][i] = history->colors.at(i); } else { - (*this->secondaryTileset->palettes)[paletteId][i] = history->colors.at(i); - (*this->secondaryTileset->palettePreviews)[paletteId][i] = history->colors.at(i); + this->secondaryTileset->palettes[paletteId][i] = history->colors.at(i); + this->secondaryTileset->palettePreviews[paletteId][i] = history->colors.at(i); } } @@ -307,11 +307,11 @@ void PaletteEditor::on_actionImport_Palette_triggered() int paletteId = this->ui->spinBox_PaletteId->value(); for (int i = 0; i < 16; i++) { if (paletteId < Project::getNumPalettesPrimary()) { - (*this->primaryTileset->palettes)[paletteId][i] = palette.at(i); - (*this->primaryTileset->palettePreviews)[paletteId][i] = palette.at(i); + this->primaryTileset->palettes[paletteId][i] = palette.at(i); + this->primaryTileset->palettePreviews[paletteId][i] = palette.at(i); } else { - (*this->secondaryTileset->palettes)[paletteId][i] = palette.at(i); - (*this->secondaryTileset->palettePreviews)[paletteId][i] = palette.at(i); + this->secondaryTileset->palettes[paletteId][i] = palette.at(i); + this->secondaryTileset->palettePreviews[paletteId][i] = palette.at(i); } } diff --git a/src/ui/tileseteditor.cpp b/src/ui/tileseteditor.cpp index 928087b5..4fd61a83 100644 --- a/src/ui/tileseteditor.cpp +++ b/src/ui/tileseteditor.cpp @@ -81,8 +81,8 @@ void TilesetEditor::setTilesets(QString primaryTilesetLabel, QString secondaryTi Tileset *secondaryTileset = project->getTileset(secondaryTilesetLabel); if (this->primaryTileset) delete this->primaryTileset; if (this->secondaryTileset) delete this->secondaryTileset; - this->primaryTileset = primaryTileset->copy(); - this->secondaryTileset = secondaryTileset->copy(); + this->primaryTileset = new Tileset(*primaryTileset); + this->secondaryTileset = new Tileset(*secondaryTileset); if (paletteEditor) paletteEditor->setTilesets(this->primaryTileset, this->secondaryTileset); } @@ -716,8 +716,8 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() secondarySpinBox->setMinimum(1); primarySpinBox->setMaximum(Project::getNumMetatilesPrimary()); secondarySpinBox->setMaximum(Project::getNumMetatilesTotal() - Project::getNumMetatilesPrimary()); - primarySpinBox->setValue(this->primaryTileset->metatiles->length()); - secondarySpinBox->setValue(this->secondaryTileset->metatiles->length()); + primarySpinBox->setValue(this->primaryTileset->metatiles.length()); + secondarySpinBox->setValue(this->secondaryTileset->metatiles.length()); form.addRow(new QLabel("Primary Tileset"), primarySpinBox); form.addRow(new QLabel("Secondary Tileset"), secondarySpinBox); @@ -730,16 +730,11 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() int numPrimaryMetatiles = primarySpinBox->value(); int numSecondaryMetatiles = secondarySpinBox->value(); int numTiles = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8; - while (this->primaryTileset->metatiles->length() > numPrimaryMetatiles) { - Metatile *metatile = this->primaryTileset->metatiles->takeLast(); - delete metatile; + while (this->primaryTileset->metatiles.length() > numPrimaryMetatiles) { + delete this->primaryTileset->metatiles.takeLast(); } - while (this->primaryTileset->metatiles->length() < numPrimaryMetatiles) { - Tile tile; - tile.palette = 0; - tile.tile = 0; - tile.xflip = false; - tile.yflip = false; + while (this->primaryTileset->metatiles.length() < numPrimaryMetatiles) { + Tile tile(0, false, false, 0); Metatile *metatile = new Metatile; metatile->behavior = 0; metatile->layerType = 0; @@ -748,18 +743,13 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() for (int i = 0; i < numTiles; i++) { metatile->tiles.append(tile); } - this->primaryTileset->metatiles->append(metatile); + this->primaryTileset->metatiles.append(metatile); } - while (this->secondaryTileset->metatiles->length() > numSecondaryMetatiles) { - Metatile *metatile = this->secondaryTileset->metatiles->takeLast(); - delete metatile; + while (this->secondaryTileset->metatiles.length() > numSecondaryMetatiles) { + delete this->secondaryTileset->metatiles.takeLast(); } - while (this->secondaryTileset->metatiles->length() < numSecondaryMetatiles) { - Tile tile; - tile.palette = 0; - tile.tile = 0; - tile.xflip = 0; - tile.yflip = 0; + while (this->secondaryTileset->metatiles.length() < numSecondaryMetatiles) { + Tile tile(0, false, false, 0); Metatile *metatile = new Metatile; metatile->behavior = 0; metatile->layerType = 0; @@ -768,7 +758,7 @@ void TilesetEditor::on_actionChange_Metatiles_Count_triggered() for (int i = 0; i < numTiles; i++) { metatile->tiles.append(tile); } - this->secondaryTileset->metatiles->append(metatile); + this->secondaryTileset->metatiles.append(metatile); } this->metatileSelector->updateSelectedMetatile(); @@ -891,7 +881,7 @@ void TilesetEditor::importTilesetMetatiles(Tileset *tileset, bool primary) MetatileParser parser; bool error = false; - QList *metatiles = parser.parse(filepath, &error, primary); + QList metatiles = parser.parse(filepath, &error, primary); if (error) { QMessageBox msgBox(this); msgBox.setText("Failed to import metatiles from Advance Map 1.92 .bvd file."); @@ -906,14 +896,14 @@ void TilesetEditor::importTilesetMetatiles(Tileset *tileset, bool primary) // TODO: This is crude because it makes a history entry for every newly-imported metatile. // Revisit this when tiles and num metatiles are added to tileset editory history. int metatileIdBase = primary ? 0 : Project::getNumMetatilesPrimary(); - for (int i = 0; i < metatiles->length(); i++) { - if (i >= tileset->metatiles->length()) { + for (int i = 0; i < metatiles.length(); i++) { + if (i >= tileset->metatiles.length()) { break; } - Metatile *prevMetatile = new Metatile(*tileset->metatiles->at(i)); + Metatile *prevMetatile = new Metatile(*tileset->metatiles.at(i)); MetatileHistoryItem *commit = new MetatileHistoryItem(static_cast(metatileIdBase + i), - prevMetatile, new Metatile(*metatiles->at(i))); + prevMetatile, new Metatile(*metatiles.at(i))); metatileHistory.push(commit); } diff --git a/src/ui/tileseteditormetatileselector.cpp b/src/ui/tileseteditormetatileselector.cpp index dddfdbbd..c7df404b 100644 --- a/src/ui/tileseteditormetatileselector.cpp +++ b/src/ui/tileseteditormetatileselector.cpp @@ -4,13 +4,12 @@ #include void TilesetEditorMetatileSelector::draw() { - if (!this->primaryTileset || !this->primaryTileset->metatiles - || !this->secondaryTileset || !this->secondaryTileset->metatiles) { + if (!this->primaryTileset || !this->secondaryTileset) { this->setPixmap(QPixmap()); } - int primaryLength = this->primaryTileset->metatiles->length(); - int length_ = primaryLength + this->secondaryTileset->metatiles->length(); + int primaryLength = this->primaryTileset->metatiles.length(); + int length_ = primaryLength + this->secondaryTileset->metatiles.length(); int height_ = length_ / this->numMetatilesWide; if (length_ % this->numMetatilesWide != 0) { height_++; @@ -63,7 +62,7 @@ void TilesetEditorMetatileSelector::updateSelectedMetatile() { if (Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset)) this->selectedMetatile = metatileId; else - this->selectedMetatile = Project::getNumMetatilesPrimary() + this->secondaryTileset->metatiles->length() - 1; + this->selectedMetatile = Project::getNumMetatilesPrimary() + this->secondaryTileset->metatiles.length() - 1; emit selectedMetatileChanged(this->selectedMetatile); } @@ -73,10 +72,10 @@ uint16_t TilesetEditorMetatileSelector::getSelectedMetatile() { uint16_t TilesetEditorMetatileSelector::getMetatileId(int x, int y) { int index = y * this->numMetatilesWide + x; - if (index < this->primaryTileset->metatiles->length()) { + if (index < this->primaryTileset->metatiles.length()) { return static_cast(index); } else { - return static_cast(Project::getNumMetatilesPrimary() + index - this->primaryTileset->metatiles->length()); + return static_cast(Project::getNumMetatilesPrimary() + index - this->primaryTileset->metatiles.length()); } } @@ -119,10 +118,10 @@ QPoint TilesetEditorMetatileSelector::getMetatileIdCoords(uint16_t metatileId) { { // Invalid metatile id. return QPoint(0, 0); - } + } int index = metatileId < Project::getNumMetatilesPrimary() ? metatileId - : metatileId - Project::getNumMetatilesPrimary() + this->primaryTileset->metatiles->length(); + : metatileId - Project::getNumMetatilesPrimary() + this->primaryTileset->metatiles.length(); return QPoint(index % this->numMetatilesWide, index / this->numMetatilesWide); } diff --git a/src/ui/tileseteditortileselector.cpp b/src/ui/tileseteditortileselector.cpp index 1b68466a..54a2da0e 100644 --- a/src/ui/tileseteditortileselector.cpp +++ b/src/ui/tileseteditortileselector.cpp @@ -13,14 +13,13 @@ QPoint TilesetEditorTileSelector::getSelectionDimensions() { } void TilesetEditorTileSelector::draw() { - if (!this->primaryTileset || !this->primaryTileset->tiles - || !this->secondaryTileset || !this->secondaryTileset->tiles) { + if (!this->primaryTileset || !this->secondaryTileset) { this->setPixmap(QPixmap()); } int totalTiles = Project::getNumTilesTotal(); - int primaryLength = this->primaryTileset->tiles->length(); - int secondaryLength = this->secondaryTileset->tiles->length(); + int primaryLength = this->primaryTileset->tiles.length(); + int secondaryLength = this->secondaryTileset->tiles.length(); int height = totalTiles / this->numTilesWide; QList palette = Tileset::getPalette(this->paletteId, this->primaryTileset, this->secondaryTileset, true); QImage image(this->numTilesWide * 16, height * 16, QImage::Format_RGBA8888); @@ -218,12 +217,11 @@ QPoint TilesetEditorTileSelector::getTileCoordsOnWidget(uint16_t tile) { } QImage TilesetEditorTileSelector::buildPrimaryTilesIndexedImage() { - if (!this->primaryTileset || !this->primaryTileset->tiles - || !this->secondaryTileset || !this->secondaryTileset->tiles) { + if (!this->primaryTileset || !this->secondaryTileset) { return QImage(); } - int primaryLength = this->primaryTileset->tiles->length(); + int primaryLength = this->primaryTileset->tiles.length(); int height = qCeil(primaryLength / static_cast(this->numTilesWide)); QImage image(this->numTilesWide * 8, height * 8, QImage::Format_RGBA8888); @@ -254,12 +252,11 @@ QImage TilesetEditorTileSelector::buildPrimaryTilesIndexedImage() { } QImage TilesetEditorTileSelector::buildSecondaryTilesIndexedImage() { - if (!this->primaryTileset || !this->primaryTileset->tiles - || !this->secondaryTileset || !this->secondaryTileset->tiles) { + if (!this->primaryTileset || !this->secondaryTileset) { return QImage(); } - int secondaryLength = this->secondaryTileset->tiles->length(); + int secondaryLength = this->secondaryTileset->tiles.length(); int height = qCeil(secondaryLength / static_cast(this->numTilesWide)); QImage image(this->numTilesWide * 8, height * 8, QImage::Format_RGBA8888); From a9b7fd6b1578db5b5b32001c4f83d598fa801287 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 22:25:50 -0500 Subject: [PATCH 23/46] Correct build error --- porymap.pro | 1 - 1 file changed, 1 deletion(-) diff --git a/porymap.pro b/porymap.pro index 1c3b2fac..91763837 100644 --- a/porymap.pro +++ b/porymap.pro @@ -25,7 +25,6 @@ SOURCES += src/core/block.cpp \ src/core/metatileparser.cpp \ src/core/paletteutil.cpp \ src/core/parseutil.cpp \ - src/core/tile.cpp \ src/core/tileset.cpp \ src/core/regionmap.cpp \ src/core/wildmoninfo.cpp \ From 820b514f26ae9c089b1b84d6ff4a4e7f6e2e9cc6 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 04:21:41 -0500 Subject: [PATCH 24/46] Change many pointer members in Project to values --- include/core/event.h | 2 +- include/project.h | 16 +++---- src/core/event.cpp | 4 +- src/core/regionmap.cpp | 6 +-- src/editor.cpp | 14 +++--- src/mainwindow.cpp | 24 +++++----- src/project.cpp | 81 +++++++++++++++------------------- src/ui/draggablepixmapitem.cpp | 2 +- src/ui/mapimageexporter.cpp | 2 +- src/ui/newmappopup.cpp | 10 ++--- src/ui/regionmapeditor.cpp | 8 ++-- 11 files changed, 79 insertions(+), 90 deletions(-) diff --git a/include/core/event.h b/include/core/event.h index 4a6e7c4a..6ee59ac5 100644 --- a/include/core/event.h +++ b/include/core/event.h @@ -77,7 +77,7 @@ public: static Event* createNewSecretBaseEvent(Project*); OrderedJson::object buildObjectEventJSON(); - OrderedJson::object buildWarpEventJSON(QMap*); + OrderedJson::object buildWarpEventJSON(const QMap &); OrderedJson::object buildTriggerEventJSON(); OrderedJson::object buildWeatherTriggerEventJSON(); OrderedJson::object buildSignEventJSON(); diff --git a/include/project.h b/include/project.h index 988a8316..41dfb758 100644 --- a/include/project.h +++ b/include/project.h @@ -33,20 +33,20 @@ public: public: QString root; - QStringList *groupNames = nullptr; - QMap *mapGroups; + QStringList groupNames; + QMap mapGroups; QList groupedMapNames; - QStringList *mapNames = nullptr; + QStringList mapNames; QMap miscConstants; QList healLocations; - QMap* mapConstantsToMapNames; - QMap* mapNamesToMapConstants; - QList mapLayoutsTable; - QList mapLayoutsTableMaster; + QMap mapConstantsToMapNames; + QMap mapNamesToMapConstants; + QStringList mapLayoutsTable; + QStringList mapLayoutsTableMaster; QString layoutsLabel; QMap mapLayouts; QMap mapLayoutsMaster; - QMap *mapSecToMapHoverName; + QMap mapSecToMapHoverName; QMap mapSectionNameToValue; QMap mapSectionValueToName; QStringList *itemNames = nullptr; diff --git a/src/core/event.cpp b/src/core/event.cpp index 5b10d20f..811f9328 100644 --- a/src/core/event.cpp +++ b/src/core/event.cpp @@ -321,13 +321,13 @@ OrderedJson::object Event::buildObjectEventJSON() return eventObj; } -OrderedJson::object Event::buildWarpEventJSON(QMap *mapNamesToMapConstants) +OrderedJson::object Event::buildWarpEventJSON(const QMap &mapNamesToMapConstants) { OrderedJson::object warpObj; warpObj["x"] = this->getU16("x"); warpObj["y"] = this->getU16("y"); warpObj["elevation"] = this->getInt("elevation"); - warpObj["dest_map"] = mapNamesToMapConstants->value(this->get("destination_map_name")); + warpObj["dest_map"] = mapNamesToMapConstants.value(this->get("destination_map_name")); warpObj["dest_warp_id"] = this->getInt("destination_warp"); this->addCustomValuesTo(&warpObj); diff --git a/src/core/regionmap.cpp b/src/core/regionmap.cpp index 12dbebf0..c5a1b294 100644 --- a/src/core/regionmap.cpp +++ b/src/core/regionmap.cpp @@ -130,7 +130,7 @@ bool RegionMap::readLayout() { return false; } - QMap *qmap = new QMap; + QMap qmap; bool mapNamesQualified = false, mapEntriesQualified = false; @@ -155,7 +155,7 @@ bool RegionMap::readLayout() { QStringList entry = reAfter.match(line).captured(1).remove(" ").split(","); QString mapsec = reBefore.match(line).captured(1); QString insertion = entry[4].remove("sMapName_"); - qmap->insert(mapsec, sMapNamesMap.value(insertion)); + qmap.insert(mapsec, sMapNamesMap.value(insertion)); mapSecToMapEntry[mapsec] = { // x y width height name entry[0].toInt(), entry[1].toInt(), entry[2].toInt(), entry[3].toInt(), insertion @@ -265,7 +265,7 @@ void RegionMap::saveOptions(int id, QString sec, QString name, int x, int y) { this->map_squares[index].mapsec = sec; if (!name.isEmpty()) { this->map_squares[index].map_name = name; - this->project->mapSecToMapHoverName->insert(sec, name); + this->project->mapSecToMapHoverName.insert(sec, name); QString sName = fixCase(sec); sMapNamesMap.insert(sName, name); if (!mapSecToMapEntry.keys().contains(sec)) { diff --git a/src/editor.cpp b/src/editor.cpp index f855d9f3..c1857d8a 100644 --- a/src/editor.cpp +++ b/src/editor.cpp @@ -726,11 +726,11 @@ void Editor::populateConnectionMapPickers() { ui->comboBox_EmergeMap->blockSignals(true); ui->comboBox_ConnectedMap->clear(); - ui->comboBox_ConnectedMap->addItems(*project->mapNames); + ui->comboBox_ConnectedMap->addItems(project->mapNames); ui->comboBox_DiveMap->clear(); - ui->comboBox_DiveMap->addItems(*project->mapNames); + ui->comboBox_DiveMap->addItems(project->mapNames); ui->comboBox_EmergeMap->clear(); - ui->comboBox_EmergeMap->addItems(*project->mapNames); + ui->comboBox_EmergeMap->addItems(project->mapNames); ui->comboBox_ConnectedMap->blockSignals(false); ui->comboBox_DiveMap->blockSignals(true); @@ -1678,7 +1678,7 @@ void Editor::updateConnectionOffset(int offset) { } void Editor::setConnectionMap(QString mapName) { - if (!mapName.isEmpty() && !project->mapNames->contains(mapName)) { + if (!mapName.isEmpty() && !project->mapNames.contains(mapName)) { logError(QString("Invalid map name '%1' specified for connection.").arg(mapName)); return; } @@ -1714,9 +1714,9 @@ void Editor::addNewConnection() { } // Don't connect the map to itself. - QString defaultMapName = project->mapNames->first(); + QString defaultMapName = project->mapNames.first(); if (defaultMapName == map->name) { - defaultMapName = project->mapNames->value(1); + defaultMapName = project->mapNames.value(1); } MapConnection* newConnection = new MapConnection; @@ -1824,7 +1824,7 @@ void Editor::updateEmergeMap(QString mapName) { } void Editor::updateDiveEmergeMap(QString mapName, QString direction) { - if (!mapName.isEmpty() && !project->mapNamesToMapConstants->contains(mapName)) { + if (!mapName.isEmpty() && !project->mapNamesToMapConstants.contains(mapName)) { logError(QString("Invalid %1 connection map name: '%2'").arg(direction).arg(mapName)); return; } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 508eb085..8a1ae0dd 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -672,7 +672,7 @@ void MainWindow::refreshMapScene() void MainWindow::openWarpMap(QString map_name, QString warp_num) { // Ensure valid destination map name. - if (!editor->project->mapNames->contains(map_name)) { + if (!editor->project->mapNames.contains(map_name)) { logError(QString("Invalid warp destination map name '%1'").arg(map_name)); return; } @@ -946,8 +946,8 @@ void MainWindow::sortMapList() { switch (mapSortOrder) { case MapSortOrder::Group: - for (int i = 0; i < project->groupNames->length(); i++) { - QString group_name = project->groupNames->value(i); + for (int i = 0; i < project->groupNames.length(); i++) { + QString group_name = project->groupNames.value(i); QStandardItem *group = new QStandardItem; group->setText(group_name); group->setIcon(mapFolderIcon); @@ -982,7 +982,7 @@ void MainWindow::sortMapList() { mapGroupItemsList->append(mapsec); mapsecToGroupNum.insert(mapsec_name, i); } - for (int i = 0; i < project->groupNames->length(); i++) { + for (int i = 0; i < project->groupNames.length(); i++) { QStringList names = project->groupedMapNames.value(i); for (int j = 0; j < names.length(); j++) { QString map_name = names.value(j); @@ -1014,7 +1014,7 @@ void MainWindow::sortMapList() { mapGroupItemsList->append(layoutItem); layoutIndices[layoutId] = i; } - for (int i = 0; i < project->groupNames->length(); i++) { + for (int i = 0; i < project->groupNames.length(); i++) { QStringList names = project->groupedMapNames.value(i); for (int j = 0; j < names.length(); j++) { QString map_name = names.value(j); @@ -1828,10 +1828,10 @@ void MainWindow::updateSelectedObjects() { } if (key == "destination_map_name") { - if (!editor->project->mapNames->contains(value)) { + if (!editor->project->mapNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->mapNames); + combo->addItems(editor->project->mapNames); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The destination map name of the warp."); } else if (key == "destination_warp") { @@ -1931,10 +1931,10 @@ void MainWindow::updateSelectedObjects() { } else if (key == "in_connection") { check->setToolTip("Check if object is positioned in the connection to another map."); } else if (key == "respawn_map") { - if (!editor->project->mapNames->contains(value)) { + if (!editor->project->mapNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->mapNames); + combo->addItems(editor->project->mapNames); combo->setToolTip("The map where the player will respawn after whiteout."); } else if (key == "respawn_npc") { spin->setToolTip("event_object ID of the NPC the player interacts with\n" @@ -2482,7 +2482,7 @@ void MainWindow::on_spinBox_ConnectionOffset_valueChanged(int offset) void MainWindow::on_comboBox_ConnectedMap_currentTextChanged(const QString &mapName) { - if (editor->project->mapNames->contains(mapName)) + if (editor->project->mapNames.contains(mapName)) editor->setConnectionMap(mapName); } @@ -2510,13 +2510,13 @@ void MainWindow::on_pushButton_ConfigureEncountersJSON_clicked() { void MainWindow::on_comboBox_DiveMap_currentTextChanged(const QString &mapName) { - if (editor->project->mapNames->contains(mapName)) + if (editor->project->mapNames.contains(mapName)) editor->updateDiveMap(mapName); } void MainWindow::on_comboBox_EmergeMap_currentTextChanged(const QString &mapName) { - if (editor->project->mapNames->contains(mapName)) + if (editor->project->mapNames.contains(mapName)) editor->updateEmergeMap(mapName); } diff --git a/src/project.cpp b/src/project.cpp index dc24259d..07abc4b9 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -38,9 +38,6 @@ int Project::max_object_events = 64; Project::Project(QWidget *parent) : parent(parent) { - groupNames = new QStringList; - mapGroups = new QMap; - mapNames = new QStringList; itemNames = new QStringList; flagNames = new QStringList; varNames = new QStringList; @@ -53,8 +50,6 @@ Project::Project(QWidget *parent) : parent(parent) bgEventFacingDirections = new QStringList; trainerTypes = new QStringList; mapCache = new QMap; - mapConstantsToMapNames = new QMap; - mapNamesToMapConstants = new QMap; tilesetCache = new QMap; initSignals(); @@ -62,9 +57,6 @@ Project::Project(QWidget *parent) : parent(parent) Project::~Project() { - delete this->groupNames; - delete this->mapGroups; - delete this->mapNames; delete this->itemNames; delete this->flagNames; delete this->varNames; @@ -78,9 +70,6 @@ Project::~Project() delete this->trainerTypes; delete this->mapTypes; - delete this->mapConstantsToMapNames; - delete this->mapNamesToMapConstants; - clearMapCache(); delete this->mapCache; clearTilesetCache(); @@ -283,8 +272,8 @@ bool Project::loadMapData(Map* map) { // Ensure the warp destination map constant is valid before adding it to the warps. QString mapConstant = event["dest_map"].toString(); - if (mapConstantsToMapNames->contains(mapConstant)) { - warp->put("destination_map_name", mapConstantsToMapNames->value(mapConstant)); + if (mapConstantsToMapNames.contains(mapConstant)) { + warp->put("destination_map_name", mapConstantsToMapNames.value(mapConstant)); warp->put("event_group_type", "warp_event_group"); map->events["warp_event_group"].append(warp); } else if (mapConstant == NONE_MAP_CONSTANT) { @@ -302,7 +291,7 @@ bool Project::loadMapData(Map* map) { HealLocation loc = *it; //if TRUE map is flyable / has healing location - if (loc.mapName == QString(mapNamesToMapConstants->value(map->name)).remove(0,4)) { + if (loc.mapName == QString(mapNamesToMapConstants.value(map->name)).remove(0,4)) { Event *heal = new Event; heal->put("map_name", map->name); heal->put("x", loc.x); @@ -311,11 +300,11 @@ bool Project::loadMapData(Map* map) { heal->put("id_name", loc.idName); heal->put("index", loc.index); heal->put("elevation", 3); // TODO: change this? - heal->put("destination_map_name", mapConstantsToMapNames->value(map->name)); + heal->put("destination_map_name", mapConstantsToMapNames.value(map->name)); heal->put("event_group_type", "heal_event_group"); heal->put("event_type", EventType::HealLocation); if (projectConfig.getHealLocationRespawnDataEnabled()) { - heal->put("respawn_map", mapConstantsToMapNames->value(QString("MAP_" + loc.respawnMap))); + heal->put("respawn_map", mapConstantsToMapNames.value(QString("MAP_" + loc.respawnMap))); heal->put("respawn_npc", loc.respawnNPC); } map->events["heal_event_group"].append(heal); @@ -408,8 +397,8 @@ bool Project::loadMapData(Map* map) { connection->direction = connectionObj["direction"].toString(); connection->offset = QString::number(connectionObj["offset"].toInt()); QString mapConstant = connectionObj["map"].toString(); - if (mapConstantsToMapNames->contains(mapConstant)) { - connection->map_name = mapConstantsToMapNames->value(mapConstant); + if (mapConstantsToMapNames.contains(mapConstant)) { + connection->map_name = mapConstantsToMapNames.value(mapConstant); map->connections.append(connection); } else { logError(QString("Failed to find connected map for map constant '%1'").arg(mapConstant)); @@ -703,7 +692,7 @@ void Project::saveMapGroups() { mapGroupsObj["layouts_table_label"] = layoutsLabel; OrderedJson::array groupNamesArr; - for (QString groupName : *this->groupNames) { + for (QString groupName : this->groupNames) { groupNamesArr.push_back(groupName); } mapGroupsObj["group_order"] = groupNamesArr; @@ -714,7 +703,7 @@ void Project::saveMapGroups() { for (QString mapName : mapNames) { groupArr.push_back(mapName); } - mapGroupsObj[this->groupNames->at(groupNum)] = groupArr; + mapGroupsObj[this->groupNames.at(groupNum)] = groupArr; groupNum++; } @@ -826,13 +815,13 @@ void Project::saveMapConstantsHeader() { text += QString("// Map Group %1\n").arg(groupNum); int maxLength = 0; for (QString mapName : mapNames) { - QString mapConstantName = mapNamesToMapConstants->value(mapName); + QString mapConstantName = mapNamesToMapConstants.value(mapName); if (mapConstantName.length() > maxLength) maxLength = mapConstantName.length(); } int groupIndex = 0; for (QString mapName : mapNames) { - QString mapConstantName = mapNamesToMapConstants->value(mapName); + QString mapConstantName = mapNamesToMapConstants.value(mapName); text += QString("#define %1%2(%3 | (%4 << 8))\n") .arg(mapConstantName) .arg(QString(" ").repeated(maxLength - mapConstantName.length() + 1)) @@ -1369,11 +1358,11 @@ void Project::saveMap(Map *map) { if (map->connections.length() > 0) { OrderedJson::array connectionsArr; for (MapConnection* connection : map->connections) { - if (mapNamesToMapConstants->contains(connection->map_name)) { + if (mapNamesToMapConstants.contains(connection->map_name)) { OrderedJson::object connectionObj; connectionObj["direction"] = connection->direction; connectionObj["offset"] = connection->offset.toInt(); - connectionObj["map"] = this->mapNamesToMapConstants->value(connection->map_name); + connectionObj["map"] = this->mapNamesToMapConstants.value(connection->map_name); connectionsArr.append(connectionObj); } else { logError(QString("Failed to write map connection. '%1' is not a valid map name").arg(connection->map_name)); @@ -1833,9 +1822,9 @@ bool Project::readWildMonData() { } bool Project::readMapGroups() { - mapConstantsToMapNames->clear(); - mapNamesToMapConstants->clear(); - mapGroups->clear(); + mapConstantsToMapNames.clear(); + mapNamesToMapConstants.clear(); + mapGroups.clear(); QString mapGroupsFilepath = QString("%1/data/maps/map_groups.json").arg(root); fileWatcher.addPath(mapGroupsFilepath); @@ -1849,29 +1838,29 @@ bool Project::readMapGroups() { QJsonArray mapGroupOrder = mapGroupsObj["group_order"].toArray(); QList groupedMaps; - QStringList *maps = new QStringList; - QStringList *groups = new QStringList; + QStringList maps; + QStringList groups; for (int groupIndex = 0; groupIndex < mapGroupOrder.size(); groupIndex++) { QString groupName = mapGroupOrder.at(groupIndex).toString(); QJsonArray mapNames = mapGroupsObj.value(groupName).toArray(); groupedMaps.append(QStringList()); - groups->append(groupName); + groups.append(groupName); for (int j = 0; j < mapNames.size(); j++) { QString mapName = mapNames.at(j).toString(); - mapGroups->insert(mapName, groupIndex); + mapGroups.insert(mapName, groupIndex); groupedMaps[groupIndex].append(mapName); - maps->append(mapName); + maps.append(mapName); // Build the mapping and reverse mapping between map constants and map names. QString mapConstant = Map::mapConstantFromName(mapName); - mapConstantsToMapNames->insert(mapConstant, mapName); - mapNamesToMapConstants->insert(mapName, mapConstant); + mapConstantsToMapNames.insert(mapConstant, mapName); + mapNamesToMapConstants.insert(mapName, mapConstant); } } - mapConstantsToMapNames->insert(NONE_MAP_CONSTANT, NONE_MAP_NAME); - mapNamesToMapConstants->insert(NONE_MAP_NAME, NONE_MAP_CONSTANT); - maps->append(NONE_MAP_NAME); + mapConstantsToMapNames.insert(NONE_MAP_CONSTANT, NONE_MAP_NAME); + mapNamesToMapConstants.insert(NONE_MAP_NAME, NONE_MAP_CONSTANT); + maps.append(NONE_MAP_NAME); groupNames = groups; groupedMapNames = groupedMaps; @@ -1881,15 +1870,15 @@ bool Project::readMapGroups() { Map* Project::addNewMapToGroup(QString mapName, int groupNum) { // Setup new map in memory, but don't write to file until map is actually saved later. - mapNames->append(mapName); - mapGroups->insert(mapName, groupNum); + mapNames.append(mapName); + mapGroups.insert(mapName, groupNum); groupedMapNames[groupNum].append(mapName); Map *map = new Map; map->isPersistedToFile = false; map->setName(mapName); - mapConstantsToMapNames->insert(map->constantName, map->name); - mapNamesToMapConstants->insert(map->name, map->constantName); + mapConstantsToMapNames.insert(map->constantName, map->name); + mapNamesToMapConstants.insert(map->name, map->constantName); setNewMapHeader(map, mapLayoutsTable.size() + 1); setNewMapLayout(map); loadMapTilesets(map); @@ -1903,8 +1892,8 @@ Map* Project::addNewMapToGroup(QString mapName, int groupNum) { } Map* Project::addNewMapToGroup(QString mapName, int groupNum, Map *newMap, bool existingLayout) { - mapNames->append(mapName); - mapGroups->insert(mapName, groupNum); + mapNames.append(mapName); + mapGroups.insert(mapName, groupNum); groupedMapNames[groupNum].append(mapName); Map *map = new Map; @@ -1913,8 +1902,8 @@ Map* Project::addNewMapToGroup(QString mapName, int groupNum, Map *newMap, bool map->isPersistedToFile = false; map->setName(mapName); - mapConstantsToMapNames->insert(map->constantName, map->name); - mapNamesToMapConstants->insert(map->name, map->constantName); + mapConstantsToMapNames.insert(map->constantName, map->name); + mapNamesToMapConstants.insert(map->name, map->constantName); if (!existingLayout) { mapLayouts.insert(map->layoutId, map->layout); mapLayoutsTable.append(map->layoutId); @@ -1935,7 +1924,7 @@ QString Project::getNewMapName() { QString newMapName; do { newMapName = QString("NewMap%1").arg(++i); - } while (mapNames->contains(newMapName)); + } while (mapNames.contains(newMapName)); return newMapName; } diff --git a/src/ui/draggablepixmapitem.cpp b/src/ui/draggablepixmapitem.cpp index cde101b1..a32edc93 100644 --- a/src/ui/draggablepixmapitem.cpp +++ b/src/ui/draggablepixmapitem.cpp @@ -106,7 +106,7 @@ void DraggablePixmapItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) { } else if (this->event->get("event_type") == EventType::SecretBase) { QString baseId = this->event->get("secret_base_id"); - QString destMap = editor->project->mapConstantsToMapNames->value("MAP_" + baseId.left(baseId.lastIndexOf("_"))); + QString destMap = editor->project->mapConstantsToMapNames.value("MAP_" + baseId.left(baseId.lastIndexOf("_"))); if (destMap != NONE_MAP_NAME) { emit editor->warpEventDoubleClicked(destMap, "0"); } diff --git a/src/ui/mapimageexporter.cpp b/src/ui/mapimageexporter.cpp index afcfeb7f..216c7db8 100644 --- a/src/ui/mapimageexporter.cpp +++ b/src/ui/mapimageexporter.cpp @@ -36,7 +36,7 @@ MapImageExporter::MapImageExporter(QWidget *parent_, Editor *editor_, ImageExpor this->ui->groupBox_Connections->setVisible(this->mode == ImageExporterMode::Normal); this->ui->groupBox_Timelapse->setVisible(this->mode == ImageExporterMode::Timelapse); - this->ui->comboBox_MapSelection->addItems(*editor->project->mapNames); + this->ui->comboBox_MapSelection->addItems(editor->project->mapNames); this->ui->comboBox_MapSelection->setCurrentText(map->name); this->ui->comboBox_MapSelection->setEnabled(false);// TODO: allow selecting map from drop-down diff --git a/src/ui/newmappopup.cpp b/src/ui/newmappopup.cpp index 19059623..31e4a653 100644 --- a/src/ui/newmappopup.cpp +++ b/src/ui/newmappopup.cpp @@ -89,8 +89,8 @@ void NewMapPopup::setDefaultValues(int groupNum, QString mapSec) { ui->comboBox_NewMap_Primary_Tileset->addItems(tilesets.value("primary")); ui->comboBox_NewMap_Secondary_Tileset->addItems(tilesets.value("secondary")); - ui->comboBox_NewMap_Group->addItems(*project->groupNames); - ui->comboBox_NewMap_Group->setCurrentText(project->groupNames->at(groupNum)); + ui->comboBox_NewMap_Group->addItems(project->groupNames); + ui->comboBox_NewMap_Group->setCurrentText(project->groupNames.at(groupNum)); if (existingLayout) { ui->spinBox_NewMap_Width->setValue(project->mapLayouts.value(layoutId)->width.toInt(nullptr, 0)); @@ -165,7 +165,7 @@ void NewMapPopup::setDefaultValues(int groupNum, QString mapSec) { } void NewMapPopup::on_lineEdit_NewMap_Name_textChanged(const QString &text) { - if (project->mapNames->contains(text)) { + if (project->mapNames.contains(text)) { QPalette palette = this->ui->lineEdit_NewMap_Name->palette(); QColor color = Qt::red; color.setAlpha(25); @@ -188,7 +188,7 @@ void NewMapPopup::on_pushButton_NewMap_Accept_clicked() { // After stripping invalid characters, strip any leading digits. QString newMapName = this->ui->lineEdit_NewMap_Name->text().remove(QRegularExpression("[^a-zA-Z0-9_]+")); newMapName.remove(QRegularExpression("^[0-9]*")); - if (project->mapNames->contains(newMapName) || newMapName.isEmpty()) { + if (project->mapNames.contains(newMapName) || newMapName.isEmpty()) { newMapName = project->getNewMapName(); } @@ -236,7 +236,7 @@ void NewMapPopup::on_pushButton_NewMap_Accept_clicked() { newMap->floorNumber = this->ui->spinBox_NewMap_Floor_Number->value(); } - group = project->groupNames->indexOf(this->ui->comboBox_NewMap_Group->currentText()); + group = project->groupNames.indexOf(this->ui->comboBox_NewMap_Group->currentText()); newMap->layout = layout; newMap->layoutId = layout->id; if (this->existingLayout) { diff --git a/src/ui/regionmapeditor.cpp b/src/ui/regionmapeditor.cpp index eab70589..6d19cb25 100644 --- a/src/ui/regionmapeditor.cpp +++ b/src/ui/regionmapeditor.cpp @@ -215,7 +215,7 @@ void RegionMapEditor::displayRegionMapLayoutOptions() { void RegionMapEditor::updateRegionMapLayoutOptions(int index) { this->ui->comboBox_RM_ConnectedMap->blockSignals(true); - this->ui->lineEdit_RM_MapName->setText(this->project->mapSecToMapHoverName->value(this->region_map->map_squares[index].mapsec)); + this->ui->lineEdit_RM_MapName->setText(this->project->mapSecToMapHoverName.value(this->region_map->map_squares[index].mapsec)); this->ui->comboBox_RM_ConnectedMap->setCurrentText(this->region_map->map_squares[index].mapsec); this->ui->comboBox_RM_ConnectedMap->blockSignals(false); } @@ -438,7 +438,7 @@ void RegionMapEditor::onRegionMapLayoutSelectedTileChanged(int index) { this->currIndex = index; this->region_map_layout_item->highlightedTile = index; if (this->region_map->map_squares[index].has_map) { - message = QString("\t %1").arg(this->project->mapSecToMapHoverName->value( + message = QString("\t %1").arg(this->project->mapSecToMapHoverName.value( this->region_map->map_squares[index].mapsec)).remove("{NAME_END}"); } this->ui->statusbar->showMessage(message); @@ -454,7 +454,7 @@ void RegionMapEditor::onRegionMapLayoutHoveredTileChanged(int index) { if (x >= 0 && y >= 0) { message = QString("(%1, %2)").arg(x).arg(y); if (this->region_map->map_squares[index].has_map) { - message += QString("\t %1").arg(this->project->mapSecToMapHoverName->value( + message += QString("\t %1").arg(this->project->mapSecToMapHoverName.value( this->region_map->map_squares[index].mapsec)).remove("{NAME_END}"); } } @@ -551,7 +551,7 @@ void RegionMapEditor::on_tabWidget_Region_Map_currentChanged(int index) { } void RegionMapEditor::on_comboBox_RM_ConnectedMap_activated(const QString &mapsec) { - this->ui->lineEdit_RM_MapName->setText(this->project->mapSecToMapHoverName->value(mapsec)); + this->ui->lineEdit_RM_MapName->setText(this->project->mapSecToMapHoverName.value(mapsec)); onRegionMapLayoutSelectedTileChanged(this->currIndex);// re-draw layout image this->hasUnsavedChanges = true;// sometimes this is called for unknown reasons } From 9a9143500f0c95ed045b7970d5c4d2d1e63e8236 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 11:33:30 -0500 Subject: [PATCH 25/46] Convert remaing pointers in Project to values --- include/project.h | 26 +++--- src/core/event.cpp | 16 ++-- src/mainwindow.cpp | 40 +++++----- src/project.cpp | 176 +++++++++++++++++------------------------ src/ui/newmappopup.cpp | 6 +- 5 files changed, 116 insertions(+), 148 deletions(-) diff --git a/include/project.h b/include/project.h index 41dfb758..7990ec8f 100644 --- a/include/project.h +++ b/include/project.h @@ -49,17 +49,17 @@ public: QMap mapSecToMapHoverName; QMap mapSectionNameToValue; QMap mapSectionValueToName; - QStringList *itemNames = nullptr; - QStringList *flagNames = nullptr; - QStringList *varNames = nullptr; - QStringList *movementTypes = nullptr; - QStringList *mapTypes = nullptr; - QStringList *mapBattleScenes = nullptr; - QStringList *weatherNames = nullptr; - QStringList *coordEventWeatherNames = nullptr; - QStringList *secretBaseIds = nullptr; - QStringList *bgEventFacingDirections = nullptr; - QStringList *trainerTypes = nullptr; + QStringList itemNames; + QStringList flagNames; + QStringList varNames; + QStringList movementTypes; + QStringList mapTypes; + QStringList mapBattleScenes; + QStringList weatherNames; + QStringList coordEventWeatherNames; + QStringList secretBaseIds; + QStringList bgEventFacingDirections; + QStringList trainerTypes; QMap metatileBehaviorMap; QMap metatileBehaviorMapInverse; QMap facingDirections; @@ -82,11 +82,11 @@ public: DataQualifiers getDataQualifiers(QString, QString); QMap dataQualifiers; - QMap *mapCache; + QMap mapCache; Map* loadMap(QString); Map* getMap(QString); - QMap *tilesetCache = nullptr; + QMap tilesetCache; Tileset* loadTileset(QString, Tileset *tileset = nullptr); Tileset* getTileset(QString, bool forceLoad = false); QMap tilesetLabels; diff --git a/src/core/event.cpp b/src/core/event.cpp index 811f9328..ea8e078f 100644 --- a/src/core/event.cpp +++ b/src/core/event.cpp @@ -71,7 +71,7 @@ Event* Event::createNewObjectEvent(Project *project) event->put("event_group_type", "object_event_group"); event->put("event_type", EventType::Object); event->put("sprite", project->getEventObjGfxConstants().keys().first()); - event->put("movement_type", project->movementTypes->first()); + event->put("movement_type", project->movementTypes.first()); if (projectConfig.getObjectEventInConnectionEnabled()) { event->put("in_connection", false); } @@ -80,7 +80,7 @@ Event* Event::createNewObjectEvent(Project *project) event->put("script_label", "NULL"); event->put("event_flag", "0"); event->put("replacement", "0"); - event->put("trainer_type", project->trainerTypes->value(0, "0")); + event->put("trainer_type", project->trainerTypes.value(0, "0")); event->put("sight_radius_tree_id", 0); event->put("elevation", 3); return event; @@ -118,7 +118,7 @@ Event* Event::createNewTriggerEvent(Project *project) event->put("event_group_type", "coord_event_group"); event->put("event_type", EventType::Trigger); event->put("script_label", "NULL"); - event->put("script_var", project->varNames->first()); + event->put("script_var", project->varNames.first()); event->put("script_var_value", "0"); event->put("elevation", 0); return event; @@ -129,7 +129,7 @@ Event* Event::createNewWeatherTriggerEvent(Project *project) Event *event = new Event; event->put("event_group_type", "coord_event_group"); event->put("event_type", EventType::WeatherTrigger); - event->put("weather", project->coordEventWeatherNames->first()); + event->put("weather", project->coordEventWeatherNames.first()); event->put("elevation", 0); return event; } @@ -139,7 +139,7 @@ Event* Event::createNewSignEvent(Project *project) Event *event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::Sign); - event->put("player_facing_direction", project->bgEventFacingDirections->first()); + event->put("player_facing_direction", project->bgEventFacingDirections.first()); event->put("script_label", "NULL"); event->put("elevation", 0); return event; @@ -150,8 +150,8 @@ Event* Event::createNewHiddenItemEvent(Project *project) Event *event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::HiddenItem); - event->put("item", project->itemNames->first()); - event->put("flag", project->flagNames->first()); + event->put("item", project->itemNames.first()); + event->put("flag", project->flagNames.first()); event->put("elevation", 3); if (projectConfig.getHiddenItemQuantityEnabled()) { event->put("quantity", 1); @@ -167,7 +167,7 @@ Event* Event::createNewSecretBaseEvent(Project *project) Event *event = new Event; event->put("event_group_type", "bg_event_group"); event->put("event_type", EventType::SecretBase); - event->put("secret_base_id", project->secretBaseIds->first()); + event->put("secret_base_id", project->secretBaseIds.first()); event->put("elevation", 0); return event; } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 8a1ae0dd..559c6f4c 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -910,11 +910,11 @@ bool MainWindow::loadProjectCombos() { ui->comboBox_SecondaryTileset->clear(); ui->comboBox_SecondaryTileset->addItems(tilesets.value("secondary")); ui->comboBox_Weather->clear(); - ui->comboBox_Weather->addItems(*project->weatherNames); + ui->comboBox_Weather->addItems(project->weatherNames); ui->comboBox_BattleScene->clear(); - ui->comboBox_BattleScene->addItems(*project->mapBattleScenes); + ui->comboBox_BattleScene->addItems(project->mapBattleScenes); ui->comboBox_Type->clear(); - ui->comboBox_Type->addItems(*project->mapTypes); + ui->comboBox_Type->addItems(project->mapTypes); return true; } @@ -1347,10 +1347,10 @@ void MainWindow::drawMapListIcons(QAbstractItemModel *model) { QVariant data = index.data(Qt::UserRole); if (!data.isNull()) { QString map_name = data.toString(); - if (editor->project && editor->project->mapCache->contains(map_name)) { + if (editor->project && editor->project->mapCache.contains(map_name)) { QStandardItem *map = mapListModel->itemFromIndex(mapListIndexes.value(map_name)); map->setIcon(*mapIcon); - if (editor->project->mapCache->value(map_name)->hasUnsavedChanges()) { + if (editor->project->mapCache.value(map_name)->hasUnsavedChanges()) { map->setIcon(*mapEditedIcon); projectHasUnsavedChanges = true; } @@ -1837,10 +1837,10 @@ void MainWindow::updateSelectedObjects() { } else if (key == "destination_warp") { combo->setToolTip("The warp id on the destination map."); } else if (key == "item") { - if (!editor->project->itemNames->contains(value)) { + if (!editor->project->itemNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->itemNames); + combo->addItems(editor->project->itemNames); combo->setCurrentIndex(combo->findText(value)); } else if (key == "quantity") { spin->setToolTip("The number of items received when the hidden item is picked up."); @@ -1849,27 +1849,27 @@ void MainWindow::updateSelectedObjects() { } else if (key == "underfoot") { check->setToolTip("If checked, hidden item can only be picked up using the Itemfinder"); } else if (key == "flag" || key == "event_flag") { - if (!editor->project->flagNames->contains(value)) { + if (!editor->project->flagNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->flagNames); + combo->addItems(editor->project->flagNames); combo->setCurrentIndex(combo->findText(value)); if (key == "flag") combo->setToolTip("The flag which is set when the hidden item is picked up."); else if (key == "event_flag") combo->setToolTip("The flag which hides the object when set."); } else if (key == "script_var") { - if (!editor->project->varNames->contains(value)) { + if (!editor->project->varNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->varNames); + combo->addItems(editor->project->varNames); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The variable by which the script is triggered.\n" "The script is triggered when this variable's value matches 'Var Value'."); } else if (key == "script_var_value") { combo->setToolTip("The variable's value which triggers the script."); } else if (key == "movement_type") { - if (!editor->project->movementTypes->contains(value)) { + if (!editor->project->movementTypes.contains(value)) { combo->addItem(value); } connect(combo, static_cast(&QComboBox::currentTextChanged), @@ -1877,31 +1877,31 @@ void MainWindow::updateSelectedObjects() { item->event->setFrameFromMovement(editor->project->facingDirections.value(value)); item->updatePixmap(); }); - combo->addItems(*editor->project->movementTypes); + combo->addItems(editor->project->movementTypes); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The object's natural movement behavior when\n" "the player is not interacting with it."); } else if (key == "weather") { - if (!editor->project->coordEventWeatherNames->contains(value)) { + if (!editor->project->coordEventWeatherNames.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->coordEventWeatherNames); + combo->addItems(editor->project->coordEventWeatherNames); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The weather that starts when the player steps on this spot."); } else if (key == "secret_base_id") { - if (!editor->project->secretBaseIds->contains(value)) { + if (!editor->project->secretBaseIds.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->secretBaseIds); + combo->addItems(editor->project->secretBaseIds); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The secret base id which is inside this secret\n" "base entrance. Secret base ids are meant to be\n" "unique to each and every secret base entrance."); } else if (key == "player_facing_direction") { - if (!editor->project->bgEventFacingDirections->contains(value)) { + if (!editor->project->bgEventFacingDirections.contains(value)) { combo->addItem(value); } - combo->addItems(*editor->project->bgEventFacingDirections); + combo->addItems(editor->project->bgEventFacingDirections); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The direction which the player must be facing\n" "to be able to interact with this event."); @@ -1919,7 +1919,7 @@ void MainWindow::updateSelectedObjects() { combo->addItems(editor->map->eventScriptLabels()); combo->setToolTip("The script which is executed with this event."); } else if (key == "trainer_type") { - combo->addItems(*editor->project->trainerTypes); + combo->addItems(editor->project->trainerTypes); combo->setCurrentIndex(combo->findText(value)); combo->setToolTip("The trainer type of this object event.\n" "If it is not a trainer, use NONE. SEE ALL DIRECTIONS\n" diff --git a/src/project.cpp b/src/project.cpp index 07abc4b9..34bb2241 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -38,42 +38,13 @@ int Project::max_object_events = 64; Project::Project(QWidget *parent) : parent(parent) { - itemNames = new QStringList; - flagNames = new QStringList; - varNames = new QStringList; - movementTypes = new QStringList; - mapTypes = new QStringList; - mapBattleScenes = new QStringList; - weatherNames = new QStringList; - coordEventWeatherNames = new QStringList; - secretBaseIds = new QStringList; - bgEventFacingDirections = new QStringList; - trainerTypes = new QStringList; - mapCache = new QMap; - tilesetCache = new QMap; - initSignals(); } Project::~Project() { - delete this->itemNames; - delete this->flagNames; - delete this->varNames; - delete this->weatherNames; - delete this->coordEventWeatherNames; - - delete this->secretBaseIds; - delete this->movementTypes; - delete this->bgEventFacingDirections; - delete this->mapBattleScenes; - delete this->trainerTypes; - delete this->mapTypes; - clearMapCache(); - delete this->mapCache; clearTilesetCache(); - delete this->tilesetCache; } void Project::initSignals() { @@ -128,24 +99,24 @@ QString Project::getProjectTitle() { } void Project::clearMapCache() { - for (QString mapName : mapCache->keys()) { - Map *map = mapCache->take(mapName); + for (QString mapName : mapCache.keys()) { + Map *map = mapCache.take(mapName); if (map) delete map; } emit mapCacheCleared(); } void Project::clearTilesetCache() { - for (QString tilesetName : tilesetCache->keys()) { - Tileset *tileset = tilesetCache->take(tilesetName); + for (QString tilesetName : tilesetCache.keys()) { + Tileset *tileset = tilesetCache.take(tilesetName); if (tileset) delete tileset; } } Map* Project::loadMap(QString map_name) { Map *map; - if (mapCache->contains(map_name)) { - map = mapCache->value(map_name); + if (mapCache.contains(map_name)) { + map = mapCache.value(map_name); // TODO: uncomment when undo/redo history is fully implemented for all actions. if (true/*map->hasUnsavedChanges()*/) { return map; @@ -158,7 +129,7 @@ Map* Project::loadMap(QString map_name) { if (!(loadMapData(map) && loadMapLayout(map))) return nullptr; - mapCache->insert(map_name, map); + mapCache.insert(map_name, map); return map; } @@ -418,8 +389,8 @@ bool Project::loadMapData(Map* map) { } QString Project::readMapLayoutId(QString map_name) { - if (mapCache->contains(map_name)) { - return mapCache->value(map_name)->layoutId; + if (mapCache.contains(map_name)) { + return mapCache.value(map_name)->layoutId; } QString mapFilepath = QString("%1/data/maps/%2/map.json").arg(root).arg(map_name); @@ -434,8 +405,8 @@ QString Project::readMapLayoutId(QString map_name) { } QString Project::readMapLocation(QString map_name) { - if (mapCache->contains(map_name)) { - return mapCache->value(map_name)->location; + if (mapCache.contains(map_name)) { + return mapCache.value(map_name)->location; } QString mapFilepath = QString("%1/data/maps/%2/map.json").arg(root).arg(map_name); @@ -453,8 +424,8 @@ void Project::setNewMapHeader(Map* map, int mapIndex) { map->layoutId = QString("%1").arg(mapIndex); map->location = mapSectionValueToName.value(0); map->requiresFlash = "FALSE"; - map->weather = weatherNames->value(0, "WEATHER_NONE"); - map->type = mapTypes->value(0, "MAP_TYPE_NONE"); + map->weather = weatherNames.value(0, "WEATHER_NONE"); + map->type = mapTypes.value(0, "MAP_TYPE_NONE"); map->song = defaultSong; if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokeruby) { map->show_location = "TRUE"; @@ -468,7 +439,7 @@ void Project::setNewMapHeader(Map* map, int mapIndex) { map->floorNumber = 0; } - map->battle_scene = mapBattleScenes->value(0, "MAP_BATTLE_SCENE_NORMAL"); + map->battle_scene = mapBattleScenes.value(0, "MAP_BATTLE_SCENE_NORMAL"); } bool Project::loadMapLayout(Map* map) { @@ -1161,7 +1132,7 @@ Tileset* Project::loadTileset(QString label, Tileset *tileset) { loadTilesetAssets(tileset); - tilesetCache->insert(label, tileset); + tilesetCache.insert(label, tileset); return tileset; } @@ -1252,10 +1223,10 @@ void Project::writeBlockdata(QString path, const Blockdata &blockdata) { } void Project::saveAllMaps() { - QList keys = mapCache->keys(); + QList keys = mapCache.keys(); for (int i = 0; i < keys.length(); i++) { QString key = keys.value(i); - Map* map = mapCache->value(key); + Map* map = mapCache.value(key); saveMap(map); } } @@ -1701,8 +1672,8 @@ Blockdata Project::readBlockdata(QString path) { } Map* Project::getMap(QString map_name) { - if (mapCache->contains(map_name)) { - return mapCache->value(map_name); + if (mapCache.contains(map_name)) { + return mapCache.value(map_name); } else { Map *map = loadMap(map_name); return map; @@ -1711,12 +1682,12 @@ Map* Project::getMap(QString map_name) { Tileset* Project::getTileset(QString label, bool forceLoad) { Tileset *existingTileset = nullptr; - if (tilesetCache->contains(label)) { - existingTileset = tilesetCache->value(label); + if (tilesetCache.contains(label)) { + existingTileset = tilesetCache.value(label); } if (existingTileset && !forceLoad) { - return tilesetCache->value(label); + return tilesetCache.value(label); } else { Tileset *tileset = loadTileset(label, existingTileset); return tileset; @@ -1886,7 +1857,7 @@ Map* Project::addNewMapToGroup(QString mapName, int groupNum) { setNewMapBorder(map); setNewMapEvents(map); setNewMapConnections(map); - mapCache->insert(mapName, map); + mapCache.insert(mapName, map); return map; } @@ -2142,12 +2113,12 @@ bool Project::readHealLocations() { } bool Project::readItemNames() { - itemNames->clear(); - QStringList prefixes = (QStringList() << "\\bITEM_(?!(B_)?USE_)"); // Exclude ITEM_USE_ and ITEM_B_USE_ constants + itemNames.clear(); + QStringList prefixes("\\bITEM_(?!(B_)?USE_)"); // Exclude ITEM_USE_ and ITEM_B_USE_ constants QString filename = "include/constants/items.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, itemNames); - if (itemNames->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &itemNames); + if (itemNames.isEmpty()) { logError(QString("Failed to read item constants from %1").arg(filename)); return false; } @@ -2161,12 +2132,12 @@ bool Project::readFlagNames() { fileWatcher.addPath(root + "/" + opponentsFilename); QMap maxTrainers = parser.readCDefines(opponentsFilename, QStringList() << "\\bMAX_"); // Parse flags - flagNames->clear(); - QStringList prefixes = (QStringList() << "\\bFLAG_"); + flagNames.clear(); + QStringList prefixes("\\bFLAG_"); QString flagsFilename = "include/constants/flags.h"; fileWatcher.addPath(root + "/" + flagsFilename); - parser.readCDefinesSorted(flagsFilename, prefixes, flagNames, maxTrainers); - if (flagNames->isEmpty()) { + parser.readCDefinesSorted(flagsFilename, prefixes, &flagNames, maxTrainers); + if (flagNames.isEmpty()) { logError(QString("Failed to read flag constants from %1").arg(flagsFilename)); return false; } @@ -2174,12 +2145,12 @@ bool Project::readFlagNames() { } bool Project::readVarNames() { - varNames->clear(); - QStringList prefixes = (QStringList() << "\\bVAR_"); + varNames.clear(); + QStringList prefixes("\\bVAR_"); QString filename = "include/constants/vars.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, varNames); - if (varNames->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &varNames); + if (varNames.isEmpty()) { logError(QString("Failed to read var constants from %1").arg(filename)); return false; } @@ -2187,12 +2158,12 @@ bool Project::readVarNames() { } bool Project::readMovementTypes() { - movementTypes->clear(); - QStringList prefixes = (QStringList() << "\\bMOVEMENT_TYPE_"); + movementTypes.clear(); + QStringList prefixes("\\bMOVEMENT_TYPE_"); QString filename = "include/constants/event_object_movement.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, movementTypes); - if (movementTypes->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &movementTypes); + if (movementTypes.isEmpty()) { logError(QString("Failed to read movement type constants from %1").arg(filename)); return false; } @@ -2211,12 +2182,12 @@ bool Project::readInitialFacingDirections() { } bool Project::readMapTypes() { - mapTypes->clear(); - QStringList prefixes = (QStringList() << "\\bMAP_TYPE_"); + mapTypes.clear(); + QStringList prefixes("\\bMAP_TYPE_"); QString filename = "include/constants/map_types.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, mapTypes); - if (mapTypes->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &mapTypes); + if (mapTypes.isEmpty()) { logError(QString("Failed to read map type constants from %1").arg(filename)); return false; } @@ -2224,12 +2195,12 @@ bool Project::readMapTypes() { } bool Project::readMapBattleScenes() { - mapBattleScenes->clear(); - QStringList prefixes = (QStringList() << "\\bMAP_BATTLE_SCENE_"); + mapBattleScenes.clear(); + QStringList prefixes("\\bMAP_BATTLE_SCENE_"); QString filename = "include/constants/map_types.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted("include/constants/map_types.h", prefixes, mapBattleScenes); - if (mapBattleScenes->isEmpty()) { + parser.readCDefinesSorted("include/constants/map_types.h", prefixes, &mapBattleScenes); + if (mapBattleScenes.isEmpty()) { logError(QString("Failed to read map battle scene constants from %1").arg(filename)); return false; } @@ -2237,12 +2208,12 @@ bool Project::readMapBattleScenes() { } bool Project::readWeatherNames() { - weatherNames->clear(); - QStringList prefixes = (QStringList() << "\\bWEATHER_"); + weatherNames.clear(); + QStringList prefixes("\\bWEATHER_"); QString filename = "include/constants/weather.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, weatherNames); - if (weatherNames->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &weatherNames); + if (weatherNames.isEmpty()) { logError(QString("Failed to read weather constants from %1").arg(filename)); return false; } @@ -2252,12 +2223,12 @@ bool Project::readWeatherNames() { bool Project::readCoordEventWeatherNames() { if (!projectConfig.getEventWeatherTriggerEnabled()) return true; - coordEventWeatherNames->clear(); - QStringList prefixes = (QStringList() << "\\bCOORD_EVENT_WEATHER_"); + coordEventWeatherNames.clear(); + QStringList prefixes("\\bCOORD_EVENT_WEATHER_"); QString filename = "include/constants/weather.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, coordEventWeatherNames); - if (coordEventWeatherNames->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &coordEventWeatherNames); + if (coordEventWeatherNames.isEmpty()) { logError(QString("Failed to read coord event weather constants from %1").arg(filename)); return false; } @@ -2267,12 +2238,12 @@ bool Project::readCoordEventWeatherNames() { bool Project::readSecretBaseIds() { if (!projectConfig.getEventSecretBaseEnabled()) return true; - secretBaseIds->clear(); - QStringList prefixes = (QStringList() << "\\bSECRET_BASE_[A-Za-z0-9_]*_[0-9]+"); + secretBaseIds.clear(); + QStringList prefixes("\\bSECRET_BASE_[A-Za-z0-9_]*_[0-9]+"); QString filename = "include/constants/secret_bases.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, secretBaseIds); - if (secretBaseIds->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &secretBaseIds); + if (secretBaseIds.isEmpty()) { logError(QString("Failed to read secret base id constants from %1").arg(filename)); return false; } @@ -2280,12 +2251,12 @@ bool Project::readSecretBaseIds() { } bool Project::readBgEventFacingDirections() { - bgEventFacingDirections->clear(); - QStringList prefixes = (QStringList() << "\\bBG_EVENT_PLAYER_FACING_"); + bgEventFacingDirections.clear(); + QStringList prefixes("\\bBG_EVENT_PLAYER_FACING_"); QString filename = "include/constants/event_bg.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, bgEventFacingDirections); - if (bgEventFacingDirections->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &bgEventFacingDirections); + if (bgEventFacingDirections.isEmpty()) { logError(QString("Failed to read bg event facing direction constants from %1").arg(filename)); return false; } @@ -2293,12 +2264,12 @@ bool Project::readBgEventFacingDirections() { } bool Project::readTrainerTypes() { - trainerTypes->clear(); - QStringList prefixes = (QStringList() << "\\bTRAINER_TYPE_"); + trainerTypes.clear(); + QStringList prefixes("\\bTRAINER_TYPE_"); QString filename = "include/constants/trainer_types.h"; fileWatcher.addPath(root + "/" + filename); - parser.readCDefinesSorted(filename, prefixes, trainerTypes); - if (trainerTypes->isEmpty()) { + parser.readCDefinesSorted(filename, prefixes, &trainerTypes); + if (trainerTypes.isEmpty()) { logError(QString("Failed to read trainer type constants from %1").arg(filename)); return false; } @@ -2309,7 +2280,7 @@ bool Project::readMetatileBehaviors() { this->metatileBehaviorMap.clear(); this->metatileBehaviorMapInverse.clear(); - QStringList prefixes = (QStringList() << "\\bMB_"); + QStringList prefixes("\\bMB_"); QString filename = "include/constants/metatile_behaviors.h"; fileWatcher.addPath(root + "/" + filename); this->metatileBehaviorMap = parser.readCDefines(filename, prefixes); @@ -2325,8 +2296,7 @@ bool Project::readMetatileBehaviors() { } QStringList Project::getSongNames() { - QStringList songDefinePrefixes; - songDefinePrefixes << "\\bSE_" << "\\bMUS_"; + QStringList songDefinePrefixes{ "\\bSE_", "\\bMUS_" }; QString filename = "include/constants/songs.h"; fileWatcher.addPath(root + "/" + filename); QMap songDefines = parser.readCDefines(filename, songDefinePrefixes); @@ -2337,8 +2307,7 @@ QStringList Project::getSongNames() { } QMap Project::getEventObjGfxConstants() { - QStringList eventObjGfxPrefixes; - eventObjGfxPrefixes << "\\bOBJ_EVENT_GFX_"; + QStringList eventObjGfxPrefixes("\\bOBJ_EVENT_GFX_"); QString filename = "include/constants/event_objects.h"; fileWatcher.addPath(root + "/" + filename); @@ -2352,15 +2321,14 @@ bool Project::readMiscellaneousConstants() { if (projectConfig.getEncounterJsonActive()) { QString filename = "include/constants/pokemon.h"; fileWatcher.addPath(root + "/" + filename); - QMap pokemonDefines = parser.readCDefines(filename, QStringList() << "MIN_" << "MAX_"); + QMap pokemonDefines = parser.readCDefines(filename, { "MIN_", "MAX_" }); miscConstants.insert("max_level_define", pokemonDefines.value("MAX_LEVEL") > pokemonDefines.value("MIN_LEVEL") ? pokemonDefines.value("MAX_LEVEL") : 100); miscConstants.insert("min_level_define", pokemonDefines.value("MIN_LEVEL") < pokemonDefines.value("MAX_LEVEL") ? pokemonDefines.value("MIN_LEVEL") : 1); } QString filename = "include/constants/global.h"; fileWatcher.addPath(root + "/" + filename); - QStringList definePrefixes; - definePrefixes << "\\bOBJECT_"; + QStringList definePrefixes("\\bOBJECT_"); QMap defines = parser.readCDefines(filename, definePrefixes); auto it = defines.find("OBJECT_EVENT_TEMPLATES_COUNT"); diff --git a/src/ui/newmappopup.cpp b/src/ui/newmappopup.cpp index 31e4a653..5b2c6426 100644 --- a/src/ui/newmappopup.cpp +++ b/src/ui/newmappopup.cpp @@ -110,7 +110,7 @@ void NewMapPopup::setDefaultValues(int groupNum, QString mapSec) { ui->spinBox_NewMap_BorderHeight->setValue(DEFAULT_BORDER_HEIGHT); } - ui->comboBox_NewMap_Type->addItems(*project->mapTypes); + ui->comboBox_NewMap_Type->addItems(project->mapTypes); ui->comboBox_NewMap_Location->addItems(project->mapSectionValueToName.values()); if (!mapSec.isEmpty()) ui->comboBox_NewMap_Location->setCurrentText(mapSec); ui->checkBox_NewMap_Show_Location->setChecked(true); @@ -197,9 +197,9 @@ void NewMapPopup::on_pushButton_NewMap_Accept_clicked() { newMap->location = this->ui->comboBox_NewMap_Location->currentText(); newMap->song = this->project->defaultSong; newMap->requiresFlash = "0"; - newMap->weather = this->project->weatherNames->value(0, "WEATHER_NONE"); + newMap->weather = this->project->weatherNames.value(0, "WEATHER_NONE"); newMap->show_location = this->ui->checkBox_NewMap_Show_Location->isChecked() ? "1" : "0"; - newMap->battle_scene = this->project->mapBattleScenes->value(0, "MAP_BATTLE_SCENE_NORMAL"); + newMap->battle_scene = this->project->mapBattleScenes.value(0, "MAP_BATTLE_SCENE_NORMAL"); if (this->existingLayout) { layout = this->project->mapLayouts.value(this->layoutId); From d9340d3b731b8025d5cc0569866b4a69eec177a5 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 11:43:18 -0500 Subject: [PATCH 26/46] Add parentWidget() to Project to avoid name-shadowing the parent member --- include/project.h | 4 ++-- src/project.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/project.h b/include/project.h index 7990ec8f..1ea1b1a3 100644 --- a/include/project.h +++ b/include/project.h @@ -31,6 +31,8 @@ public: Project(const Project &) = delete; Project & operator = (const Project &) = delete; + inline QWidget *parentWidget() const { return static_cast(parent()); } + public: QString root; QStringList groupNames; @@ -219,8 +221,6 @@ private: static int default_map_size; static int max_object_events; - QWidget *parent; - signals: void reloadProject(); void uncheckMonitorFilesAction(); diff --git a/src/project.cpp b/src/project.cpp index 34bb2241..1f49cf3e 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -36,7 +36,7 @@ int Project::max_map_data_size = 10240; // 0x2800 int Project::default_map_size = 20; int Project::max_object_events = 64; -Project::Project(QWidget *parent) : parent(parent) +Project::Project(QWidget *parent) : QObject(parent) { initSignals(); } @@ -61,7 +61,7 @@ void Project::initSignals() { static bool showing = false; if (showing) return; - QMessageBox notice(this->parent); + QMessageBox notice(this->parentWidget()); notice.setText("File Changed"); notice.setInformativeText(QString("The file %1 has changed on disk. Would you like to reload the project?") .arg(changed.remove(this->root + "/"))); From f65b6a047eb2d736ef4e251bc12b8cbf4cd7978c Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 05:24:10 -0500 Subject: [PATCH 27/46] Fix a memory leak in parseAsm() --- src/core/parseutil.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/core/parseutil.cpp b/src/core/parseutil.cpp index e59cee49..e6b8a274 100644 --- a/src/core/parseutil.cpp +++ b/src/core/parseutil.cpp @@ -65,25 +65,19 @@ QList* ParseUtil::parseAsm(QString filename) { text = readTextFile(root + "/" + filename); QStringList lines = text.split('\n'); for (QString line : lines) { - QString label; strip_comment(&line); if (line.trimmed().isEmpty()) { } else if (line.contains(':')) { - label = line.left(line.indexOf(':')); - QStringList *list = new QStringList; - list->append(".label"); // This is not a real keyword. It's used only to make the output more regular. - list->append(label); - parsed->append(*list); + QString label = line.left(line.indexOf(':')); + QStringList list{ ".label", label }; // .label is not a real keyword. It's used only to make the output more regular. + parsed->append(list); // There should not be anything else on the line. // gas will raise a syntax error if there is. } else { line = line.trimmed(); - //parsed->append(line.split(QRegExp("\\s*,\\s*"))); - QString macro; - QStringList params; int index = line.indexOf(QRegExp("\\s+")); - macro = line.left(index); - params = line.right(line.length() - index).trimmed().split(QRegExp("\\s*,\\s*")); + QString macro = line.left(index); + QStringList params(line.right(line.length() - index).trimmed().split(QRegExp("\\s*,\\s*"))); params.prepend(macro); parsed->append(params); } From fa8b3871202444641f3a78b0a3df066492d3aaec Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 06:15:54 -0500 Subject: [PATCH 28/46] Fix some more memory leaks related to parseAsm() --- include/core/parseutil.h | 6 ++-- src/core/parseutil.cpp | 48 ++++++++++++++++---------------- src/project.cpp | 59 ++++++++++++++++++++-------------------- 3 files changed, 55 insertions(+), 58 deletions(-) diff --git a/include/core/parseutil.h b/include/core/parseutil.h index 96cc1201..399f43fb 100644 --- a/include/core/parseutil.h +++ b/include/core/parseutil.h @@ -44,15 +44,15 @@ public: static QString readTextFile(QString); static int textFileLineCount(const QString &path); void strip_comment(QString*); - QList* parseAsm(QString); + QList parseAsm(const QString &filename); int evaluateDefine(QString, QMap*); QStringList readCArray(QString text, QString label); QMap readNamedIndexCArray(QString text, QString label); QString readCIncbin(QString text, QString label); QMap readCDefines(QString filename, QStringList prefixes, QMap = QMap()); void readCDefinesSorted(QString, QStringList, QStringList*, QMap = QMap()); - QList* getLabelMacros(QList*, QString); - QStringList* getLabelValues(QList*, QString); + QList getLabelMacros(const QList &, const QString &); + QStringList getLabelValues(const QList &, const QString &); bool tryParseJsonFile(QJsonDocument *out, QString filepath); bool ensureFieldsExist(QJsonObject obj, QList fields); diff --git a/src/core/parseutil.cpp b/src/core/parseutil.cpp index e6b8a274..cd053458 100644 --- a/src/core/parseutil.cpp +++ b/src/core/parseutil.cpp @@ -59,27 +59,27 @@ int ParseUtil::textFileLineCount(const QString &path) { return text.split('\n').count() + 1; } -QList* ParseUtil::parseAsm(QString filename) { - QList *parsed = new QList; +QList ParseUtil::parseAsm(const QString &filename) { + QList parsed; - text = readTextFile(root + "/" + filename); - QStringList lines = text.split('\n'); + text = readTextFile(root + '/' + filename); + const QStringList lines = text.split('\n'); for (QString line : lines) { strip_comment(&line); if (line.trimmed().isEmpty()) { } else if (line.contains(':')) { - QString label = line.left(line.indexOf(':')); - QStringList list{ ".label", label }; // .label is not a real keyword. It's used only to make the output more regular. - parsed->append(list); + const QString label = line.left(line.indexOf(':')); + const QStringList list{ ".label", label }; // .label is not a real keyword. It's used only to make the output more regular. + parsed.append(list); // There should not be anything else on the line. // gas will raise a syntax error if there is. } else { line = line.trimmed(); int index = line.indexOf(QRegExp("\\s+")); - QString macro = line.left(index); + const QString macro = line.left(index); QStringList params(line.right(line.length() - index).trimmed().split(QRegExp("\\s*,\\s*"))); params.prepend(macro); - parsed->append(params); + parsed.append(params); } } return parsed; @@ -335,7 +335,7 @@ QMap ParseUtil::readNamedIndexCArray(QString filename, QString QRegularExpression re_text(QString(R"(\b%1\b\s*(\[?[^\]]*\])?\s*=\s*\{([^\}]*)\})").arg(label)); QString body = re_text.match(text).captured(2).replace(QRegularExpression("\\s*"), ""); - + QRegularExpression re("\\[(?[A-Za-z0-9_]*)\\]=(?&?[A-Za-z0-9_]*)"); QRegularExpressionMatchIterator iter = re.globalMatch(body); @@ -349,24 +349,23 @@ QMap ParseUtil::readNamedIndexCArray(QString filename, QString return map; } -QList* ParseUtil::getLabelMacros(QList *list, QString label) { +QList ParseUtil::getLabelMacros(const QList &list, const QString &label) { bool in_label = false; - QList *new_list = new QList; - for (int i = 0; i < list->length(); i++) { - QStringList params = list->value(i); - QString macro = params.value(0); + QList new_list; + for (const auto ¶ms : list) { + const QString macro = params.value(0); if (macro == ".label") { if (params.value(1) == label) { in_label = true; } else if (in_label) { // If nothing has been read yet, assume the label // we're looking for is in a stack of labels. - if (new_list->length() > 0) { + if (new_list.length() > 0) { break; } } } else if (in_label) { - new_list->append(params); + new_list.append(params); } } return new_list; @@ -374,17 +373,16 @@ QList* ParseUtil::getLabelMacros(QList *list, QString // For if you don't care about filtering by macro, // and just want all values associated with some label. -QStringList* ParseUtil::getLabelValues(QList *list, QString label) { - list = getLabelMacros(list, label); - QStringList *values = new QStringList; - for (int i = 0; i < list->length(); i++) { - QStringList params = list->value(i); - QString macro = params.value(0); +QStringList ParseUtil::getLabelValues(const QList &list, const QString &label) { + const QList labelMacros = getLabelMacros(list, label); + QStringList values; + for (const auto ¶ms : labelMacros) { + const QString macro = params.value(0); if (macro == ".align" || macro == ".ifdef" || macro == ".ifndef") { continue; } - for (int j = 1; j < params.length(); j++) { - values->append(params.value(j)); + for (int i = 1; i < params.length(); i++) { + values.append(params.value(i)); } } return values; diff --git a/src/project.cpp b/src/project.cpp index 1f49cf3e..7058cb95 100644 --- a/src/project.cpp +++ b/src/project.cpp @@ -1108,26 +1108,26 @@ bool Project::loadMapTilesets(Map* map) { } Tileset* Project::loadTileset(QString label, Tileset *tileset) { - QStringList *values = parser.getLabelValues(parser.parseAsm("data/tilesets/headers.inc"), label); - if (values->isEmpty()) { + const QStringList values = parser.getLabelValues(parser.parseAsm("data/tilesets/headers.inc"), label); + if (values.isEmpty()) { return nullptr; } if (tileset == nullptr) { tileset = new Tileset; } tileset->name = label; - tileset->is_compressed = values->value(0); - tileset->is_secondary = values->value(1); - tileset->padding = values->value(2); - tileset->tiles_label = values->value(3); - tileset->palettes_label = values->value(4); - tileset->metatiles_label = values->value(5); + tileset->is_compressed = values.value(0); + tileset->is_secondary = values.value(1); + tileset->padding = values.value(2); + tileset->tiles_label = values.value(3); + tileset->palettes_label = values.value(4); + tileset->metatiles_label = values.value(5); if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) { - tileset->callback_label = values->value(6); - tileset->metatile_attrs_label = values->value(7); + tileset->callback_label = values.value(6); + tileset->metatile_attrs_label = values.value(7); } else { - tileset->metatile_attrs_label = values->value(6); - tileset->callback_label = values->value(7); + tileset->metatile_attrs_label = values.value(6); + tileset->callback_label = values.value(7); } loadTilesetAssets(tileset); @@ -1450,15 +1450,15 @@ void Project::loadTilesetAssets(Tileset* tileset) { } QRegularExpression re("([a-z])([A-Z0-9])"); QString tilesetName = tileset->name; - QString dir_path = root + "/data/tilesets/" + category + "/" + tilesetName.replace("gTileset_", "").replace(re, "\\1_\\2").toLower(); + QString dir_path = root + "/data/tilesets/" + category + '/' + tilesetName.replace("gTileset_", "").replace(re, "\\1_\\2").toLower(); - QList *graphics = parser.parseAsm("data/tilesets/graphics.inc"); - QStringList *tiles_values = parser.getLabelValues(graphics, tileset->tiles_label); - QStringList *palettes_values = parser.getLabelValues(graphics, tileset->palettes_label); + const QList graphics = parser.parseAsm("data/tilesets/graphics.inc"); + const QStringList tiles_values = parser.getLabelValues(graphics, tileset->tiles_label); + const QStringList palettes_values = parser.getLabelValues(graphics, tileset->palettes_label); QString tiles_path; - if (!tiles_values->isEmpty()) { - tiles_path = root + "/" + tiles_values->value(0).section('"', 1, 1); + if (!tiles_values.isEmpty()) { + tiles_path = root + '/' + tiles_values.value(0).section('"', 1, 1); } else { tiles_path = dir_path + "/tiles.4bpp"; if (tileset->is_compressed == "TRUE") { @@ -1466,28 +1466,27 @@ void Project::loadTilesetAssets(Tileset* tileset) { } } - if (!palettes_values->isEmpty()) { - for (int i = 0; i < palettes_values->length(); i++) { - QString value = palettes_values->value(i); - tileset->palettePaths.append(this->fixPalettePath(root + "/" + value.section('"', 1, 1))); + if (!palettes_values.isEmpty()) { + for (const auto &value : palettes_values) { + tileset->palettePaths.append(this->fixPalettePath(root + '/' + value.section('"', 1, 1))); } } else { QString palettes_dir_path = dir_path + "/palettes"; for (int i = 0; i < 16; i++) { - tileset->palettePaths.append(palettes_dir_path + "/" + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".pal"); + tileset->palettePaths.append(palettes_dir_path + '/' + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".pal"); } } - QList *metatiles_macros = parser.parseAsm("data/tilesets/metatiles.inc"); - QStringList *metatiles_values = parser.getLabelValues(metatiles_macros, tileset->metatiles_label); - if (!metatiles_values->isEmpty()) { - tileset->metatiles_path = root + "/" + metatiles_values->value(0).section('"', 1, 1); + const QList metatiles_macros = parser.parseAsm("data/tilesets/metatiles.inc"); + const QStringList metatiles_values = parser.getLabelValues(metatiles_macros, tileset->metatiles_label); + if (!metatiles_values.isEmpty()) { + tileset->metatiles_path = root + '/' + metatiles_values.value(0).section('"', 1, 1); } else { tileset->metatiles_path = dir_path + "/metatiles.bin"; } - QStringList *metatile_attrs_values = parser.getLabelValues(metatiles_macros, tileset->metatile_attrs_label); - if (!metatile_attrs_values->isEmpty()) { - tileset->metatile_attrs_path = root + "/" + metatile_attrs_values->value(0).section('"', 1, 1); + const QStringList metatile_attrs_values = parser.getLabelValues(metatiles_macros, tileset->metatile_attrs_label); + if (!metatile_attrs_values.isEmpty()) { + tileset->metatile_attrs_path = root + '/' + metatile_attrs_values.value(0).section('"', 1, 1); } else { tileset->metatile_attrs_path = dir_path + "/metatile_attributes.bin"; } From fdd12cde25d8f6c0b76b4401c4752479cbd30de6 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Tue, 16 Feb 2021 07:15:47 -0500 Subject: [PATCH 29/46] Refactor ParseUtil to stop using pointers and output-parameters --- include/core/parseutil.h | 41 ++++++++--------- src/core/parseutil.cpp | 99 ++++++++++++++++++---------------------- src/project.cpp | 41 +++++++---------- 3 files changed, 81 insertions(+), 100 deletions(-) diff --git a/include/core/parseutil.h b/include/core/parseutil.h index 399f43fb..7c9b225e 100644 --- a/include/core/parseutil.h +++ b/include/core/parseutil.h @@ -39,31 +39,30 @@ public: class ParseUtil { public: - ParseUtil(); - void set_root(QString); - static QString readTextFile(QString); + ParseUtil() { }; + void set_root(const QString &dir); + static QString readTextFile(const QString &path); static int textFileLineCount(const QString &path); - void strip_comment(QString*); QList parseAsm(const QString &filename); - int evaluateDefine(QString, QMap*); - QStringList readCArray(QString text, QString label); - QMap readNamedIndexCArray(QString text, QString label); - QString readCIncbin(QString text, QString label); - QMap readCDefines(QString filename, QStringList prefixes, QMap = QMap()); - void readCDefinesSorted(QString, QStringList, QStringList*, QMap = QMap()); - QList getLabelMacros(const QList &, const QString &); - QStringList getLabelValues(const QList &, const QString &); - bool tryParseJsonFile(QJsonDocument *out, QString filepath); - bool ensureFieldsExist(QJsonObject obj, QList fields); + int evaluateDefine(const QString&, const QMap&); + QStringList readCArray(const QString &text, const QString &label); + QMap readNamedIndexCArray(const QString &text, const QString &label); + QString readCIncbin(const QString &text, const QString &label); + QMap readCDefines(const QString &filename, const QStringList &prefixes, QMap = { }); + QStringList readCDefinesSorted(const QString&, const QStringList&, const QMap& = { }); + QList getLabelMacros(const QList&, const QString&); + QStringList getLabelValues(const QList&, const QString&); + bool tryParseJsonFile(QJsonDocument *out, const QString &filepath); + bool ensureFieldsExist(const QJsonObject &obj, const QList &fields); // Returns the 1-indexed line number for the definition of scriptLabel in the scripts file at filePath. // Returns 0 if a definition for scriptLabel cannot be found. static int getScriptLineNumber(const QString &filePath, const QString &scriptLabel); static int getRawScriptLineNumber(QString text, const QString &scriptLabel); static int getPoryScriptLineNumber(QString text, const QString &scriptLabel); - static QString &removeStringLiterals(QString &text); - static QString &removeLineComments(QString &text, const QString &commentSymbol); - static QString &removeLineComments(QString &text, const QStringList &commentSymbols); + static QString removeStringLiterals(QString text); + static QString removeLineComments(QString text, const QString &commentSymbol); + static QString removeLineComments(QString text, const QStringList &commentSymbols); static QStringList splitShellCommand(QStringView command); @@ -71,10 +70,10 @@ private: QString root; QString text; QString file; - QList tokenizeExpression(QString expression, QMap* knownIdentifiers); - QList generatePostfix(QList tokens); - int evaluatePostfix(QList postfix); - void error(QString message, QString expression); + QList tokenizeExpression(QString expression, const QMap &knownIdentifiers); + QList generatePostfix(const QList &tokens); + int evaluatePostfix(const QList &postfix); + void error(const QString &message, const QString &expression); }; #endif // PARSEUTIL_H diff --git a/src/core/parseutil.cpp b/src/core/parseutil.cpp index cd053458..30ebe19c 100644 --- a/src/core/parseutil.cpp +++ b/src/core/parseutil.cpp @@ -6,15 +6,12 @@ #include #include -ParseUtil::ParseUtil() -{ -} -void ParseUtil::set_root(QString dir) { +void ParseUtil::set_root(const QString &dir) { this->root = dir; } -void ParseUtil::error(QString message, QString expression) { +void ParseUtil::error(const QString &message, const QString &expression) { QStringList lines = text.split(QRegularExpression("[\r\n]")); int lineNum = 0, colNum = 0; for (QString line : lines) { @@ -25,21 +22,7 @@ void ParseUtil::error(QString message, QString expression) { logError(QString("%1:%2:%3: %4").arg(file).arg(lineNum).arg(colNum).arg(message)); } -void ParseUtil::strip_comment(QString *line) { - bool in_string = false; - for (int i = 0; i < line->length(); i++) { - if (line->at(i) == '"') { - in_string = !in_string; - } else if (line->at(i) == '@') { - if (!in_string) { - line->truncate(i); - break; - } - } - } -} - -QString ParseUtil::readTextFile(QString path) { +QString ParseUtil::readTextFile(const QString &path) { QFile file(path); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Could not open '%1': ").arg(path) + file.errorString()); @@ -63,21 +46,23 @@ QList ParseUtil::parseAsm(const QString &filename) { QList parsed; text = readTextFile(root + '/' + filename); - const QStringList lines = text.split('\n'); - for (QString line : lines) { - strip_comment(&line); - if (line.trimmed().isEmpty()) { - } else if (line.contains(':')) { + const QStringList lines = removeLineComments(text, "@").split('\n'); + for (const auto &line : lines) { + const QString trimmedLine = line.trimmed(); + if (trimmedLine.isEmpty()) { + continue; + } + + if (line.contains(':')) { const QString label = line.left(line.indexOf(':')); const QStringList list{ ".label", label }; // .label is not a real keyword. It's used only to make the output more regular. parsed.append(list); // There should not be anything else on the line. // gas will raise a syntax error if there is. } else { - line = line.trimmed(); - int index = line.indexOf(QRegExp("\\s+")); - const QString macro = line.left(index); - QStringList params(line.right(line.length() - index).trimmed().split(QRegExp("\\s*,\\s*"))); + int index = trimmedLine.indexOf(QRegExp("\\s+")); + const QString macro = trimmedLine.left(index); + QStringList params(trimmedLine.right(trimmedLine.length() - index).trimmed().split(QRegExp("\\s*,\\s*"))); params.prepend(macro); parsed.append(params); } @@ -85,13 +70,13 @@ QList ParseUtil::parseAsm(const QString &filename) { return parsed; } -int ParseUtil::evaluateDefine(QString define, QMap* knownDefines) { +int ParseUtil::evaluateDefine(const QString &define, const QMap &knownDefines) { QList tokens = tokenizeExpression(define, knownDefines); QList postfixExpression = generatePostfix(tokens); return evaluatePostfix(postfixExpression); } -QList ParseUtil::tokenizeExpression(QString expression, QMap* knownIdentifiers) { +QList ParseUtil::tokenizeExpression(QString expression, const QMap &knownIdentifiers) { QList tokens; QStringList tokenTypes = (QStringList() << "hex" << "decimal" << "identifier" << "operator" << "leftparen" << "rightparen"); @@ -108,8 +93,8 @@ QList ParseUtil::tokenizeExpression(QString expression, QMapcontains(token)) { - QString actualToken = QString("%1").arg(knownIdentifiers->value(token)); + if (knownIdentifiers.contains(token)) { + QString actualToken = QString("%1").arg(knownIdentifiers.value(token)); expression = expression.replace(0, token.length(), actualToken); token = actualToken; tokenType = "decimal"; @@ -152,7 +137,7 @@ QMap Token::precedenceMap = QMap( // Shunting-yard algorithm for generating postfix notation. // https://en.wikipedia.org/wiki/Shunting-yard_algorithm -QList ParseUtil::generatePostfix(QList tokens) { +QList ParseUtil::generatePostfix(const QList &tokens) { QList output; QStack operatorStack; for (Token token : tokens) { @@ -194,7 +179,7 @@ QList ParseUtil::generatePostfix(QList tokens) { // Evaluate postfix expression. // https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_evaluation_algorithm -int ParseUtil::evaluatePostfix(QList postfix) { +int ParseUtil::evaluatePostfix(const QList &postfix) { QStack stack; for (Token token : postfix) { if (token.type == TokenClass::Operator && stack.size() > 1) { @@ -228,7 +213,7 @@ int ParseUtil::evaluatePostfix(QList postfix) { return stack.size() ? stack.pop().value.toInt(nullptr, 0) : 0; } -QString ParseUtil::readCIncbin(QString filename, QString label) { +QString ParseUtil::readCIncbin(const QString &filename, const QString &label) { QString path; if (label.isNull()) { @@ -251,7 +236,10 @@ QString ParseUtil::readCIncbin(QString filename, QString label) { return path; } -QMap ParseUtil::readCDefines(QString filename, QStringList prefixes, QMap allDefines) { +QMap ParseUtil::readCDefines(const QString &filename, + const QStringList &prefixes, + QMap allDefines) +{ QMap filteredDefines; file = filename; @@ -280,7 +268,7 @@ QMap ParseUtil::readCDefines(QString filename, QStringList prefixe QString name = match.captured("defineName"); QString expression = match.captured("defineValue"); if (expression == " ") continue; - int value = evaluateDefine(expression, &allDefines); + int value = evaluateDefine(expression, allDefines); allDefines.insert(name, value); for (QString prefix : prefixes) { if (name.startsWith(prefix) || QRegularExpression(prefix).match(name).hasMatch()) { @@ -291,7 +279,10 @@ QMap ParseUtil::readCDefines(QString filename, QStringList prefixe return filteredDefines; } -void ParseUtil::readCDefinesSorted(QString filename, QStringList prefixes, QStringList* definesToSet, QMap knownDefines) { +QStringList ParseUtil::readCDefinesSorted(const QString &filename, + const QStringList &prefixes, + const QMap &knownDefines) +{ QMap defines = readCDefines(filename, prefixes, knownDefines); // The defines should to be sorted by their underlying value, not alphabetically. @@ -300,10 +291,10 @@ void ParseUtil::readCDefinesSorted(QString filename, QStringList prefixes, QStri for (QString defineName : defines.keys()) { definesInverse.insert(defines[defineName], defineName); } - *definesToSet = definesInverse.values(); + return definesInverse.values(); } -QStringList ParseUtil::readCArray(QString filename, QString label) { +QStringList ParseUtil::readCArray(const QString &filename, const QString &label) { QStringList list; if (label.isNull()) { @@ -329,7 +320,7 @@ QStringList ParseUtil::readCArray(QString filename, QString label) { return list; } -QMap ParseUtil::readNamedIndexCArray(QString filename, QString label) { +QMap ParseUtil::readNamedIndexCArray(const QString &filename, const QString &label) { text = readTextFile(root + "/" + filename); QMap map; @@ -388,16 +379,16 @@ QStringList ParseUtil::getLabelValues(const QList &list, const QStr return values; } -bool ParseUtil::tryParseJsonFile(QJsonDocument *out, QString filepath) { +bool ParseUtil::tryParseJsonFile(QJsonDocument *out, const QString &filepath) { QFile file(filepath); if (!file.open(QIODevice::ReadOnly)) { logError(QString("Error: Could not open %1 for reading").arg(filepath)); return false; } - QByteArray data = file.readAll(); + const QByteArray data = file.readAll(); QJsonParseError parseError; - QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError); + const QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError); file.close(); if (parseError.error != QJsonParseError::NoError) { logError(QString("Error: Failed to parse json file %1: %2").arg(filepath).arg(parseError.errorString())); @@ -408,7 +399,7 @@ bool ParseUtil::tryParseJsonFile(QJsonDocument *out, QString filepath) { return true; } -bool ParseUtil::ensureFieldsExist(QJsonObject obj, QList fields) { +bool ParseUtil::ensureFieldsExist(const QJsonObject &obj, const QList &fields) { for (QString field : fields) { if (!obj.contains(field)) { logError(QString("JSON object is missing field '%1'.").arg(field)); @@ -431,8 +422,8 @@ int ParseUtil::getScriptLineNumber(const QString &filePath, const QString &scrip } int ParseUtil::getRawScriptLineNumber(QString text, const QString &scriptLabel) { - removeStringLiterals(text); - removeLineComments(text, "@"); + text = removeStringLiterals(text); + text = removeLineComments(text, "@"); static const QRegularExpression re_incScriptLabel("\\b(?