From 42b56edc9d394c8b86c739d8362e0dde2a68d2bf Mon Sep 17 00:00:00 2001 From: BigBahss Date: Sun, 14 Feb 2021 15:10:03 -0500 Subject: [PATCH 01/11] 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 02/11] 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 03/11] 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 04/11] 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 05/11] 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 820b514f26ae9c089b1b84d6ff4a4e7f6e2e9cc6 Mon Sep 17 00:00:00 2001 From: BigBahss Date: Mon, 15 Feb 2021 04:21:41 -0500 Subject: [PATCH 06/11] 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 07/11] 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 08/11] 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 09/11] 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 10/11] 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 11/11] 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(?