Compare commits

...

2 commits

Author SHA1 Message Date
Marcus Huderle
57051b7a4a [clang-format] Format source code 2021-02-17 18:20:14 -06:00
Marcus Huderle
3d50732b80 Create .clang-format 2021-02-17 18:19:24 -06:00
138 changed files with 5763 additions and 6416 deletions

66
.clang-format Normal file
View file

@ -0,0 +1,66 @@
---
Language: Cpp
# BasedOnStyle: WebKit
AccessModifierOffset: -4
AlignAfterOpenBracket: false
AlignConsecutiveAssignments: false
AlignEscapedNewlinesLeft: false
AlignOperands: false
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 160
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
...

View file

@ -15,13 +15,13 @@ enum MapSortOrder {
Layout = 2,
};
class KeyValueConfigBase : public QObject
{
class KeyValueConfigBase : public QObject {
public:
void save();
void load();
virtual ~KeyValueConfigBase();
virtual void reset() = 0;
protected:
virtual QString getConfigFilepath() = 0;
virtual void parseConfigKeyValue(QString key, QString value) = 0;
@ -30,8 +30,7 @@ protected:
virtual void setUnreadKeys() = 0;
};
class PorymapConfig: public KeyValueConfigBase
{
class PorymapConfig : public KeyValueConfigBase {
public:
PorymapConfig() {
reset();
@ -82,12 +81,14 @@ public:
QString getTheme();
QString getTextEditorOpenFolder();
QString getTextEditorGotoLine();
protected:
virtual QString getConfigFilepath() override;
virtual void parseConfigKeyValue(QString key, QString value) override;
virtual QMap<QString, QString> getKeyValueMap() override;
virtual void onNewConfigFileCreated() override{};
virtual void setUnreadKeys() override{};
private:
QString recentProject;
QString stringFromByteArray(QByteArray);
@ -124,8 +125,7 @@ enum BaseGameVersion {
pokeemerald,
};
class ProjectConfig: public KeyValueConfigBase
{
class ProjectConfig : public KeyValueConfigBase {
public:
ProjectConfig() {
reset();
@ -176,12 +176,14 @@ public:
bool getTripleLayerMetatilesEnabled();
void setCustomScripts(QList<QString> scripts);
QList<QString> getCustomScripts();
protected:
virtual QString getConfigFilepath() override;
virtual void parseConfigKeyValue(QString key, QString value) override;
virtual QMap<QString, QString> getKeyValueMap() override;
virtual void onNewConfigFileCreated() override;
virtual void setUnreadKeys() override;
private:
BaseGameVersion baseGameVersion;
QString projectDir;
@ -206,15 +208,14 @@ extern ProjectConfig projectConfig;
class QAction;
class Shortcut;
class ShortcutsConfig : public KeyValueConfigBase
{
class ShortcutsConfig : public KeyValueConfigBase {
public:
ShortcutsConfig() :
user_shortcuts({ }),
default_shortcuts({ })
{ }
ShortcutsConfig() : user_shortcuts({}), default_shortcuts({}) {
}
virtual void reset() override { user_shortcuts.clear(); }
virtual void reset() override {
user_shortcuts.clear();
}
// Call this before applying user shortcuts so that the user can restore defaults.
void setDefaultShortcuts(const QObjectList& objects);
@ -235,19 +236,13 @@ private:
QMultiMap<QString, QKeySequence> user_shortcuts;
QMultiMap<QString, QKeySequence> default_shortcuts;
enum StoreType {
User,
Default
};
enum StoreType { User, Default };
QString cfgKey(const QObject* object) const;
QList<QKeySequence> currentShortcuts(const QObject* object) const;
void storeShortcutsFromList(StoreType storeType, const QObjectList& objects);
void storeShortcuts(
StoreType storeType,
const QString &cfgKey,
const QList<QKeySequence> &keySequences);
void storeShortcuts(StoreType storeType, const QString& cfgKey, const QList<QKeySequence>& keySequences);
};
extern ShortcutsConfig shortcutsConfig;

View file

@ -4,8 +4,7 @@
#include <QObject>
class Block
{
class Block {
public:
Block();
Block(uint16_t);

View file

@ -7,8 +7,7 @@
#include <QByteArray>
#include <QVector>
class Blockdata : public QVector<Block>
{
class Blockdata : public QVector<Block> {
public:
QByteArray serialize() const;
};

View file

@ -42,15 +42,15 @@ enum CommandId {
/// onto the map using the pencil tool.
class PaintMetatile : public QUndoCommand {
public:
PaintMetatile(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent = nullptr);
PaintMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand* command) override;
int id() const override { return CommandId::ID_PaintMetatile; }
int id() const override {
return CommandId::ID_PaintMetatile;
}
private:
Map* map;
@ -61,36 +61,34 @@ private:
unsigned actionId;
};
/// Implements a command to commit paint actions
/// on the metatile collision and elevation.
class PaintCollision : public PaintMetatile {
public:
PaintCollision(Map *map,
const Blockdata &oldCollision, const Blockdata &newCollision,
unsigned actionId, QUndoCommand *parent = nullptr)
PaintCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, unsigned actionId, QUndoCommand* parent = nullptr)
: PaintMetatile(map, oldCollision, newCollision, actionId, parent) {
setText("Paint Collision");
}
int id() const override { return CommandId::ID_PaintCollision; }
int id() const override {
return CommandId::ID_PaintCollision;
}
};
/// Implements a command to commit paint actions on the map border.
class PaintBorder : public QUndoCommand {
public:
PaintBorder(Map *map,
const Blockdata &oldBorder, const Blockdata &newBorder,
unsigned actionId, QUndoCommand *parent = nullptr);
PaintBorder(Map* map, const Blockdata& oldBorder, const Blockdata& newBorder, unsigned actionId, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; };
int id() const override { return CommandId::ID_PaintBorder; }
bool mergeWith(const QUndoCommand*) override {
return false;
};
int id() const override {
return CommandId::ID_PaintBorder;
}
private:
Map* map;
@ -101,85 +99,79 @@ private:
unsigned actionId;
};
/// Implements a command to commit flood fill metatile actions
/// with the bucket tool onto the map.
class BucketFillMetatile : public PaintMetatile {
public:
BucketFillMetatile(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent = nullptr)
BucketFillMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr)
: PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) {
setText("Bucket Fill Metatiles");
}
int id() const override { return CommandId::ID_BucketFillMetatile; }
int id() const override {
return CommandId::ID_BucketFillMetatile;
}
};
/// Implements a command to commit flood fill actions
/// on the metatile collision and elevation.
class BucketFillCollision : public PaintCollision {
public:
BucketFillCollision(Map *map,
const Blockdata &oldCollision, const Blockdata &newCollision,
QUndoCommand *parent = nullptr)
BucketFillCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, QUndoCommand* parent = nullptr)
: PaintCollision(map, oldCollision, newCollision, -1, parent) {
setText("Flood Fill Collision");
}
bool mergeWith(const QUndoCommand *) override { return false; }
int id() const override { return CommandId::ID_BucketFillCollision; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override {
return CommandId::ID_BucketFillCollision;
}
};
/// Implements a command to commit magic fill metatile actions
/// with the bucket or paint tool onto the map.
class MagicFillMetatile : public PaintMetatile {
public:
MagicFillMetatile(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent = nullptr)
MagicFillMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr)
: PaintMetatile(map, oldMetatiles, newMetatiles, actionId, parent) {
setText("Magic Fill Metatiles");
}
int id() const override { return CommandId::ID_MagicFillMetatile; }
int id() const override {
return CommandId::ID_MagicFillMetatile;
}
};
/// Implements a command to commit magic fill collision actions.
class MagicFillCollision : public PaintCollision {
public:
MagicFillCollision(Map *map,
const Blockdata &oldCollision, const Blockdata &newCollision,
QUndoCommand *parent = nullptr)
MagicFillCollision(Map* map, const Blockdata& oldCollision, const Blockdata& newCollision, QUndoCommand* parent = nullptr)
: PaintCollision(map, oldCollision, newCollision, -1, parent) {
setText("Magic Fill Collision");
}
bool mergeWith(const QUndoCommand *) override { return false; }
int id() const override { return CommandId::ID_MagicFillCollision; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override {
return CommandId::ID_MagicFillCollision;
}
};
/// Implements a command to commit metatile shift actions.
class ShiftMetatiles : public QUndoCommand {
public:
ShiftMetatiles(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent = nullptr);
ShiftMetatiles(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand* command) override;
int id() const override { return CommandId::ID_ShiftMetatiles; }
int id() const override {
return CommandId::ID_ShiftMetatiles;
}
private:
Map* map;
@ -190,22 +182,21 @@ private:
unsigned actionId;
};
/// Implements a command to commit a map or border resize action.
class ResizeMap : public QUndoCommand {
public:
ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
QSize oldBorderDimensions, QSize newBorderDimensions,
const Blockdata &oldBorder, const Blockdata &newBorder,
QUndoCommand *parent = nullptr);
ResizeMap(Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QSize oldBorderDimensions,
QSize newBorderDimensions, const Blockdata& oldBorder, const Blockdata& newBorder, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; }
int id() const override { return CommandId::ID_ResizeMap; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override {
return CommandId::ID_ResizeMap;
}
private:
Map* map;
@ -227,15 +218,11 @@ private:
Blockdata oldBorder;
};
/// Implements a command to commit a single- or multi-Event move action.
/// Actions are merged into one until the mouse is released.
class EventMove : public QUndoCommand {
public:
EventMove(QList<Event *> events,
int deltaX, int deltaY, unsigned actionId,
QUndoCommand *parent = nullptr);
EventMove(QList<Event*> events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
@ -251,32 +238,28 @@ private:
unsigned actionId;
};
/// Implements a command to commit Event shift actions.
class EventShift : public EventMove {
public:
EventShift(QList<Event *> events,
int deltaX, int deltaY, unsigned actionId,
QUndoCommand *parent = nullptr);
EventShift(QList<Event*> events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent = nullptr);
int id() const override;
private:
QList<Event*> events;
};
/// Implements a command to commit Event create actions.
/// Works for a single Event only.
class EventCreate : public QUndoCommand {
public:
EventCreate(Editor *editor, Map *map, Event *event,
QUndoCommand *parent = nullptr);
EventCreate(Editor* editor, Map* map, Event* event, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override;
private:
@ -285,20 +268,18 @@ private:
Editor* editor;
};
/// Implements a command to commit Event deletions.
/// Applies to every currently selected Event.
class EventDelete : public QUndoCommand {
public:
EventDelete(Editor *editor, Map *map,
QList<Event *> selectedEvents, Event *nextSelectedEvent,
QUndoCommand *parent = nullptr);
EventDelete(Editor* editor, Map* map, QList<Event*> selectedEvents, Event* nextSelectedEvent, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override;
private:
@ -308,18 +289,17 @@ private:
Event* nextSelectedEvent;
};
/// Implements a command to commit Event duplications.
class EventDuplicate : public QUndoCommand {
public:
EventDuplicate(Editor *editor, Map *map, QList<Event *> selectedEvents,
QUndoCommand *parent = nullptr);
EventDuplicate(Editor* editor, Map* map, QList<Event*> selectedEvents, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override;
private:
@ -328,22 +308,22 @@ private:
Editor* editor;
};
/// Implements a command to commit map edits from the scripting API.
/// The scripting api can edit metatiles and map dimensions.
class ScriptEditMap : public QUndoCommand {
public:
ScriptEditMap(Map *map,
QSize oldMapDimensions, QSize newMapDimensions,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
QUndoCommand *parent = nullptr);
ScriptEditMap(
Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
bool mergeWith(const QUndoCommand *) override { return false; }
int id() const override { return CommandId::ID_ScriptEditMap; }
bool mergeWith(const QUndoCommand*) override {
return false;
}
int id() const override {
return CommandId::ID_ScriptEditMap;
}
private:
Map* map;

View file

@ -10,8 +10,7 @@
using OrderedJson = poryjson::Json;
class EventType
{
class EventType {
public:
static QString Object;
static QString Warp;
@ -25,12 +24,12 @@ public:
class DraggablePixmapItem;
class Project;
class Event
{
class Event {
public:
Event();
Event(const Event&);
Event(QJsonObject, QString);
public:
int x() const {
return getInt("x");
@ -101,7 +100,9 @@ public:
bool usingSprite;
DraggablePixmapItem* pixmapItem = nullptr;
void setPixmapItem(DraggablePixmapItem *item) { pixmapItem = item; }
void setPixmapItem(DraggablePixmapItem* item) {
pixmapItem = item;
}
};
#endif // EVENT_H

View file

@ -4,10 +4,10 @@
#include <QList>
template <typename T>
class History {
template <typename T> class History {
public:
History() { }
History() {
}
T back() {
if (head > 0) {
return history.at(--head);

View file

@ -25,8 +25,7 @@ class MapPixmapItem;
class CollisionPixmapItem;
class BorderMetatilesPixmapItem;
class Map : public QObject
{
class Map : public QObject {
Q_OBJECT
public:
explicit Map(QObject* parent = nullptr);
@ -99,13 +98,19 @@ public:
QVector<Event*> ownedEvents;
MapPixmapItem* mapItem = nullptr;
void setMapItem(MapPixmapItem *item) { mapItem = item; }
void setMapItem(MapPixmapItem* item) {
mapItem = item;
}
CollisionPixmapItem* collisionItem = nullptr;
void setCollisionItem(CollisionPixmapItem *item) { collisionItem = item; }
void setCollisionItem(CollisionPixmapItem* item) {
collisionItem = item;
}
BorderMetatilesPixmapItem* borderItem = nullptr;
void setBorderItem(BorderMetatilesPixmapItem *item) { borderItem = item; }
void setBorderItem(BorderMetatilesPixmapItem* item) {
borderItem = item;
}
QUndoStack editHistory;

View file

@ -10,7 +10,8 @@
class MapLayout {
public:
MapLayout() {}
MapLayout() {
}
static QString layoutConstantFromName(QString mapName);
QString id;
QString name;

View file

@ -7,8 +7,7 @@
#include <QPoint>
#include <QString>
class Metatile
{
class Metatile {
public:
Metatile();
Metatile(const Metatile& other) = default;

View file

@ -6,8 +6,7 @@
#include <QList>
#include <QString>
class MetatileParser
{
class MetatileParser {
public:
MetatileParser();
QList<Metatile*> parse(QString filepath, bool* error, bool primaryTileset);

View file

@ -6,12 +6,12 @@
#include <QRgb>
#include <QString>
class PaletteUtil
{
class PaletteUtil {
public:
PaletteUtil();
QList<QRgb> parse(QString filepath, bool* error);
void writeJASC(QString filepath, QVector<QRgb> colors, int offset, int nColors);
private:
QList<QRgb> parsePal(QString filepath, bool* error);
QList<QRgb> parseJASC(QString filepath, bool* error);

View file

@ -36,8 +36,7 @@ public:
int operatorPrecedence; // only relevant for operator tokens
};
class ParseUtil
{
class ParseUtil {
public:
ParseUtil(){};
void set_root(const QString& dir);

View file

@ -38,11 +38,11 @@ public:
this->mapWidth = width;
this->mapHeight = height;
}
~RegionMapHistoryItem() {}
~RegionMapHistoryItem() {
}
};
class RegionMapEntry
{
class RegionMapEntry {
public:
RegionMapEntry() = default;
RegionMapEntry(int x_, int y_, int width_, int height_, QString name_) {
@ -64,8 +64,7 @@ public:
void setHeight(int);
};
class RegionMapSquare
{
class RegionMapSquare {
public:
int x = -1;
int y = -1;
@ -79,8 +78,7 @@ public:
QString city_map_name;
};
class RegionMap : public QObject
{
class RegionMap : public QObject {
Q_OBJECT
public:

View file

@ -2,23 +2,13 @@
#ifndef TILE_H
#define TILE_H
class Tile
{
class Tile {
public:
Tile() :
tile(0),
xflip(false),
yflip(false),
palette(0)
{ }
Tile() : tile(0), xflip(false), yflip(false), palette(0) {
}
Tile(int tile, bool xflip, bool yflip, int palette) :
tile(tile),
xflip(xflip),
yflip(yflip),
palette(palette)
{ }
Tile(int tile, bool xflip, bool yflip, int palette) : tile(tile), xflip(xflip), yflip(yflip), palette(palette) {
}
public:
int tile;

View file

@ -6,8 +6,7 @@
#include "tile.h"
#include <QImage>
class Tileset
{
class Tileset {
public:
Tileset() = default;
Tileset(const Tileset& other) = default;

View file

@ -29,8 +29,7 @@
class DraggablePixmapItem;
class MetatilesPixmapItem;
class Editor : public QObject
{
class Editor : public QObject {
Q_OBJECT
public:
Editor(Ui::MainWindow* ui);
@ -176,9 +175,7 @@ private:
QString getMovementPermissionText(uint16_t collision, uint16_t elevation);
QString getMetatileDisplayMessage(uint16_t metatileId);
bool eventLimitReached(Map*, QString);
bool startDetachedProcess(const QString &command,
const QString &workingDirectory = QString(),
qint64 *pid = nullptr) const;
bool startDetachedProcess(const QString& command, const QString& workingDirectory = QString(), qint64* pid = nullptr) const;
private slots:
void onMapStartPaint(QGraphicsSceneMouseEvent* event, MapPixmapItem* item);

View file

@ -81,18 +81,14 @@
namespace poryjson {
enum JsonParse {
STANDARD, COMMENTS
};
enum JsonParse { STANDARD, COMMENTS };
class JsonValue;
class Json final {
public:
// Types
enum Type {
NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT
};
enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT };
// Array and object typedefs
typedef QVector<Json> array;
@ -113,21 +109,23 @@ public:
Json(object&& values); // OBJECT
// Implicit constructor: anything with a to_json() function.
template <class T, class = decltype(&T::to_json)>
Json(const T & t) : Json(t.to_json()) {}
template <class T, class = decltype(&T::to_json)> Json(const T& t) : Json(t.to_json()) {
}
// Implicit constructor: map-like objects (std::map, std::unordered_map, etc)
template <class M, typename std::enable_if<
std::is_constructible<QString, decltype(std::declval<M>().begin()->first)>::value
template <class M, typename std::enable_if<std::is_constructible<QString, decltype(std::declval<M>().begin()->first)>::value
&& std::is_constructible<Json, decltype(std::declval<M>().begin()->second)>::value,
int>::type = 0>
Json(const M & m) : Json(object(m.begin(), m.end())) {}
int>::type
= 0>
Json(const M& m)
: Json(object(m.begin(), m.end())) {
}
// Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc)
template <class V, typename std::enable_if<
std::is_constructible<Json, decltype(*std::declval<V>().begin())>::value,
int>::type = 0>
Json(const V & v) : Json(array(v.begin(), v.end())) {}
template <class V, typename std::enable_if<std::is_constructible<Json, decltype(*std::declval<V>().begin())>::value, int>::type = 0>
Json(const V& v)
: Json(array(v.begin(), v.end())) {
}
// This prevents Json(some_pointer) from accidentally producing a bool. Use
// Json(bool(some_pointer)) if that behavior is desired.
@ -136,12 +134,24 @@ public:
// Accessors
Type type() const;
bool is_null() const { return type() == NUL; }
bool is_number() const { return type() == NUMBER; }
bool is_bool() const { return type() == BOOL; }
bool is_string() const { return type() == STRING; }
bool is_array() const { return type() == ARRAY; }
bool is_object() const { return type() == OBJECT; }
bool is_null() const {
return type() == NUL;
}
bool is_number() const {
return type() == NUMBER;
}
bool is_bool() const {
return type() == BOOL;
}
bool is_string() const {
return type() == STRING;
}
bool is_array() const {
return type() == ARRAY;
}
bool is_object() const {
return type() == OBJECT;
}
// Return the enclosed value if this is a number, 0 otherwise. Note that poryjson does not
// distinguish between integer and non-integer numbers - number_value() and int_value()
@ -176,12 +186,8 @@ public:
}
// Parse. If parse fails, return Json() and assign an error message to err.
static Json parse(const QString & in,
QString & err,
JsonParse strategy = JsonParse::STANDARD);
static Json parse(const char * in,
QString & err,
JsonParse strategy = JsonParse::STANDARD) {
static Json parse(const QString& in, QString& err, JsonParse strategy = JsonParse::STANDARD);
static Json parse(const char* in, QString& err, JsonParse strategy = JsonParse::STANDARD) {
if (in) {
return parse(QString(in), err, strategy);
} else {
@ -192,10 +198,18 @@ public:
bool operator==(const Json& rhs) const;
bool operator<(const Json& rhs) const;
bool operator!= (const Json &rhs) const { return !(*this == rhs); }
bool operator<= (const Json &rhs) const { return !(rhs < *this); }
bool operator> (const Json &rhs) const { return (rhs < *this); }
bool operator>= (const Json &rhs) const { return !(*this < rhs); }
bool operator!=(const Json& rhs) const {
return !(*this == rhs);
}
bool operator<=(const Json& rhs) const {
return !(rhs < *this);
}
bool operator>(const Json& rhs) const {
return (rhs < *this);
}
bool operator>=(const Json& rhs) const {
return !(*this < rhs);
}
private:
std::shared_ptr<JsonValue> m_ptr;
@ -237,7 +251,8 @@ protected:
virtual const Json& operator[](int i) const;
virtual const Json::object& object_items() const;
virtual const Json& operator[](const QString& key) const;
virtual ~JsonValue() {}
virtual ~JsonValue() {
}
};
} // namespace poryjson

File diff suppressed because it is too large Load diff

View file

@ -29,8 +29,7 @@ namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
class MainWindow : public QMainWindow {
Q_OBJECT
public:

View file

@ -21,8 +21,7 @@
static QString NONE_MAP_CONSTANT = "MAP_NONE";
static QString NONE_MAP_NAME = "None";
class Project : public QObject
{
class Project : public QObject {
Q_OBJECT
public:
Project(QWidget* parent = nullptr);
@ -31,7 +30,9 @@ public:
Project(const Project&) = delete;
Project& operator=(const Project&) = delete;
inline QWidget *parentWidget() const { return static_cast<QWidget *>(parent()); }
inline QWidget* parentWidget() const {
return static_cast<QWidget*>(parent());
}
public:
QString root;
@ -76,8 +77,7 @@ public:
void clearMapCache();
void clearTilesetCache();
struct DataQualifiers
{
struct DataQualifiers {
bool isStatic;
bool isConst;
};

View file

@ -15,8 +15,7 @@ enum CallbackType {
OnMapOpened,
};
class Scripting
{
class Scripting {
public:
Scripting(MainWindow* mainWindow);
static QJSValue fromBlock(Block block);

View file

@ -4,8 +4,7 @@
#include <QCursor>
class Settings
{
class Settings {
public:
Settings();
bool smartPathsEnabled;

View file

@ -7,11 +7,11 @@ namespace Ui {
class AboutPorymap;
}
class AboutPorymap : public QMainWindow
{
class AboutPorymap : public QMainWindow {
public:
explicit AboutPorymap(QWidget* parent = nullptr);
~AboutPorymap();
private:
Ui::AboutPorymap* ui;
};

View file

@ -3,14 +3,12 @@
#include <QStackedWidget>
class AdjustingStackedWidget : public QStackedWidget
{
class AdjustingStackedWidget : public QStackedWidget {
Q_OBJECT
public:
AdjustingStackedWidget(QWidget *parent = nullptr) : QStackedWidget(parent) {}
AdjustingStackedWidget(QWidget* parent = nullptr) : QStackedWidget(parent) {
}
// override this to allow the stacked widget's current page to dictate size
virtual void setCurrentIndex(int index) {

View file

@ -19,6 +19,7 @@ public:
void draw();
signals:
void borderMetatilesChanged();
protected:
void mousePressEvent(QGraphicsSceneMouseEvent*);
};

View file

@ -10,7 +10,8 @@
class CollisionPixmapItem : public MapPixmapItem {
Q_OBJECT
public:
CollisionPixmapItem(Map *map, MovementPermissionsSelector *movementPermissionsSelector, MetatileSelector *metatileSelector, Settings *settings, qreal *opacity)
CollisionPixmapItem(
Map* map, MovementPermissionsSelector* movementPermissionsSelector, MetatileSelector* metatileSelector, Settings* settings, qreal* opacity)
: MapPixmapItem(map, metatileSelector, settings) {
this->movementPermissionsSelector = movementPermissionsSelector;
this->opacity = opacity;

View file

@ -16,7 +16,9 @@ public:
MetatileSelector* metatileSelector;
void draw();
void setMap(Map *map) { this->map = map; }
void setMap(Map* map) {
this->map = map;
}
};
#endif // CURRENTSELECTEDMETATILESPIXMAPITEM_H

View file

@ -5,12 +5,10 @@
#include <QPainter>
#include <QRgb>
class CursorTileRect : public QGraphicsItem
{
class CursorTileRect : public QGraphicsItem {
public:
CursorTileRect(bool* enabled, QRgb color);
QRectF boundingRect() const override
{
QRectF boundingRect() const override {
int width = this->width;
int height = this->height;
if (this->singleTileMode) {
@ -21,15 +19,12 @@ public:
height = 32;
}
qreal penWidth = 4;
return QRectF(-penWidth,
-penWidth,
width + penWidth * 2,
height + penWidth * 2);
return QRectF(-penWidth, -penWidth, width + penWidth * 2, height + penWidth * 2);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
{
if (!(*enabled)) return;
void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override {
if (!(*enabled))
return;
int width = this->width;
int height = this->height;
if (this->singleTileMode) {
@ -51,15 +46,20 @@ public:
void initRightClickSelectionAnchor(int coordX, int coordY);
void stopRightClickSelectionAnchor();
void setSmartPathMode(bool enable);
bool getSmartPathMode() { return this->smartPathMode; }
bool getSmartPathMode() {
return this->smartPathMode;
}
void setStraightPathMode(bool enable);
bool getStraightPathMode() { return this->straightPathMode; }
bool getStraightPathMode() {
return this->straightPathMode;
}
void setSingleTileMode();
void stopSingleTileMode();
void updateLocation(int x, int y);
void updateSelectionSize(int width, int height);
void setVisibility(bool visible);
bool* enabled;
private:
bool visible;
int width;
@ -77,5 +77,4 @@ private:
bool smartPathInEffect();
};
#endif // CURSORTILERECT_H

View file

@ -6,8 +6,7 @@
#include <QFrame>
#include <QTableWidget>
class CustomAttributesTable : public QFrame
{
class CustomAttributesTable : public QFrame {
public:
explicit CustomAttributesTable(Event* event, QWidget* parent = nullptr);
~CustomAttributesTable();

View file

@ -15,7 +15,8 @@ class Editor;
class DraggablePixmapItem : public QObject, public QGraphicsPixmapItem {
Q_OBJECT
public:
DraggablePixmapItem(QPixmap pixmap): QGraphicsPixmapItem(pixmap) {}
DraggablePixmapItem(QPixmap pixmap) : QGraphicsPixmapItem(pixmap) {
}
DraggablePixmapItem(Event* event_, Editor* editor_) : QGraphicsPixmapItem(event_->pixmap) {
event = event_;

View file

@ -9,8 +9,7 @@ namespace Ui {
class EventPropertiesFrame;
}
class EventPropertiesFrame : public QFrame
{
class EventPropertiesFrame : public QFrame {
Q_OBJECT
public:

View file

@ -3,15 +3,14 @@
#include <QSortFilterProxyModel>
class FilterChildrenProxyModel : public QSortFilterProxyModel
{
class FilterChildrenProxyModel : public QSortFilterProxyModel {
Q_OBJECT
public:
explicit FilterChildrenProxyModel(QObject* parent = nullptr);
protected:
bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const;
};
#endif // FILTERCHILDRENPROXYMODEL_H

View file

@ -4,9 +4,7 @@
#include <QLayout>
#include <QStyle>
class FlowLayout : public QLayout
{
class FlowLayout : public QLayout {
public:
explicit FlowLayout(QWidget* parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);
explicit FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);

View file

@ -7,16 +7,18 @@
class Editor;
class GraphicsView : public QGraphicsView
{
class GraphicsView : public QGraphicsView {
public:
GraphicsView() : QGraphicsView() {}
GraphicsView(QWidget *parent) : QGraphicsView(parent) {}
GraphicsView() : QGraphicsView() {
}
GraphicsView(QWidget* parent) : QGraphicsView(parent) {
}
public:
// GraphicsView_Object object;
Editor* editor;
Overlay overlay;
protected:
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);

View file

@ -14,21 +14,8 @@ QImage getPalettedTileImage(uint16_t, Tileset*, Tileset*, int, bool useTruePalet
QImage getGreyscaleTileImage(uint16_t tile, Tileset* primaryTileset, Tileset* secondaryTileset);
static QList<QRgb> greyscalePalette({
qRgb(0, 0, 0),
qRgb(16, 16, 16),
qRgb(32, 32, 32),
qRgb(48, 48, 48),
qRgb(64, 64, 64),
qRgb(80, 80, 80),
qRgb(96, 96, 96),
qRgb(112, 112, 112),
qRgb(128, 128, 128),
qRgb(144, 144, 144),
qRgb(160, 160, 160),
qRgb(176, 176, 176),
qRgb(192, 192, 192),
qRgb(208, 208, 208),
qRgb(224, 224, 224),
qRgb(0, 0, 0), qRgb(16, 16, 16), qRgb(32, 32, 32), qRgb(48, 48, 48), qRgb(64, 64, 64), qRgb(80, 80, 80), qRgb(96, 96, 96), qRgb(112, 112, 112),
qRgb(128, 128, 128), qRgb(144, 144, 144), qRgb(160, 160, 160), qRgb(176, 176, 176), qRgb(192, 192, 192), qRgb(208, 208, 208), qRgb(224, 224, 224),
qRgb(240, 240, 240),
});

View file

@ -16,8 +16,7 @@ enum ImageExporterMode {
Timelapse,
};
class MapImageExporter : public QDialog
{
class MapImageExporter : public QDialog {
Q_OBJECT
public:

View file

@ -13,11 +13,7 @@ private:
using QGraphicsPixmapItem::paint;
public:
enum class PaintMode {
Disabled,
Metatiles,
EventObjects
};
enum class PaintMode { Disabled, Metatiles, EventObjects };
MapPixmapItem(Map* map_, MetatileSelector* metatileSelector, Settings* settings) {
this->map = map_;
this->map->setMapItem(this);
@ -40,11 +36,7 @@ public:
bool prevStraightPathState;
int straight_path_initial_x;
int straight_path_initial_y;
enum Axis {
None = 0,
X,
Y
};
enum Axis { None = 0, X, Y };
MapPixmapItem::Axis lockedAxis;
QPoint selection_origin;
QList<QPoint> selection;
@ -53,21 +45,12 @@ public:
virtual void magicFill(QGraphicsSceneMouseEvent*);
void magicFill(int x, int y, uint16_t metatileId, bool fromScriptCall = false);
void magicFill(int x, int y, bool fromScriptCall = false);
void magicFill(
int initialX,
int initialY,
QPoint selectionDimensions,
QList<uint16_t> *selectedMetatiles,
QList<QPair<uint16_t, uint16_t>> *selectedCollisions,
bool fromScriptCall = false);
void magicFill(int initialX, int initialY, QPoint selectionDimensions, QList<uint16_t>* selectedMetatiles,
QList<QPair<uint16_t, uint16_t>>* selectedCollisions, bool fromScriptCall = false);
void floodFill(int x, int y, bool fromScriptCall = false);
void floodFill(int x, int y, uint16_t metatileId, bool fromScriptCall = false);
void floodFill(int initialX,
int initialY,
QPoint selectionDimensions,
QList<uint16_t> *selectedMetatiles,
QList<QPair<uint16_t, uint16_t>> *selectedCollisions,
bool fromScriptCall = false);
void floodFill(int initialX, int initialY, QPoint selectionDimensions, QList<uint16_t>* selectedMetatiles,
QList<QPair<uint16_t, uint16_t>>* selectedCollisions, bool fromScriptCall = false);
void floodFillSmartPath(int initialX, int initialY, bool fromScriptCall = false);
virtual void pick(QGraphicsSceneMouseEvent*);
virtual void select(QGraphicsSceneMouseEvent*);

View file

@ -4,9 +4,7 @@
#include <QGraphicsObject>
#include <QLine>
class MapRuler : public QGraphicsObject, private QLine
{
class MapRuler : public QGraphicsObject, private QLine {
Q_OBJECT
public:
@ -18,25 +16,45 @@ public:
void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override;
bool eventFilter(QObject*, QEvent* event) override;
bool isAnchored() const { return anchored; }
bool isLocked() const { return locked; }
bool isAnchored() const {
return anchored;
}
bool isLocked() const {
return locked;
}
// Ruler start point in metatiles
QPoint anchor() const { return QLine::p1(); }
QPoint anchor() const {
return QLine::p1();
}
// Ruler end point in metatiles
QPoint endPos() const { return QLine::p2(); }
QPoint endPos() const {
return QLine::p2();
}
// X-coordinate of the ruler's left edge in metatiles
int left() const { return qMin(anchor().x(), endPos().x()); }
int left() const {
return qMin(anchor().x(), endPos().x());
}
// Y-coordinate of the ruler's top edge in metatiles
int top() const { return qMin(anchor().y(), endPos().y()); }
int top() const {
return qMin(anchor().y(), endPos().y());
}
// Horizontal component of the ruler in metatiles
int deltaX() const { return QLine::dx(); }
int deltaX() const {
return QLine::dx();
}
// Vertical component of the ruler in metatiles
int deltaY() const { return QLine::dy(); }
int deltaY() const {
return QLine::dy();
}
// Ruler width in metatiles
int width() const { return qAbs(deltaX()); }
int width() const {
return qAbs(deltaX());
}
// Ruler height in metatiles
int height() const { return qAbs(deltaY()); }
int height() const {
return qAbs(deltaY());
}
public slots:
void mouseEvent(QGraphicsSceneMouseEvent* event);
@ -63,8 +81,12 @@ private:
QPoint snapToWithinBounds(QPoint pos) const;
void updateGeometry();
void updateStatus(Qt::Corner corner);
int pixWidth() const { return width() * 16; }
int pixHeight() const { return height() * 16; }
int pixWidth() const {
return width() * 16;
}
int pixHeight() const {
return height() * 16;
}
};
#endif // MAPRULER_H

View file

@ -3,11 +3,11 @@
#include <QObject>
class MapSceneEventFilter : public QObject
{
class MapSceneEventFilter : public QObject {
Q_OBJECT
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
public:
explicit MapSceneEventFilter(QObject* parent = nullptr);

View file

@ -19,6 +19,7 @@ public:
void setTilesets(Tileset*, Tileset*);
void setMetatile(Metatile*);
void clearLastModifiedCoords();
private:
Metatile* metatile;
Tileset* primaryTileset;
@ -28,6 +29,7 @@ private:
signals:
void tileChanged(int, int);
void selectedTilesChanged(QPoint, int, int);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent*);
void mouseMoveEvent(QGraphicsSceneMouseEvent*);

View file

@ -31,12 +31,14 @@ public:
void setExternalSelection(int, int, QList<uint16_t>, QList<QPair<uint16_t, uint16_t>>);
QPoint getMetatileIdCoordsOnWidget(uint16_t);
void setMap(Map*);
protected:
void mousePressEvent(QGraphicsSceneMouseEvent*);
void mouseMoveEvent(QGraphicsSceneMouseEvent*);
void mouseReleaseEvent(QGraphicsSceneMouseEvent*);
void hoverMoveEvent(QGraphicsSceneHoverEvent*);
void hoverLeaveEvent(QGraphicsSceneHoverEvent*);
private:
bool externalSelection;
int numMetatilesWide;

View file

@ -5,21 +5,15 @@
#include <QPainter>
#include <QRgb>
class MovableRect : public QGraphicsItem
{
class MovableRect : public QGraphicsItem {
public:
MovableRect(bool* enabled, int width, int height, QRgb color);
QRectF boundingRect() const override
{
QRectF boundingRect() const override {
qreal penWidth = 4;
return QRectF(-penWidth,
-penWidth,
30 * 8 + penWidth * 2,
20 * 8 + penWidth * 2);
return QRectF(-penWidth, -penWidth, 30 * 8 + penWidth * 2, 20 * 8 + penWidth * 2);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) override
{
void paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*) override {
painter->setPen(this->color);
painter->drawRect(-2, -2, this->width + 3, this->height + 3);
painter->setPen(QColor(0, 0, 0));
@ -28,6 +22,7 @@ public:
}
void updateLocation(int x, int y);
bool* enabled;
private:
int width;
int height;

View file

@ -6,10 +6,8 @@
class QLineEdit;
// A collection of QKeySequenceEdit's laid out horizontally.
class MultiKeyEdit : public QWidget
{
class MultiKeyEdit : public QWidget {
Q_OBJECT
public:

View file

@ -4,8 +4,7 @@
#include "event.h"
#include <QToolButton>
class NewEventToolButton : public QToolButton
{
class NewEventToolButton : public QToolButton {
Q_OBJECT
public:
explicit NewEventToolButton(QWidget* parent = nullptr);
@ -29,6 +28,7 @@ public slots:
void newSecretBase();
signals:
void newEventAdded(QString);
private:
QString selectedEventType;
void init();

View file

@ -11,8 +11,7 @@ namespace Ui {
class NewMapPopup;
}
class NewMapPopup : public QMainWindow
{
class NewMapPopup : public QMainWindow {
Q_OBJECT
public:
explicit NewMapPopup(QWidget* parent = nullptr, Project* project = nullptr);

View file

@ -8,8 +8,7 @@ namespace Ui {
class NewTilesetDialog;
}
class NewTilesetDialog : public QDialog
{
class NewTilesetDialog : public QDialog {
Q_OBJECT
public:

View file

@ -3,8 +3,7 @@
#include <QComboBox>
class NoScrollComboBox : public QComboBox
{
class NoScrollComboBox : public QComboBox {
Q_OBJECT
public:

View file

@ -3,8 +3,7 @@
#include <QSpinBox>
class NoScrollSpinBox : public QSpinBox
{
class NoScrollSpinBox : public QSpinBox {
Q_OBJECT
public:

View file

@ -8,7 +8,8 @@
class OverlayItem {
public:
OverlayItem() {}
OverlayItem() {
}
virtual ~OverlayItem(){};
virtual void render(QPainter*){};
};
@ -22,8 +23,10 @@ public:
this->color = color;
this->fontSize = fontSize;
}
~OverlayText() {}
~OverlayText() {
}
virtual void render(QPainter* painter);
private:
QString text;
int x;
@ -42,8 +45,10 @@ public:
this->color = color;
this->filled = filled;
}
~OverlayRect() {}
~OverlayRect() {
}
virtual void render(QPainter* painter);
private:
int x;
int y;
@ -60,18 +65,20 @@ public:
this->y = y;
this->image = image;
}
~OverlayImage() {}
~OverlayImage() {
}
virtual void render(QPainter* painter);
private:
int x;
int y;
QImage image;
};
class Overlay
{
class Overlay {
public:
Overlay() {}
Overlay() {
}
~Overlay() {
this->clearItems();
}
@ -80,6 +87,7 @@ public:
void addText(QString text, int x, int y, QString color = "#000000", int fontSize = 12);
void addRect(int x, int y, int width, int height, QString color = "#000000", bool filled = false);
void addImage(int x, int y, QString filepath);
private:
QList<OverlayItem*> items;
};

View file

@ -6,13 +6,11 @@
class NoScrollComboBox;
class QAbstractButton;
namespace Ui {
class PreferenceEditor;
}
class PreferenceEditor : public QMainWindow
{
class PreferenceEditor : public QMainWindow {
Q_OBJECT
public:

View file

@ -16,8 +16,7 @@ namespace Ui {
class RegionMapEditor;
}
class RegionMapEditor : public QMainWindow
{
class RegionMapEditor : public QMainWindow {
Q_OBJECT
public:

View file

@ -7,7 +7,8 @@
class SelectablePixmapItem : public QObject, public QGraphicsPixmapItem {
Q_OBJECT
public:
SelectablePixmapItem(int cellWidth, int cellHeight): SelectablePixmapItem(cellWidth, cellHeight, INT_MAX, INT_MAX) {}
SelectablePixmapItem(int cellWidth, int cellHeight) : SelectablePixmapItem(cellWidth, cellHeight, INT_MAX, INT_MAX) {
}
SelectablePixmapItem(int cellWidth, int cellHeight, int maxSelectionWidth, int maxSelectionHeight) {
this->cellWidth = cellWidth;
this->cellHeight = cellHeight;

View file

@ -5,11 +5,9 @@
#include <QKeySequence>
#include <QShortcut>
// Alternative to QShortcut that adds support for multiple key sequences.
// Use this to allow the shortcut to be editable in ShortcutsEditor.
class Shortcut : public QObject
{
class Shortcut : public QObject {
Q_OBJECT
Q_DECLARE_PRIVATE(QShortcut)
Q_PROPERTY(QKeySequence key READ key WRITE setKey)
@ -20,11 +18,9 @@ class Shortcut : public QObject
public:
explicit Shortcut(QWidget* parent);
Shortcut(const QKeySequence &key, QWidget *parent,
const char *member = nullptr, const char *ambiguousMember = nullptr,
Shortcut(const QKeySequence& key, QWidget* parent, const char* member = nullptr, const char* ambiguousMember = nullptr,
Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
Shortcut(const QList<QKeySequence> &keys, QWidget *parent,
const char *member = nullptr, const char *ambiguousMember = nullptr,
Shortcut(const QList<QKeySequence>& keys, QWidget* parent, const char* member = nullptr, const char* ambiguousMember = nullptr,
Qt::ShortcutContext shortcutContext = Qt::WindowShortcut);
~Shortcut();
@ -51,8 +47,9 @@ public:
int id() const;
QList<int> ids() const;
inline QWidget *parentWidget() const
{ return static_cast<QWidget *>(QObject::parent()); }
inline QWidget* parentWidget() const {
return static_cast<QWidget*>(QObject::parent());
}
signals:
void activated();

View file

@ -13,13 +13,11 @@ class QFormLayout;
class MultiKeyEdit;
class QAbstractButton;
namespace Ui {
class ShortcutsEditor;
}
class ShortcutsEditor : public QMainWindow
{
class ShortcutsEditor : public QMainWindow {
Q_OBJECT
public:

View file

@ -30,8 +30,7 @@ public:
Metatile* newMetatile;
};
class TilesetEditor : public QMainWindow
{
class TilesetEditor : public QMainWindow {
Q_OBJECT
public:

View file

@ -7,8 +7,7 @@
class TilesetEditorTileSelector : public SelectablePixmapItem {
Q_OBJECT
public:
TilesetEditorTileSelector(Tileset *primaryTileset, Tileset *secondaryTileset, bool isTripleLayer)
: SelectablePixmapItem(16, 16, isTripleLayer ? 6 : 4, 2) {
TilesetEditorTileSelector(Tileset* primaryTileset, Tileset* secondaryTileset, bool isTripleLayer) : SelectablePixmapItem(16, 16, isTripleLayer ? 6 : 4, 2) {
this->primaryTileset = primaryTileset;
this->secondaryTileset = secondaryTileset;
this->numTilesWide = 16;

View file

@ -16,7 +16,6 @@
#include <QAbstractButton>
KeyValueConfigBase::~KeyValueConfigBase() {
}
void KeyValueConfigBase::load() {
@ -81,15 +80,11 @@ void KeyValueConfigBase::save() {
}
const QMap<MapSortOrder, QString> mapSortOrderMap = {
{MapSortOrder::Group, "group"},
{MapSortOrder::Layout, "layout"},
{MapSortOrder::Area, "area"},
{ MapSortOrder::Group, "group" }, { MapSortOrder::Layout, "layout" }, { MapSortOrder::Area, "area" },
};
const QMap<QString, MapSortOrder> mapSortOrderReverseMap = {
{"group", MapSortOrder::Group},
{"layout", MapSortOrder::Layout},
{"area", MapSortOrder::Area},
{ "group", MapSortOrder::Group }, { "layout", MapSortOrder::Layout }, { "area", MapSortOrder::Area },
};
PorymapConfig porymapConfig;
@ -217,8 +212,7 @@ QMap<QString, QString> PorymapConfig::getKeyValueMap() {
map.insert("show_player_view", this->showPlayerView ? "1" : "0");
map.insert("show_cursor_tile", this->showCursorTile ? "1" : "0");
map.insert("monitor_files", this->monitorFiles ? "1" : "0");
map.insert("region_map_dimensions", QString("%1x%2").arg(this->regionMapDimensions.width())
.arg(this->regionMapDimensions.height()));
map.insert("region_map_dimensions", QString("%1x%2").arg(this->regionMapDimensions.width()).arg(this->regionMapDimensions.height()));
map.insert("theme", this->theme);
map.insert("text_editor_open_directory", this->textEditorOpenFolder);
map.insert("text_editor_goto_line", this->textEditorGotoLine);
@ -262,8 +256,7 @@ void PorymapConfig::setMonitorFiles(bool monitor) {
this->save();
}
void PorymapConfig::setMainGeometry(QByteArray mainWindowGeometry_, QByteArray mainWindowState_,
QByteArray mapSplitterState_, QByteArray mainSplitterState_) {
void PorymapConfig::setMainGeometry(QByteArray mainWindowGeometry_, QByteArray mainWindowState_, QByteArray mapSplitterState_, QByteArray mainSplitterState_) {
this->mainWindowGeometry = mainWindowGeometry_;
this->mainWindowState = mainWindowState_;
this->mapSplitterState = mapSplitterState_;
@ -414,15 +407,11 @@ QString PorymapConfig::getTextEditorGotoLine() {
}
const QMap<BaseGameVersion, QString> baseGameVersionMap = {
{BaseGameVersion::pokeruby, "pokeruby"},
{BaseGameVersion::pokefirered, "pokefirered"},
{BaseGameVersion::pokeemerald, "pokeemerald"},
{ BaseGameVersion::pokeruby, "pokeruby" }, { BaseGameVersion::pokefirered, "pokefirered" }, { BaseGameVersion::pokeemerald, "pokeemerald" },
};
const QMap<QString, BaseGameVersion> baseGameVersionReverseMap = {
{"pokeruby", BaseGameVersion::pokeruby},
{"pokefirered", BaseGameVersion::pokefirered},
{"pokeemerald", BaseGameVersion::pokeemerald},
{ "pokeruby", BaseGameVersion::pokeruby }, { "pokefirered", BaseGameVersion::pokefirered }, { "pokeemerald", BaseGameVersion::pokeemerald },
};
ProjectConfig projectConfig;
@ -527,14 +516,22 @@ void ProjectConfig::parseConfigKeyValue(QString key, QString value) {
void ProjectConfig::setUnreadKeys() {
// Set game-version specific defaults for any config field that wasn't read
bool isPokefirered = this->baseGameVersion == BaseGameVersion::pokefirered;
if (!readKeys.contains("use_custom_border_size")) this->useCustomBorderSize = isPokefirered;
if (!readKeys.contains("enable_event_weather_trigger")) this->enableEventWeatherTrigger = !isPokefirered;
if (!readKeys.contains("enable_event_secret_base")) this->enableEventSecretBase = !isPokefirered;
if (!readKeys.contains("enable_hidden_item_quantity")) this->enableHiddenItemQuantity = isPokefirered;
if (!readKeys.contains("enable_hidden_item_requires_itemfinder")) this->enableHiddenItemRequiresItemfinder = isPokefirered;
if (!readKeys.contains("enable_heal_location_respawn_data")) this->enableHealLocationRespawnData = isPokefirered;
if (!readKeys.contains("enable_object_event_in_connection")) this->enableObjectEventInConnection = isPokefirered;
if (!readKeys.contains("enable_floor_number")) this->enableFloorNumber = isPokefirered;
if (!readKeys.contains("use_custom_border_size"))
this->useCustomBorderSize = isPokefirered;
if (!readKeys.contains("enable_event_weather_trigger"))
this->enableEventWeatherTrigger = !isPokefirered;
if (!readKeys.contains("enable_event_secret_base"))
this->enableEventSecretBase = !isPokefirered;
if (!readKeys.contains("enable_hidden_item_quantity"))
this->enableHiddenItemQuantity = isPokefirered;
if (!readKeys.contains("enable_hidden_item_requires_itemfinder"))
this->enableHiddenItemRequiresItemfinder = isPokefirered;
if (!readKeys.contains("enable_heal_location_respawn_data"))
this->enableHealLocationRespawnData = isPokefirered;
if (!readKeys.contains("enable_object_event_in_connection"))
this->enableObjectEventInConnection = isPokefirered;
if (!readKeys.contains("enable_floor_number"))
this->enableFloorNumber = isPokefirered;
}
QMap<QString, QString> ProjectConfig::getKeyValueMap() {
@ -793,11 +790,7 @@ void ShortcutsConfig::storeShortcutsFromList(StoreType storeType, const QObjectL
storeShortcuts(storeType, cfgKey(object), currentShortcuts(object));
}
void ShortcutsConfig::storeShortcuts(
StoreType storeType,
const QString &cfgKey,
const QList<QKeySequence> &keySequences)
{
void ShortcutsConfig::storeShortcuts(StoreType storeType, const QString& cfgKey, const QList<QKeySequence>& keySequences) {
bool storeUser = (storeType == User) || !user_shortcuts.contains(cfgKey);
if (storeType == Default)

View file

@ -1,24 +1,16 @@
#include "block.h"
Block::Block() : tile(0), collision(0), elevation(0) { }
Block::Block() : tile(0), collision(0), elevation(0) {
}
Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) :
tile(tile),
collision(collision),
elevation(elevation)
{ }
Block::Block(uint16_t tile, uint16_t collision, uint16_t elevation) : tile(tile), collision(collision), elevation(elevation) {
}
Block::Block(uint16_t word) :
tile(word & 0x3ff),
collision((word >> 10) & 0x3),
elevation((word >> 12) & 0xf)
{ }
Block::Block(uint16_t word) : tile(word & 0x3ff), collision((word >> 10) & 0x3), elevation((word >> 12) & 0xf) {
}
Block::Block(const Block &other) :
tile(other.tile),
collision(other.collision),
elevation(other.elevation)
{ }
Block::Block(const Block& other) : tile(other.tile), collision(other.collision), elevation(other.elevation) {
}
Block& Block::operator=(const Block& other) {
tile = other.tile;
@ -28,10 +20,7 @@ Block &Block::operator=(const Block &other) {
}
uint16_t Block::rawValue() const {
return static_cast<uint16_t>(
(tile & 0x3ff) +
((collision & 0x3) << 10) +
((elevation & 0xf) << 12));
return static_cast<uint16_t>((tile & 0x3ff) + ((collision & 0x3) << 10) + ((elevation & 0xf) << 12));
}
bool Block::operator==(Block other) const {

View file

@ -13,12 +13,10 @@ int getEventTypeMask(QList<Event *> events) {
eventTypeMask |= IDMask_EventType_Object;
} else if (event->get("event_type") == EventType::Warp) {
eventTypeMask |= IDMask_EventType_Warp;
} else if (event->get("event_type") == EventType::Trigger ||
event->get("event_type") == EventType::WeatherTrigger) {
} else if (event->get("event_type") == EventType::Trigger || event->get("event_type") == EventType::WeatherTrigger) {
eventTypeMask |= IDMask_EventType_Trigger;
} else if (event->get("event_type") == EventType::Sign ||
event->get("event_type") == EventType::HiddenItem ||
event->get("event_type") == EventType::SecretBase) {
} else if (event->get("event_type") == EventType::Sign || event->get("event_type") == EventType::HiddenItem
|| event->get("event_type") == EventType::SecretBase) {
eventTypeMask |= IDMask_EventType_BG;
} else if (event->get("event_type") == EventType::HealLocation) {
eventTypeMask |= IDMask_EventType_Heal;
@ -32,9 +30,8 @@ void renderMapBlocks(Map *map, bool ignoreCache = false) {
map->collisionItem->draw(ignoreCache);
}
PaintMetatile::PaintMetatile(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) {
PaintMetatile::PaintMetatile(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent)
: QUndoCommand(parent) {
setText("Paint Metatiles");
this->map = map;
@ -47,7 +44,8 @@ PaintMetatile::PaintMetatile(Map *map,
void PaintMetatile::redo() {
QUndoCommand::redo();
if (!map) return;
if (!map)
return;
map->layout->blockdata = newMetatiles;
@ -57,7 +55,8 @@ void PaintMetatile::redo() {
}
void PaintMetatile::undo() {
if (!map) return;
if (!map)
return;
map->layout->blockdata = oldMetatiles;
@ -86,9 +85,7 @@ bool PaintMetatile::mergeWith(const QUndoCommand *command) {
************************************************************************
******************************************************************************/
PaintBorder::PaintBorder(Map *map,
const Blockdata &oldBorder, const Blockdata &newBorder,
unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) {
PaintBorder::PaintBorder(Map* map, const Blockdata& oldBorder, const Blockdata& newBorder, unsigned actionId, QUndoCommand* parent) : QUndoCommand(parent) {
setText("Paint Border");
this->map = map;
@ -101,7 +98,8 @@ PaintBorder::PaintBorder(Map *map,
void PaintBorder::redo() {
QUndoCommand::redo();
if (!map) return;
if (!map)
return;
map->layout->border = newBorder;
@ -109,7 +107,8 @@ void PaintBorder::redo() {
}
void PaintBorder::undo() {
if (!map) return;
if (!map)
return;
map->layout->border = oldBorder;
@ -122,9 +121,8 @@ void PaintBorder::undo() {
************************************************************************
******************************************************************************/
ShiftMetatiles::ShiftMetatiles(Map *map,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
unsigned actionId, QUndoCommand *parent) : QUndoCommand(parent) {
ShiftMetatiles::ShiftMetatiles(Map* map, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, unsigned actionId, QUndoCommand* parent)
: QUndoCommand(parent) {
setText("Shift Metatiles");
this->map = map;
@ -137,7 +135,8 @@ ShiftMetatiles::ShiftMetatiles(Map *map,
void ShiftMetatiles::redo() {
QUndoCommand::redo();
if (!map) return;
if (!map)
return;
map->layout->blockdata = newMetatiles;
@ -147,7 +146,8 @@ void ShiftMetatiles::redo() {
}
void ShiftMetatiles::undo() {
if (!map) return;
if (!map)
return;
map->layout->blockdata = oldMetatiles;
@ -176,11 +176,9 @@ bool ShiftMetatiles::mergeWith(const QUndoCommand *command) {
************************************************************************
******************************************************************************/
ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
QSize oldBorderDimensions, QSize newBorderDimensions,
const Blockdata &oldBorder, const Blockdata &newBorder,
QUndoCommand *parent) : QUndoCommand(parent) {
ResizeMap::ResizeMap(Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles,
QSize oldBorderDimensions, QSize newBorderDimensions, const Blockdata& oldBorder, const Blockdata& newBorder, QUndoCommand* parent)
: QUndoCommand(parent) {
setText("Resize Map");
this->map = map;
@ -207,7 +205,8 @@ ResizeMap::ResizeMap(Map *map, QSize oldMapDimensions, QSize newMapDimensions,
void ResizeMap::redo() {
QUndoCommand::redo();
if (!map) return;
if (!map)
return;
map->layout->blockdata = newMetatiles;
map->setDimensions(newMapWidth, newMapHeight, false);
@ -221,7 +220,8 @@ void ResizeMap::redo() {
}
void ResizeMap::undo() {
if (!map) return;
if (!map)
return;
map->layout->blockdata = oldMetatiles;
map->setDimensions(oldMapWidth, oldMapHeight, false);
@ -240,9 +240,7 @@ void ResizeMap::undo() {
************************************************************************
******************************************************************************/
EventMove::EventMove(QList<Event *> events,
int deltaX, int deltaY, unsigned actionId,
QUndoCommand *parent) : QUndoCommand(parent) {
EventMove::EventMove(QList<Event*> events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent) : QUndoCommand(parent) {
setText("Move Event");
this->events = events;
@ -291,9 +289,7 @@ int EventMove::id() const {
************************************************************************
******************************************************************************/
EventShift::EventShift(QList<Event *> events,
int deltaX, int deltaY, unsigned actionId,
QUndoCommand *parent)
EventShift::EventShift(QList<Event*> events, int deltaX, int deltaY, unsigned actionId, QUndoCommand* parent)
: EventMove(events, deltaX, deltaY, actionId, parent) {
this->events = events;
setText("Shift Events");
@ -307,8 +303,7 @@ int EventShift::id() const {
************************************************************************
******************************************************************************/
EventCreate::EventCreate(Editor *editor, Map *map, Event *event,
QUndoCommand *parent) : QUndoCommand(parent) {
EventCreate::EventCreate(Editor* editor, Map* map, Event* event, QUndoCommand* parent) : QUndoCommand(parent) {
setText("Create Event");
this->editor = editor;
@ -351,9 +346,7 @@ int EventCreate::id() const {
************************************************************************
******************************************************************************/
EventDelete::EventDelete(Editor *editor, Map *map,
QList<Event *> selectedEvents, Event *nextSelectedEvent,
QUndoCommand *parent) : QUndoCommand(parent) {
EventDelete::EventDelete(Editor* editor, Map* map, QList<Event*> selectedEvents, Event* nextSelectedEvent, QUndoCommand* parent) : QUndoCommand(parent) {
if (selectedEvents.size() > 1) {
setText("Delete Events");
} else {
@ -411,9 +404,7 @@ int EventDelete::id() const {
************************************************************************
******************************************************************************/
EventDuplicate::EventDuplicate(Editor *editor, Map *map,
QList<Event *> selectedEvents,
QUndoCommand *parent) : QUndoCommand(parent) {
EventDuplicate::EventDuplicate(Editor* editor, Map* map, QList<Event*> selectedEvents, QUndoCommand* parent) : QUndoCommand(parent) {
setText("Duplicate Event");
this->editor = editor;
@ -466,10 +457,9 @@ int EventDuplicate::id() const {
************************************************************************
******************************************************************************/
ScriptEditMap::ScriptEditMap(Map *map,
QSize oldMapDimensions, QSize newMapDimensions,
const Blockdata &oldMetatiles, const Blockdata &newMetatiles,
QUndoCommand *parent) : QUndoCommand(parent) {
ScriptEditMap::ScriptEditMap(
Map* map, QSize oldMapDimensions, QSize newMapDimensions, const Blockdata& oldMetatiles, const Blockdata& newMetatiles, QUndoCommand* parent)
: QUndoCommand(parent) {
setText("Script Edit Map");
this->map = map;
@ -486,7 +476,8 @@ ScriptEditMap::ScriptEditMap(Map *map,
void ScriptEditMap::redo() {
QUndoCommand::redo();
if (!map) return;
if (!map)
return;
map->layout->blockdata = newMetatiles;
if (newMapWidth != map->getWidth() || newMapHeight != map->getHeight()) {
@ -500,7 +491,8 @@ void ScriptEditMap::redo() {
}
void ScriptEditMap::undo() {
if (!map) return;
if (!map)
return;
map->layout->blockdata = oldMetatiles;
if (oldMapWidth != map->getWidth() || oldMapHeight != map->getHeight()) {

View file

@ -12,31 +12,26 @@ QString EventType::HiddenItem = "event_hidden_item";
QString EventType::SecretBase = "event_secret_base";
QString EventType::HealLocation = "event_heal_location";
Event::Event() :
spriteWidth(16),
spriteHeight(16),
usingSprite(false)
{ }
Event::Event() : spriteWidth(16), spriteHeight(16), usingSprite(false) {
}
Event::Event(const Event& toCopy) :
values(toCopy.values),
Event::Event(const Event& toCopy)
: values(toCopy.values),
customValues(toCopy.customValues),
pixmap(toCopy.pixmap),
spriteWidth(toCopy.spriteWidth),
spriteHeight(toCopy.spriteHeight),
frame(toCopy.frame),
hFlip(toCopy.hFlip),
usingSprite(toCopy.usingSprite)
{ }
usingSprite(toCopy.usingSprite) {
}
Event::Event(QJsonObject obj, QString type) : Event()
{
Event::Event(QJsonObject obj, QString type) : Event() {
this->put("event_type", type);
this->readCustomValues(obj);
}
Event* Event::createNewEvent(QString event_type, QString map_name, Project *project)
{
Event* Event::createNewEvent(QString event_type, QString map_name, Project* project) {
Event* event = nullptr;
if (event_type == EventType::Object) {
event = createNewObjectEvent(project);
@ -65,8 +60,7 @@ Event* Event::createNewEvent(QString event_type, QString map_name, Project *proj
return event;
}
Event* Event::createNewObjectEvent(Project *project)
{
Event* Event::createNewObjectEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "object_event_group");
event->put("event_type", EventType::Object);
@ -86,8 +80,7 @@ Event* Event::createNewObjectEvent(Project *project)
return event;
}
Event* Event::createNewWarpEvent(QString map_name)
{
Event* Event::createNewWarpEvent(QString map_name) {
Event* event = new Event;
event->put("event_group_type", "warp_event_group");
event->put("event_type", EventType::Warp);
@ -97,8 +90,7 @@ Event* Event::createNewWarpEvent(QString map_name)
return event;
}
Event* Event::createNewHealLocationEvent(QString map_name)
{
Event* Event::createNewHealLocationEvent(QString map_name) {
Event* event = new Event;
event->put("event_group_type", "heal_event_group");
event->put("event_type", EventType::HealLocation);
@ -112,8 +104,7 @@ Event* Event::createNewHealLocationEvent(QString map_name)
return event;
}
Event* Event::createNewTriggerEvent(Project *project)
{
Event* Event::createNewTriggerEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "coord_event_group");
event->put("event_type", EventType::Trigger);
@ -124,8 +115,7 @@ Event* Event::createNewTriggerEvent(Project *project)
return event;
}
Event* Event::createNewWeatherTriggerEvent(Project *project)
{
Event* Event::createNewWeatherTriggerEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "coord_event_group");
event->put("event_type", EventType::WeatherTrigger);
@ -134,8 +124,7 @@ Event* Event::createNewWeatherTriggerEvent(Project *project)
return event;
}
Event* Event::createNewSignEvent(Project *project)
{
Event* Event::createNewSignEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "bg_event_group");
event->put("event_type", EventType::Sign);
@ -145,8 +134,7 @@ Event* Event::createNewSignEvent(Project *project)
return event;
}
Event* Event::createNewHiddenItemEvent(Project *project)
{
Event* Event::createNewHiddenItemEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "bg_event_group");
event->put("event_type", EventType::HiddenItem);
@ -162,8 +150,7 @@ Event* Event::createNewHiddenItemEvent(Project *project)
return event;
}
Event* Event::createNewSecretBaseEvent(Project *project)
{
Event* Event::createNewSecretBaseEvent(Project* project) {
Event* event = new Event;
event->put("event_group_type", "bg_event_group");
event->put("event_type", EventType::SecretBase);
@ -172,84 +159,44 @@ Event* Event::createNewSecretBaseEvent(Project *project)
return event;
}
int Event::getPixelX()
{
int Event::getPixelX() {
return (this->x() * 16) - qMax(0, (this->spriteWidth - 16) / 2);
}
int Event::getPixelY()
{
int Event::getPixelY() {
return (this->y() * 16) - qMax(0, this->spriteHeight - 16);
}
static QMap<QString, bool> expectedObjectFields{
{"graphics_id", true},
{"x", true},
{"y", true},
{"elevation", true},
{"movement_type", true},
{"movement_range_x", true},
{"movement_range_y", true},
{"trainer_type", true},
{"trainer_sight_or_berry_tree_id", true},
{"script", true},
{"flag", true},
{ "graphics_id", true }, { "x", true }, { "y", true }, { "elevation", true }, { "movement_type", true }, { "movement_range_x", true },
{ "movement_range_y", true }, { "trainer_type", true }, { "trainer_sight_or_berry_tree_id", true }, { "script", true }, { "flag", true },
};
static QMap<QString, bool> expectedWarpFields{
{"x", true},
{"y", true},
{"elevation", true},
{"dest_map", true},
{"dest_warp_id", true},
{ "x", true }, { "y", true }, { "elevation", true }, { "dest_map", true }, { "dest_warp_id", true },
};
static QMap<QString, bool> expectedTriggerFields{
{"type", true},
{"x", true},
{"y", true},
{"elevation", true},
{"var", true},
{"var_value", true},
{"script", true},
{ "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "var", true }, { "var_value", true }, { "script", true },
};
static QMap<QString, bool> expectedWeatherTriggerFields{
{"type", true},
{"x", true},
{"y", true},
{"elevation", true},
{"weather", true},
{ "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "weather", true },
};
static QMap<QString, bool> expectedSignFields{
{"type", true},
{"x", true},
{"y", true},
{"elevation", true},
{"player_facing_dir", true},
{"script", true},
{ "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "player_facing_dir", true }, { "script", true },
};
static QMap<QString, bool> expectedHiddenItemFields{
{"type", true},
{"x", true},
{"y", true},
{"elevation", true},
{"item", true},
{"flag", true},
{ "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "item", true }, { "flag", true },
};
static QMap<QString, bool> expectedSecretBaseFields{
{"type", true},
{"x", true},
{"y", true},
{"elevation", true},
{"secret_base_id", true},
{ "type", true }, { "x", true }, { "y", true }, { "elevation", true }, { "secret_base_id", true },
};
QMap<QString, bool> Event::getExpectedFields()
{
QMap<QString, bool> Event::getExpectedFields() {
QString type = this->get("event_type");
QMap<QString, bool> expectedFields = QMap<QString, bool>();
if (type == EventType::Object) {
@ -279,8 +226,7 @@ QMap<QString, bool> Event::getExpectedFields()
return expectedFields;
};
void Event::readCustomValues(QJsonObject values)
{
void Event::readCustomValues(QJsonObject values) {
this->customValues.clear();
QMap<QString, bool> expectedValues = this->getExpectedFields();
for (QString key : values.keys()) {
@ -290,8 +236,7 @@ void Event::readCustomValues(QJsonObject values)
}
}
void Event::addCustomValuesTo(OrderedJson::object *obj)
{
void Event::addCustomValuesTo(OrderedJson::object* obj) {
for (QString key : this->customValues.keys()) {
if (!obj->contains(key)) {
(*obj)[key] = this->customValues[key];
@ -299,8 +244,7 @@ void Event::addCustomValuesTo(OrderedJson::object *obj)
}
}
OrderedJson::object Event::buildObjectEventJSON()
{
OrderedJson::object Event::buildObjectEventJSON() {
OrderedJson::object eventObj;
eventObj["graphics_id"] = this->get("sprite");
if (projectConfig.getObjectEventInConnectionEnabled()) {
@ -321,8 +265,7 @@ OrderedJson::object Event::buildObjectEventJSON()
return eventObj;
}
OrderedJson::object Event::buildWarpEventJSON(const QMap<QString, QString> &mapNamesToMapConstants)
{
OrderedJson::object Event::buildWarpEventJSON(const QMap<QString, QString>& mapNamesToMapConstants) {
OrderedJson::object warpObj;
warpObj["x"] = this->getU16("x");
warpObj["y"] = this->getU16("y");
@ -334,8 +277,7 @@ OrderedJson::object Event::buildWarpEventJSON(const QMap<QString, QString> &mapN
return warpObj;
}
OrderedJson::object Event::buildTriggerEventJSON()
{
OrderedJson::object Event::buildTriggerEventJSON() {
OrderedJson::object triggerObj;
triggerObj["type"] = "trigger";
triggerObj["x"] = this->getU16("x");
@ -349,8 +291,7 @@ OrderedJson::object Event::buildTriggerEventJSON()
return triggerObj;
}
OrderedJson::object Event::buildWeatherTriggerEventJSON()
{
OrderedJson::object Event::buildWeatherTriggerEventJSON() {
OrderedJson::object weatherObj;
weatherObj["type"] = "weather";
weatherObj["x"] = this->getU16("x");
@ -362,8 +303,7 @@ OrderedJson::object Event::buildWeatherTriggerEventJSON()
return weatherObj;
}
OrderedJson::object Event::buildSignEventJSON()
{
OrderedJson::object Event::buildSignEventJSON() {
OrderedJson::object signObj;
signObj["type"] = "sign";
signObj["x"] = this->getU16("x");
@ -376,8 +316,7 @@ OrderedJson::object Event::buildSignEventJSON()
return signObj;
}
OrderedJson::object Event::buildHiddenItemEventJSON()
{
OrderedJson::object Event::buildHiddenItemEventJSON() {
OrderedJson::object hiddenItemObj;
hiddenItemObj["type"] = "hidden_item";
hiddenItemObj["x"] = this->getU16("x");
@ -396,8 +335,7 @@ OrderedJson::object Event::buildHiddenItemEventJSON()
return hiddenItemObj;
}
OrderedJson::object Event::buildSecretBaseEventJSON()
{
OrderedJson::object Event::buildSecretBaseEventJSON() {
OrderedJson::object secretBaseObj;
secretBaseObj["type"] = "secret_base";
secretBaseObj["x"] = this->getU16("x");
@ -409,8 +347,7 @@ OrderedJson::object Event::buildSecretBaseEventJSON()
return secretBaseObj;
}
void Event::setPixmapFromSpritesheet(QImage spritesheet, int spriteWidth, int spriteHeight, int frame, bool hFlip)
{
void Event::setPixmapFromSpritesheet(QImage spritesheet, int spriteWidth, int spriteHeight, int frame, bool hFlip) {
// Set first palette color fully transparent.
QImage img = spritesheet.copy(frame * spriteWidth % spritesheet.width(), 0, spriteWidth, spriteHeight);
if (hFlip) {

View file

@ -2,8 +2,7 @@
#include "config.h"
#include "map.h"
HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t y, QString respawnMap, uint16_t respawnNPC)
{
HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t y, QString respawnMap, uint16_t respawnNPC) {
this->idName = id;
this->mapName = map;
this->index = i;
@ -13,15 +12,13 @@ HealLocation::HealLocation(QString id, QString map, int i, uint16_t x, uint16_t
this->respawnNPC = respawnNPC;
}
HealLocation HealLocation::fromEvent(Event *event)
{
HealLocation HealLocation::fromEvent(Event* event) {
HealLocation hl;
hl.idName = event->get("id_name");
hl.mapName = event->get("loc_name");
try {
hl.index = event->get("index").toInt();
}
catch(...) {
} catch (...) {
hl.index = 0;
}
hl.x = event->getU16("x");
@ -33,8 +30,7 @@ HealLocation HealLocation::fromEvent(Event *event)
return hl;
}
QDebug operator<<(QDebug debug, const HealLocation &hl)
{
QDebug operator<<(QDebug debug, const HealLocation& hl) {
debug << "HealLocation_" + hl.mapName << "(" << hl.x << ',' << hl.y << ")";
return debug;
}

View file

@ -11,8 +11,7 @@ unsigned long crc_table[256];
int crc_table_computed = 0;
/* Make the table for a fast CRC. */
void make_crc_table(void)
{
void make_crc_table(void) {
unsigned long c;
int n, k;
@ -34,9 +33,7 @@ void make_crc_table(void)
is the 1's complement of the final running CRC (see the
crc() routine below)). */
unsigned long update_crc(unsigned long crc, QByteArray buf,
int len)
{
unsigned long update_crc(unsigned long crc, QByteArray buf, int len) {
unsigned long c = crc;
int n;
@ -49,8 +46,7 @@ unsigned long update_crc(unsigned long crc, QByteArray buf,
}
/* Return the CRC of the bytes buf[0..len-1]. */
unsigned long crc(QByteArray buf, int len)
{
unsigned long crc(QByteArray buf, int len) {
return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL;
}
@ -60,8 +56,7 @@ unsigned long crc(QByteArray buf, int len)
// and re-importing into porymap (Qt), will cause the image to be
// interpreted as having too many colors. By properly exporting 16-palette
// images in porymap, we can effectively avoid that issue.
void exportIndexed4BPPPng(QImage image, QString filepath)
{
void exportIndexed4BPPPng(QImage image, QString filepath) {
// Verify that the image is not empty
if (image.isNull()) {
logError(QString("Failed to export %1: the image is null.").arg(filepath));

View file

@ -10,9 +10,7 @@
#include <QImage>
#include <QRegularExpression>
Map::Map(QObject *parent) : QObject(parent)
{
Map::Map(QObject* parent) : QObject(parent) {
editHistory.setClean();
}
@ -20,7 +18,8 @@ Map::~Map() {
// delete all associated events
while (!ownedEvents.isEmpty()) {
Event* last = ownedEvents.takeLast();
if (last) delete last;
if (last)
delete last;
}
}
@ -42,23 +41,19 @@ QString Map::mapConstantFromName(QString mapName) {
return constantName;
}
QString Map::objectEventsLabelFromName(QString mapName)
{
QString Map::objectEventsLabelFromName(QString mapName) {
return QString("%1_EventObjects").arg(mapName);
}
QString Map::warpEventsLabelFromName(QString mapName)
{
QString Map::warpEventsLabelFromName(QString mapName) {
return QString("%1_MapWarps").arg(mapName);
}
QString Map::coordEventsLabelFromName(QString mapName)
{
QString Map::coordEventsLabelFromName(QString mapName) {
return QString("%1_MapCoordEvents").arg(mapName);
}
QString Map::bgEventsLabelFromName(QString mapName)
{
QString Map::bgEventsLabelFromName(QString mapName) {
return QString("%1_MapBGEvents").arg(mapName);
}
@ -173,13 +168,8 @@ QPixmap Map::render(bool ignoreCache = false, MapLayout * fromLayout) {
}
changed_any = true;
Block block = layout->blockdata.at(i);
QImage metatile_image = getMetatileImage(
block.tile,
fromLayout ? fromLayout->tileset_primary : layout->tileset_primary,
fromLayout ? fromLayout->tileset_secondary : layout->tileset_secondary,
metatileLayerOrder,
metatileLayerOpacity
);
QImage metatile_image = getMetatileImage(block.tile, fromLayout ? fromLayout->tileset_primary : layout->tileset_primary,
fromLayout ? fromLayout->tileset_secondary : layout->tileset_secondary, metatileLayerOrder, metatileLayerOpacity);
int map_y = width_ ? i / width_ : 0;
int map_x = width_ ? i % width_ : 0;
QPoint metatile_origin = QPoint(map_x * 16, map_y * 16);
@ -445,7 +435,8 @@ void Map::removeEvent(Event *event) {
void Map::addEvent(Event* event) {
events[event->get("event_group_type")].append(event);
if (!ownedEvents.contains(event)) ownedEvents.append(event);
if (!ownedEvents.contains(event))
ownedEvents.append(event);
}
bool Map::hasUnsavedChanges() {

View file

@ -2,12 +2,8 @@
#include "tileset.h"
#include "project.h"
Metatile::Metatile() :
behavior(0),
layerType(0),
encounterType(0),
terrainType(0)
{ }
Metatile::Metatile() : behavior(0), layerType(0), encounterType(0), terrainType(0) {
}
int Metatile::getBlockIndex(int index) {
if (index < Project::getNumMetatilesPrimary()) {

View file

@ -3,13 +3,10 @@
#include "log.h"
#include "project.h"
MetatileParser::MetatileParser()
{
MetatileParser::MetatileParser() {
}
QList<Metatile*> MetatileParser::parse(QString filepath, bool *error, bool primaryTileset)
{
QList<Metatile*> MetatileParser::parse(QString filepath, bool* error, bool primaryTileset) {
QFile file(filepath);
if (!file.open(QIODevice::ReadOnly)) {
*error = true;
@ -30,17 +27,11 @@ QList<Metatile*> MetatileParser::parse(QString filepath, bool *error, bool prima
int metatileSize = 16;
int attrSize;
BaseGameVersion version;
if (in.at(projIdOffset + 0) == 'R'
&& in.at(projIdOffset + 1) == 'S'
&& in.at(projIdOffset + 2) == 'E'
&& in.at(projIdOffset + 3) == ' ') {
if (in.at(projIdOffset + 0) == 'R' && in.at(projIdOffset + 1) == 'S' && in.at(projIdOffset + 2) == 'E' && in.at(projIdOffset + 3) == ' ') {
// ruby and emerald are handled equally here.
version = BaseGameVersion::pokeemerald;
attrSize = 2;
} else if (in.at(projIdOffset + 0) == 'F'
&& in.at(projIdOffset + 1) == 'R'
&& in.at(projIdOffset + 2) == 'L'
&& in.at(projIdOffset + 3) == 'G') {
} else if (in.at(projIdOffset + 0) == 'F' && in.at(projIdOffset + 1) == 'R' && in.at(projIdOffset + 2) == 'L' && in.at(projIdOffset + 3) == 'G') {
version = BaseGameVersion::pokefirered;
attrSize = 4;
} else {
@ -50,10 +41,8 @@ QList<Metatile*> MetatileParser::parse(QString filepath, bool *error, bool prima
}
int maxMetatiles = primaryTileset ? Project::getNumMetatilesPrimary() : Project::getNumMetatilesTotal() - Project::getNumMetatilesPrimary();
int numMetatiles = static_cast<unsigned char>(in.at(0)) |
(static_cast<unsigned char>(in.at(1)) << 8) |
(static_cast<unsigned char>(in.at(2)) << 16) |
(static_cast<unsigned char>(in.at(3)) << 24);
int numMetatiles = static_cast<unsigned char>(in.at(0)) | (static_cast<unsigned char>(in.at(1)) << 8) | (static_cast<unsigned char>(in.at(2)) << 16)
| (static_cast<unsigned char>(in.at(3)) << 24);
if (numMetatiles > maxMetatiles) {
*error = true;
logError(QString(".bvd file contains data for %1 metatiles, but the maximum number of metatiles is %2.").arg(numMetatiles).arg(maxMetatiles));
@ -78,26 +67,22 @@ QList<Metatile*> MetatileParser::parse(QString filepath, bool *error, bool prima
QList<Tile> tiles;
for (int j = 0; j < 8; j++) {
int metatileOffset = 4 + i * metatileSize + j * 2;
uint16_t word = static_cast<uint16_t>(
static_cast<unsigned char>(in.at(metatileOffset)) |
(static_cast<unsigned char>(in.at(metatileOffset + 1)) << 8));
uint16_t word
= static_cast<uint16_t>(static_cast<unsigned char>(in.at(metatileOffset)) | (static_cast<unsigned char>(in.at(metatileOffset + 1)) << 8));
Tile tile(word & 0x3ff, (word >> 10) & 1, (word >> 11) & 1, (word >> 12) & 0xf);
tiles.append(tile);
}
int attrOffset = 4 + (numMetatiles * metatileSize) + (i * attrSize);
if (version == BaseGameVersion::pokefirered) {
int value = static_cast<unsigned char>(in.at(attrOffset)) |
(static_cast<unsigned char>(in.at(attrOffset + 1)) << 8) |
(static_cast<unsigned char>(in.at(attrOffset + 2)) << 16) |
(static_cast<unsigned char>(in.at(attrOffset + 3)) << 24);
int value = static_cast<unsigned char>(in.at(attrOffset)) | (static_cast<unsigned char>(in.at(attrOffset + 1)) << 8)
| (static_cast<unsigned char>(in.at(attrOffset + 2)) << 16) | (static_cast<unsigned char>(in.at(attrOffset + 3)) << 24);
metatile->behavior = value & 0x1FF;
metatile->terrainType = (value & 0x3E00) >> 9;
metatile->encounterType = (value & 0x7000000) >> 24;
metatile->layerType = (value & 0x60000000) >> 29;
} else {
int value = static_cast<unsigned char>(in.at(attrOffset)) |
(static_cast<unsigned char>(in.at(attrOffset + 1)) << 8);
int value = static_cast<unsigned char>(in.at(attrOffset)) | (static_cast<unsigned char>(in.at(attrOffset + 1)) << 8);
metatile->behavior = value & 0xFF;
metatile->layerType = (value & 0xF000) >> 12;
metatile->encounterType = 0;

View file

@ -3,9 +3,7 @@
#include <QFileInfo>
#include <QRegularExpression>
PaletteUtil::PaletteUtil()
{
PaletteUtil::PaletteUtil() {
}
QList<QRgb> PaletteUtil::parse(QString filepath, bool* error) {
@ -105,9 +103,7 @@ QList<QRgb> PaletteUtil::parseJASC(QString filepath, bool *error) {
return QList<QRgb>();
}
palette.append(qRgb(this->clampColorValue(red),
this->clampColorValue(green),
this->clampColorValue(blue)));
palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue)));
} else {
*error = true;
logError(QString("JASC palette file '%1' had an unexpected format. Invalid color '%2'.").arg(filepath).arg(line));
@ -133,7 +129,9 @@ QList<QRgb> PaletteUtil::parseAdvanceMapPal(QString filepath, bool *error) {
if (in.length() % 4 != 0) {
*error = true;
logError(QString("Advance Map 1.92 palette file '%1' had an unexpected format. File's length must be a multiple of 4, but the length is %2.").arg(filepath).arg(in.length()));
logError(QString("Advance Map 1.92 palette file '%1' had an unexpected format. File's length must be a multiple of 4, but the length is %2.")
.arg(filepath)
.arg(in.length()));
return QList<QRgb>();
}
@ -143,9 +141,7 @@ QList<QRgb> PaletteUtil::parseAdvanceMapPal(QString filepath, bool *error) {
unsigned char red = static_cast<unsigned char>(in.at(i));
unsigned char green = static_cast<unsigned char>(in.at(i + 1));
unsigned char blue = static_cast<unsigned char>(in.at(i + 2));
palette.append(qRgb(this->clampColorValue(red),
this->clampColorValue(green),
this->clampColorValue(blue)));
palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue)));
i += 4;
}
@ -165,7 +161,9 @@ QList<QRgb> PaletteUtil::parseAdobeColorTable(QString filepath, bool *error) {
if (in.length() != 0x300) {
*error = true;
logError(QString("Adobe Color Table palette file '%1' had an unexpected format. File's length must be exactly 768, but the length is %2.").arg(filepath).arg(in.length()));
logError(QString("Adobe Color Table palette file '%1' had an unexpected format. File's length must be exactly 768, but the length is %2.")
.arg(filepath)
.arg(in.length()));
return QList<QRgb>();
}
@ -175,9 +173,7 @@ QList<QRgb> PaletteUtil::parseAdobeColorTable(QString filepath, bool *error) {
unsigned char red = static_cast<unsigned char>(in.at(i));
unsigned char green = static_cast<unsigned char>(in.at(i + 1));
unsigned char blue = static_cast<unsigned char>(in.at(i + 2));
palette.append(qRgb(this->clampColorValue(red),
this->clampColorValue(green),
this->clampColorValue(blue)));
palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue)));
i += 3;
}
@ -203,7 +199,9 @@ QList<QRgb> PaletteUtil::parseTileLayerPro(QString filepath, bool *error) {
if (in.length() != 0x304) {
*error = true;
logError(QString("Tile Layer Pro palette file '%1' had an unexpected format. File's length must be exactly 772, but the length is %2.").arg(filepath).arg(in.length()));
logError(QString("Tile Layer Pro palette file '%1' had an unexpected format. File's length must be exactly 772, but the length is %2.")
.arg(filepath)
.arg(in.length()));
return QList<QRgb>();
}
@ -213,9 +211,7 @@ QList<QRgb> PaletteUtil::parseTileLayerPro(QString filepath, bool *error) {
unsigned char red = static_cast<unsigned char>(in.at(i));
unsigned char green = static_cast<unsigned char>(in.at(i + 1));
unsigned char blue = static_cast<unsigned char>(in.at(i + 2));
palette.append(qRgb(this->clampColorValue(red),
this->clampColorValue(green),
this->clampColorValue(blue)));
palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue)));
i += 3;
}
@ -258,9 +254,7 @@ QList<QRgb> PaletteUtil::parseAdvancePaletteEditor(QString filepath, bool *error
int red = (raw & 0x1F) * 8;
int green = ((raw >> 5) & 0x1F) * 8;
int blue = ((raw >> 10) & 0x1F) * 8;
palette.append(qRgb(this->clampColorValue(red),
this->clampColorValue(green),
this->clampColorValue(blue)));
palette.append(qRgb(this->clampColorValue(red), this->clampColorValue(green), this->clampColorValue(blue)));
}
file.close();
@ -282,9 +276,7 @@ void PaletteUtil::writeJASC(QString filepath, QVector<QRgb> palette, int offset,
for (int i = offset; i < offset + nColors; i++) {
QRgb color = palette.at(i);
text += QString::number(qRed(color)) + " "
+ QString::number(qGreen(color)) + " "
+ QString::number(qBlue(color)) + "\r\n";
text += QString::number(qRed(color)) + " " + QString::number(qGreen(color)) + " " + QString::number(qBlue(color)) + "\r\n";
}
QFile file(filepath);

View file

@ -6,7 +6,6 @@
#include <QJsonObject>
#include <QStack>
void ParseUtil::set_root(const QString& dir) {
this->root = dir;
}
@ -17,7 +16,8 @@ void ParseUtil::error(const QString &message, const QString &expression) {
for (QString line : lines) {
lineNum++;
colNum = line.indexOf(expression) + 1;
if (colNum) break;
if (colNum)
break;
}
logError(QString("%1:%2:%3: %4").arg(file).arg(lineNum).arg(colNum).arg(message));
}
@ -79,8 +79,14 @@ int ParseUtil::evaluateDefine(const QString &define, const QMap<QString, int> &k
QList<Token> ParseUtil::tokenizeExpression(QString expression, const QMap<QString, int>& knownIdentifiers) {
QList<Token> tokens;
QStringList tokenTypes = (QStringList() << "hex" << "decimal" << "identifier" << "operator" << "leftparen" << "rightparen");
QRegularExpression re("^(?<hex>0x[0-9a-fA-F]+)|(?<decimal>[0-9]+)|(?<identifier>[a-zA-Z_0-9]+)|(?<operator>[+\\-*\\/<>|^%]+)|(?<leftparen>\\()|(?<rightparen>\\))");
QStringList tokenTypes = (QStringList() << "hex"
<< "decimal"
<< "identifier"
<< "operator"
<< "leftparen"
<< "rightparen");
QRegularExpression re(
"^(?<hex>0x[0-9a-fA-F]+)|(?<decimal>[0-9]+)|(?<identifier>[a-zA-Z_0-9]+)|(?<operator>[+\\-*\\/<>|^%]+)|(?<leftparen>\\()|(?<rightparen>\\))");
expression = expression.trimmed();
while (!expression.isEmpty()) {
@ -100,15 +106,12 @@ QList<Token> ParseUtil::tokenizeExpression(QString expression, const QMap<QStrin
tokenType = "decimal";
} else {
tokenType = "error";
QString message = QString("unknown token '%1' found in expression '%2'")
.arg(token).arg(expression);
QString message = QString("unknown token '%1' found in expression '%2'").arg(token).arg(expression);
error(message, expression);
}
}
else if (tokenType == "operator") {
} else if (tokenType == "operator") {
if (!Token::precedenceMap.contains(token)) {
QString message = QString("unsupported postfix operator: '%1'")
.arg(token);
QString message = QString("unsupported postfix operator: '%1'").arg(token);
error(message, expression);
}
}
@ -122,18 +125,8 @@ QList<Token> ParseUtil::tokenizeExpression(QString expression, const QMap<QStrin
return tokens;
}
QMap<QString, int> Token::precedenceMap = QMap<QString, int>(
{
{"*", 3},
{"/", 3},
{"+", 4},
{"-", 4},
{"<<", 5},
{">>", 5},
{"&", 8},
{"^", 9},
{"|", 10}
});
QMap<QString, int> Token::precedenceMap
= QMap<QString, int>({ { "*", 3 }, { "/", 3 }, { "+", 4 }, { "-", 4 }, { "<<", 5 }, { ">>", 5 }, { "&", 8 }, { "^", 9 }, { "|", 10 } });
// Shunting-yard algorithm for generating postfix notation.
// https://en.wikipedia.org/wiki/Shunting-yard_algorithm
@ -157,9 +150,7 @@ QList<Token> ParseUtil::generatePostfix(const QList<Token> &tokens) {
}
} else {
// token is an operator
while (!operatorStack.isEmpty()
&& operatorStack.top().operatorPrecedence <= token.operatorPrecedence
&& operatorStack.top().value != "(") {
while (!operatorStack.isEmpty() && operatorStack.top().operatorPrecedence <= token.operatorPrecedence && operatorStack.top().value != "(") {
output.append(operatorStack.pop());
}
operatorStack.push(token);
@ -222,11 +213,11 @@ QString ParseUtil::readCIncbin(const QString &filename, const QString &label) {
text = readTextFile(root + "/" + filename);
QRegExp *re = new QRegExp(QString(
"\\b%1\\b"
QRegExp* re = new QRegExp(QString("\\b%1\\b"
"\\s*\\[?\\s*\\]?\\s*=\\s*"
"INCBIN_[US][0-9][0-9]?"
"\\(\\s*\"([^\"]*)\"\\s*\\)").arg(label));
"\\(\\s*\"([^\"]*)\"\\s*\\)")
.arg(label));
int pos = re->indexIn(text);
if (pos != -1) {
@ -236,10 +227,7 @@ QString ParseUtil::readCIncbin(const QString &filename, const QString &label) {
return path;
}
QMap<QString, int> ParseUtil::readCDefines(const QString &filename,
const QStringList &prefixes,
QMap<QString, int> allDefines)
{
QMap<QString, int> ParseUtil::readCDefines(const QString& filename, const QStringList& prefixes, QMap<QString, int> allDefines) {
QMap<QString, int> filteredDefines;
file = filename;
@ -267,7 +255,8 @@ QMap<QString, int> ParseUtil::readCDefines(const QString &filename,
QRegularExpressionMatch match = iter.next();
QString name = match.captured("defineName");
QString expression = match.captured("defineValue");
if (expression == " ") continue;
if (expression == " ")
continue;
int value = evaluateDefine(expression, allDefines);
allDefines.insert(name, value);
for (QString prefix : prefixes) {
@ -279,10 +268,7 @@ QMap<QString, int> ParseUtil::readCDefines(const QString &filename,
return filteredDefines;
}
QStringList ParseUtil::readCDefinesSorted(const QString &filename,
const QStringList &prefixes,
const QMap<QString, int> &knownDefines)
{
QStringList ParseUtil::readCDefinesSorted(const QString& filename, const QStringList& prefixes, const QMap<QString, int>& knownDefines) {
QMap<QString, int> defines = readCDefines(filename, prefixes, knownDefines);
// The defines should to be sorted by their underlying value, not alphabetically.
@ -312,7 +298,8 @@ QStringList ParseUtil::readCArray(const QString &filename, const QString &label)
QStringList split = body.split(',');
for (QString item : split) {
item = item.trimmed();
if (!item.contains(QRegularExpression("[^A-Za-z0-9_&()\\s]"))) list.append(item);
if (!item.contains(QRegularExpression("[^A-Za-z0-9_&()\\s]")))
list.append(item);
// do not print error info here because this is called dozens of times
}
}

View file

@ -35,15 +35,11 @@ bool RegionMap::init(Project *pro) {
region_map_entries_path = path + "/src/data/region_map/region_map_entries.h";
region_map_layout_bin_path = path + "/graphics/pokenav/region_map_section_layout.bin";
city_map_tiles_path = path + "/graphics/pokenav/zoom_tiles.png";
bool allFilesExist = ensureRegionMapFileExists(region_map_bin_path)
&& ensureRegionMapFileExists(region_map_png_path)
&& ensureRegionMapFileExists(region_map_entries_path)
&& ensureRegionMapFileExists(region_map_layout_bin_path)
bool allFilesExist = ensureRegionMapFileExists(region_map_bin_path) && ensureRegionMapFileExists(region_map_png_path)
&& ensureRegionMapFileExists(region_map_entries_path) && ensureRegionMapFileExists(region_map_layout_bin_path)
&& ensureRegionMapFileExists(city_map_tiles_path);
return allFilesExist
&& readBkgImgBin()
&& readLayout();
return allFilesExist && readBkgImgBin() && readLayout();
}
void RegionMap::save() {
@ -115,7 +111,8 @@ void RegionMap::saveBkgImgBin() {
}
QFile file(region_map_bin_path);
if (!file.open(QIODevice::WriteOnly)) return;
if (!file.open(QIODevice::WriteOnly))
return;
file.write(data);
file.close();
}
@ -156,8 +153,7 @@ bool RegionMap::readLayout() {
QString mapsec = reBefore.match(line).captured(1);
QString insertion = entry[4].remove("sMapName_");
qmap.insert(mapsec, sMapNamesMap.value(insertion));
mapSecToMapEntry[mapsec] = {
// x y width height name
mapSecToMapEntry[mapsec] = { // x y width height name
entry[0].toInt(), entry[1].toInt(), entry[2].toInt(), entry[3].toInt(), insertion
};
} else if (line.contains("gRegionMapEntries")) {
@ -224,15 +220,16 @@ void RegionMap::saveLayout() {
int longest = 1;
for (auto sec : project->mapSectionNameToValue.keys()) {
if (sec.length() > longest) longest = sec.length();
if (sec.length() > longest)
longest = sec.length();
}
for (auto sec : project->mapSectionNameToValue.keys()) {
if (!mapSecToMapEntry.contains(sec) || sec == "MAPSEC_NONE") continue;
if (!mapSecToMapEntry.contains(sec) || sec == "MAPSEC_NONE")
continue;
RegionMapEntry entry = mapSecToMapEntry.value(sec);
entries_text += " [" + sec + QString("]%1= {").arg(QString(" ").repeated(1 + longest - sec.length()))
+ QString::number(entry.x) + ", " + QString::number(entry.y) + ", "
+ QString::number(entry.width) + ", " + QString::number(entry.height) + ", sMapName_" + entry.name + "},\n";
entries_text += " [" + sec + QString("]%1= {").arg(QString(" ").repeated(1 + longest - sec.length())) + QString::number(entry.x) + ", "
+ QString::number(entry.y) + ", " + QString::number(entry.width) + ", " + QString::number(entry.height) + ", sMapName_" + entry.name + "},\n";
}
entries_text += "};\n\n#endif // GUARD_DATA_REGION_MAP_REGION_MAP_ENTRIES_H\n";
@ -246,7 +243,8 @@ void RegionMap::saveLayout() {
}
}
QFile bfile(region_map_layout_bin_path);
if (!bfile.open(QIODevice::WriteOnly)) return;
if (!bfile.open(QIODevice::WriteOnly))
return;
bfile.write(data);
bfile.close();
}
@ -306,7 +304,8 @@ void RegionMap::replaceSectionId(unsigned oldId, unsigned newId) {
square.has_map = false;
square.secid = newId;
QString secname = project->mapSectionValueToName.value(newId);
if (secname != "MAPSEC_NONE") square.has_map = true;
if (secname != "MAPSEC_NONE")
square.has_map = true;
square.mapsec = secname;
square.map_name = sMapNamesMap.value(mapSecToMapEntry.value(secname).name);
}
@ -348,7 +347,8 @@ QVector<uint8_t> RegionMap::getTiles() {
}
void RegionMap::setTiles(QVector<uint8_t> tileIds) {
if (tileIds.size() != map_squares.size()) return;
if (tileIds.size() != map_squares.size())
return;
int i = 0;
for (uint8_t tileId : tileIds) {
@ -421,8 +421,8 @@ QString RegionMap::fixCase(QString caps) {
if (big) {
camel += ch.toUpper();
big = false;
}
else camel += ch.toLower();
} else
camel += ch.toLower();
}
return camel;
}

View file

@ -7,7 +7,6 @@
#include <QPainter>
#include <QImage>
Tileset* Tileset::getBlockTileset(int metatile_index, Tileset* primaryTileset, Tileset* secondaryTileset) {
if (metatile_index < Project::getNumMetatilesPrimary()) {
return primaryTileset;
@ -53,9 +52,7 @@ QList<QList<QRgb>> Tileset::getBlockPalettes(Tileset *primaryTileset, Tileset *s
QList<QRgb> Tileset::getPalette(int paletteId, Tileset* primaryTileset, Tileset* secondaryTileset, bool useTruePalettes) {
QList<QRgb> paletteTable;
Tileset *tileset = paletteId < Project::getNumPalettesPrimary()
? primaryTileset
: secondaryTileset;
Tileset* tileset = paletteId < Project::getNumPalettesPrimary() ? primaryTileset : secondaryTileset;
auto palettes = useTruePalettes ? tileset->palettes : tileset->palettePreviews;
for (int i = 0; i < palettes.at(paletteId).length(); i++) {
paletteTable.append(palettes.at(paletteId).at(i));
@ -102,7 +99,6 @@ bool Tileset::appendToGraphics(QString graphicsFile, QString friendlyName, bool
for (int i = 0; i < Project::getNumPalettesTotal(); ++i) {
QString paletteString = QString("%1.gbapal").arg(i, 2, 10, QLatin1Char('0'));
dataString.append(QString("\t.incbin \"data/tilesets/%1/%2/palettes/%3\"\n").arg(primaryString, friendlyName.toLower(), paletteString));
}
dataString.append("\n\t.align 2\n");
dataString.append(QString("gTilesetTiles_%1::\n").arg(friendlyName));

View file

@ -1,8 +1,6 @@
#include "wildmoninfo.h"
#include "montabwidget.h"
WildMonInfo getDefaultMonInfo(EncounterField field) {
WildMonInfo newInfo;
newInfo.active = true;

View file

@ -19,8 +19,7 @@
static bool selectNewEvents = false;
Editor::Editor(Ui::MainWindow* ui)
{
Editor::Editor(Ui::MainWindow* ui) {
this->ui = ui;
this->selected_events = new QList<DraggablePixmapItem*>;
this->settings = new Settings();
@ -40,8 +39,7 @@ Editor::Editor(Ui::MainWindow* ui)
});
}
Editor::~Editor()
{
Editor::~Editor() {
delete this->selected_events;
delete this->settings;
delete this->playerViewRect;
@ -383,8 +381,7 @@ void Editor::deleteWildMonGroup() {
int i = project->encounterGroupLabels.indexOf(labelCombo->currentText());
if (i < 0) {
logError(QString("Failed to find selected wild mon group: %1. Unable to delete")
.arg(labelCombo->currentText()));
logError(QString("Failed to find selected wild mon group: %1. Unable to delete").arg(labelCombo->currentText()));
return;
}
@ -452,9 +449,7 @@ void Editor::configureEncounterJSON(QWidget *window) {
chanceSpinner->setMinimum(1);
chanceSpinner->setMaximum(9999);
chanceSpinner->setValue(chance);
connect(chanceSpinner, QOverload<int>::of(&QSpinBox::valueChanged), [&updateTotal, &currentField](int) {
updateTotal(currentField);
});
connect(chanceSpinner, QOverload<int>::of(&QSpinBox::valueChanged), [&updateTotal, &currentField](int) { updateTotal(currentField); });
bool useGroups = !currentField.groups.isEmpty();
@ -472,7 +467,8 @@ void Editor::configureEncounterJSON(QWidget *window) {
}
}
for (QString groupName : field.groups.keys()) {
if (groupName == newGroupName) field.groups[newGroupName].append(index);
if (groupName == newGroupName)
field.groups[newGroupName].append(index);
}
break;
}
@ -573,7 +569,8 @@ void Editor::configureEncounterJSON(QWidget *window) {
});
QPushButton* deleteFieldButton = new QPushButton("Delete Field");
connect(deleteFieldButton, &QPushButton::clicked, [drawSlotWidgets, fieldChoices, &tempFields]() {
if (tempFields.size() < 2) return;// don't delete last
if (tempFields.size() < 2)
return; // don't delete last
int index = fieldChoices->currentIndex();
fieldChoices->removeItem(index);
tempFields.remove(index);
@ -634,7 +631,8 @@ void Editor::saveEncounterTabData() {
QStackedWidget* stack = ui->stackedWidget_WildMons;
QComboBox* labelCombo = ui->comboBox_EncounterGroupLabel;
if (!stack->count()) return;
if (!stack->count())
return;
tsl::ordered_map<QString, WildPokemonHeader>& encounterMap = project->wildMonData[map->constantName];
@ -647,7 +645,8 @@ void Editor::saveEncounterTabData() {
for (EncounterField monField : project->wildMonFields) {
QString fieldName = monField.name;
if (!tabWidget->isTabEnabled(fieldIndex++)) continue;
if (!tabWidget->isTabEnabled(fieldIndex++))
continue;
QTableWidget* monTable = static_cast<QTableWidget*>(tabWidget->widget(fieldIndex - 1));
QVector<WildPokemon> newWildMons;
@ -816,7 +815,6 @@ void Editor::onConnectionOffsetChanged(int newOffset) {
ui->spinBox_ConnectionOffset->blockSignals(true);
ui->spinBox_ConnectionOffset->setValue(newOffset);
ui->spinBox_ConnectionOffset->blockSignals(false);
}
void Editor::setConnectionEditControlValues(MapConnection* connection) {
@ -956,8 +954,8 @@ void Editor::scaleMapView(int s) {
void Editor::onHoveredMapMetatileChanged(const QPoint& pos) {
this->playerViewRect->updateLocation(pos.x(), pos.y());
this->cursorMapTileRect->updateLocation(pos.x(), pos.y());
if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles
&& pos.x() >= 0 && pos.x() < map->getWidth() && pos.y() >= 0 && pos.y() < map->getHeight()) {
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;
this->ui->statusBar->showMessage(QString("X: %1, Y: %2, %3, Scale = %4x")
@ -965,20 +963,17 @@ void Editor::onHoveredMapMetatileChanged(const QPoint &pos) {
.arg(pos.y())
.arg(getMetatileDisplayMessage(metatileId))
.arg(QString::number(pow(scale_base, scale_exp), 'g', 2)));
} else if (map_item->paintingMode == MapPixmapItem::PaintMode::EventObjects
&& pos.x() >= 0 && pos.x() < map->getWidth() && pos.y() >= 0 && pos.y() < map->getHeight()) {
this->ui->statusBar->showMessage(QString("X: %1, Y: %2, Scale = %3x")
.arg(pos.x())
.arg(pos.y())
.arg(QString::number(pow(scale_base, scale_exp), 'g', 2)));
} else if (map_item->paintingMode == MapPixmapItem::PaintMode::EventObjects && pos.x() >= 0 && pos.x() < map->getWidth() && pos.y() >= 0
&& pos.y() < map->getHeight()) {
this->ui->statusBar->showMessage(
QString("X: %1, Y: %2, Scale = %3x").arg(pos.x()).arg(pos.y()).arg(QString::number(pow(scale_base, scale_exp), 'g', 2)));
}
}
void Editor::onHoveredMapMetatileCleared() {
this->playerViewRect->setVisible(false);
this->cursorMapTileRect->setVisible(false);
if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles
|| map_item->paintingMode == MapPixmapItem::PaintMode::EventObjects) {
if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles || map_item->paintingMode == MapPixmapItem::PaintMode::EventObjects) {
this->ui->statusBar->clearMessage();
}
}
@ -986,15 +981,11 @@ void Editor::onHoveredMapMetatileCleared() {
void Editor::onHoveredMapMovementPermissionChanged(int x, int y) {
this->playerViewRect->updateLocation(x, y);
this->cursorMapTileRect->updateLocation(x, y);
if (map_item->paintingMode == MapPixmapItem::PaintMode::Metatiles
&& x >= 0 && x < map->getWidth() && y >= 0 && y < map->getHeight()) {
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;
QString message = QString("X: %1, Y: %2, %3")
.arg(x)
.arg(y)
.arg(this->getMovementPermissionText(collision, elevation));
QString message = QString("X: %1, Y: %2, %3").arg(x).arg(y).arg(this->getMovementPermissionText(collision, elevation));
this->ui->statusBar->showMessage(message);
}
}
@ -1078,8 +1069,7 @@ void Editor::onMapEndPaint(QGraphicsSceneMouseEvent *, MapPixmapItem *item) {
this->cursorMapTileRect->stopAnchor();
}
void Editor::setSmartPathCursorMode(QGraphicsSceneMouseEvent *event)
{
void Editor::setSmartPathCursorMode(QGraphicsSceneMouseEvent* event) {
bool shiftPressed = event->modifiers() & Qt::ShiftModifier;
if (settings->smartPathsEnabled) {
if (!shiftPressed) {
@ -1320,12 +1310,9 @@ void Editor::displayMetatileSelector() {
scene_metatiles = new QGraphicsScene;
if (!metatile_selector_item) {
metatile_selector_item = new MetatileSelector(8, map);
connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionChanged,
this, &Editor::onHoveredMetatileSelectionChanged);
connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionCleared,
this, &Editor::onHoveredMetatileSelectionCleared);
connect(metatile_selector_item, &MetatileSelector::selectedMetatilesChanged,
this, &Editor::onSelectedMetatilesChanged);
connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionChanged, this, &Editor::onHoveredMetatileSelectionChanged);
connect(metatile_selector_item, &MetatileSelector::hoveredMetatileSelectionCleared, this, &Editor::onHoveredMetatileSelectionCleared);
connect(metatile_selector_item, &MetatileSelector::selectedMetatilesChanged, this, &Editor::onSelectedMetatilesChanged);
metatile_selector_item->select(0);
} else {
metatile_selector_item->setMap(map);
@ -1348,12 +1335,8 @@ void Editor::displayMapMetatiles() {
int tw = 16;
int th = 16;
scene->setSceneRect(
-BORDER_DISTANCE * tw,
-BORDER_DISTANCE * th,
map_item->pixmap().width() + BORDER_DISTANCE * 2 * tw,
map_item->pixmap().height() + BORDER_DISTANCE * 2 * th
);
scene->setSceneRect(-BORDER_DISTANCE * tw, -BORDER_DISTANCE * th, map_item->pixmap().width() + BORDER_DISTANCE * 2 * tw,
map_item->pixmap().height() + BORDER_DISTANCE * 2 * th);
}
void Editor::displayMapMovementPermissions() {
@ -1361,13 +1344,11 @@ void Editor::displayMapMovementPermissions() {
scene->removeItem(collision_item);
delete collision_item;
}
collision_item = new CollisionPixmapItem(map, this->movement_permissions_selector_item,
this->metatile_selector_item, this->settings, &this->collisionOpacity);
collision_item
= new CollisionPixmapItem(map, this->movement_permissions_selector_item, this->metatile_selector_item, this->settings, &this->collisionOpacity);
connect(collision_item, &CollisionPixmapItem::mouseEvent, this, &Editor::mouseEvent_collision);
connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionChanged,
this, &Editor::onHoveredMapMovementPermissionChanged);
connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionCleared,
this, &Editor::onHoveredMapMovementPermissionCleared);
connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionChanged, this, &Editor::onHoveredMapMovementPermissionChanged);
connect(collision_item, &CollisionPixmapItem::hoveredMapMovementPermissionCleared, this, &Editor::onHoveredMapMovementPermissionCleared);
collision_item->draw(true);
scene->addItem(collision_item);
@ -1384,8 +1365,7 @@ void Editor::displayBorderMetatiles() {
selected_border_metatiles_item->draw();
scene_selected_border_metatiles->addItem(selected_border_metatiles_item);
connect(selected_border_metatiles_item, &BorderMetatilesPixmapItem::borderMetatilesChanged,
this, &Editor::onBorderMetatilesChanged);
connect(selected_border_metatiles_item, &BorderMetatilesPixmapItem::borderMetatilesChanged, this, &Editor::onBorderMetatilesChanged);
}
void Editor::displayCurrentMetatilesSelection() {
@ -1417,10 +1397,10 @@ void Editor::displayMovementPermissionSelector() {
scene_collision_metatiles = new QGraphicsScene;
if (!movement_permissions_selector_item) {
movement_permissions_selector_item = new MovementPermissionsSelector();
connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionChanged,
this, &Editor::onHoveredMovementPermissionChanged);
connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionCleared,
this, &Editor::onHoveredMovementPermissionCleared);
connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionChanged, this,
&Editor::onHoveredMovementPermissionChanged);
connect(movement_permissions_selector_item, &MovementPermissionsSelector::hoveredMovementPermissionCleared, this,
&Editor::onHoveredMovementPermissionCleared);
movement_permissions_selector_item->select(0, 3);
}
@ -1536,12 +1516,9 @@ void Editor::createConnectionItem(MapConnection* connection, bool hide) {
connection_edit_item->setY(y);
connection_edit_item->setZValue(-1);
scene->addItem(connection_edit_item);
connect(connection_edit_item, &ConnectionPixmapItem::connectionMoved,
this, &Editor::onConnectionMoved);
connect(connection_edit_item, &ConnectionPixmapItem::connectionItemSelected,
this, &Editor::onConnectionItemSelected);
connect(connection_edit_item, &ConnectionPixmapItem::connectionItemDoubleClicked,
this, &Editor::onConnectionItemDoubleClicked);
connect(connection_edit_item, &ConnectionPixmapItem::connectionMoved, this, &Editor::onConnectionMoved);
connect(connection_edit_item, &ConnectionPixmapItem::connectionItemSelected, this, &Editor::onConnectionItemSelected);
connect(connection_edit_item, &ConnectionPixmapItem::connectionItemDoubleClicked, this, &Editor::onConnectionItemDoubleClicked);
connection_edit_items.append(connection_edit_item);
}
@ -1556,12 +1533,7 @@ void Editor::maskNonVisibleConnectionTiles() {
QPainterPath mask;
mask.addRect(scene->itemsBoundingRect().toRect());
mask.addRect(
-BORDER_DISTANCE * 16,
-BORDER_DISTANCE * 16,
(map->getWidth() + BORDER_DISTANCE * 2) * 16,
(map->getHeight() + BORDER_DISTANCE * 2) * 16
);
mask.addRect(-BORDER_DISTANCE * 16, -BORDER_DISTANCE * 16, (map->getWidth() + BORDER_DISTANCE * 2) * 16, (map->getHeight() + BORDER_DISTANCE * 2) * 16);
// Mask the tiles with the current theme's background color.
QPen pen(ui->graphicsView_Map->palette().color(QPalette::Active, QPalette::Base));
@ -1750,10 +1722,8 @@ void Editor::updateMirroredConnection(MapConnection* connection, QString origina
if (!otherMap)
return;
static QMap<QString, QString> oppositeDirections = QMap<QString, QString>({
{"up", "down"}, {"right", "left"},
{"down", "up"}, {"left", "right"},
{"dive", "emerge"},{"emerge", "dive"}});
static QMap<QString, QString> oppositeDirections
= QMap<QString, QString>({ { "up", "down" }, { "right", "left" }, { "down", "up" }, { "left", "right" }, { "dive", "emerge" }, { "emerge", "dive" } });
QString oppositeDirection = oppositeDirections.value(originalDirection);
// Find the matching connection in the connected map.
@ -1861,47 +1831,42 @@ void Editor::updateDiveEmergeMap(QString mapName, QString direction) {
ui->label_NumConnections->setText(QString::number(map->connections.length()));
}
void Editor::updatePrimaryTileset(QString tilesetLabel, bool forceLoad)
{
if (map->layout->tileset_primary_label != tilesetLabel || forceLoad)
{
void Editor::updatePrimaryTileset(QString tilesetLabel, bool forceLoad) {
if (map->layout->tileset_primary_label != tilesetLabel || forceLoad) {
map->layout->tileset_primary_label = tilesetLabel;
map->layout->tileset_primary = project->getTileset(tilesetLabel, forceLoad);
}
}
void Editor::updateSecondaryTileset(QString tilesetLabel, bool forceLoad)
{
if (map->layout->tileset_secondary_label != tilesetLabel || forceLoad)
{
void Editor::updateSecondaryTileset(QString tilesetLabel, bool forceLoad) {
if (map->layout->tileset_secondary_label != tilesetLabel || forceLoad) {
map->layout->tileset_secondary_label = tilesetLabel;
map->layout->tileset_secondary = project->getTileset(tilesetLabel, forceLoad);
}
}
void Editor::toggleBorderVisibility(bool visible)
{
void Editor::toggleBorderVisibility(bool visible) {
this->setBorderItemsVisible(visible);
this->setConnectionsVisibility(visible);
}
void Editor::updateCustomMapHeaderValues(QTableWidget *table)
{
void Editor::updateCustomMapHeaderValues(QTableWidget* table) {
QMap<QString, QString> fields;
for (int row = 0; row < table->rowCount(); row++) {
QString keyStr = "";
QString valueStr = "";
QTableWidgetItem* key = table->item(row, 0);
QTableWidgetItem* value = table->item(row, 1);
if (key) keyStr = key->text();
if (value) valueStr = value->text();
if (key)
keyStr = key->text();
if (value)
valueStr = value->text();
fields[keyStr] = valueStr;
}
map->customHeaders = fields;
}
Tileset* Editor::getCurrentMapPrimaryTileset()
{
Tileset* Editor::getCurrentMapPrimaryTileset() {
QString tilesetLabel = map->layout->tileset_primary_label;
return project->getTileset(tilesetLabel);
}
@ -1918,7 +1883,8 @@ void Editor::redrawObject(DraggablePixmapItem *item) {
if (item) {
qreal opacity = item->event->usingSprite ? 1.0 : 0.7;
item->setOpacity(opacity);
item->setPixmap(item->event->pixmap.copy(item->event->frame * item->event->spriteWidth % item->event->pixmap.width(), 0, item->event->spriteWidth, item->event->spriteHeight));
item->setPixmap(item->event->pixmap.copy(
item->event->frame * item->event->spriteWidth % item->event->pixmap.width(), 0, item->event->spriteWidth, item->event->spriteHeight));
item->setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
if (selected_events && selected_events->contains(item)) {
QImage image = item->pixmap().toImage();
@ -1976,7 +1942,8 @@ void Editor::duplicateSelectedEvents() {
logWarn(QString("Skipping duplication, the map limit for events of type '%1' has been reached.").arg(eventType));
continue;
}
if (eventType == EventType::HealLocation) continue;
if (eventType == EventType::HealLocation)
continue;
Event* duplicate = new Event(*original);
duplicate->setX(duplicate->x() + 1);
duplicate->setY(duplicate->y() + 1);
@ -2002,8 +1969,7 @@ DraggablePixmapItem* Editor::addNewEvent(QString event_type) {
}
// Currently only object events have an explicit limit
bool Editor::eventLimitReached(Map *map, QString event_type)
{
bool Editor::eventLimitReached(Map* map, QString event_type) {
if (project && map && !event_type.isEmpty()) {
if (event_type == EventType::Object)
return map->events.value("object_event_group").length() >= project->getMaxObjectEvents();

View file

@ -40,8 +40,12 @@ using std::move;
* it may not be orderable.
*/
struct NullStruct {
bool operator==(NullStruct) const { return true; }
bool operator<(NullStruct) const { return false; }
bool operator==(NullStruct) const {
return true;
}
bool operator<(NullStruct) const {
return false;
}
};
/* * * * * * * * * * * * * * * * * * * *
@ -49,12 +53,14 @@ struct NullStruct {
*/
static void dump(NullStruct, QString& out, int* indent) {
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
out += "null";
}
static void dump(double value, QString& out, int* indent) {
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
if (std::isfinite(value)) {
char buf[32];
snprintf(buf, sizeof buf, "%.17g", value);
@ -65,19 +71,22 @@ static void dump(double value, QString &out, int *indent) {
}
static void dump(int value, QString& out, int* indent) {
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
char buf[32];
snprintf(buf, sizeof buf, "%d", value);
out += buf;
}
static void dump(bool value, QString& out, int* indent) {
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
out += value ? "true" : "false";
}
static void dump(const QString& value, QString& out, int* indent, bool isKey = false) {
if (!isKey && !out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!isKey && !out.endsWith(": "))
out += QString(*indent * 2, ' ');
out += '"';
for (int i = 0; i < value.length(); i++) {
const char ch = value[i].unicode();
@ -116,7 +125,8 @@ static void dump(const QString &value, QString &out, int *indent, bool isKey = f
static void dump(const Json::array& values, QString& out, int* indent) {
bool first = true;
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
out += "[\n";
*indent += 1;
for (const auto& value : values) {
@ -132,7 +142,8 @@ static void dump(const Json::array &values, QString &out, int *indent) {
static void dump(const Json::object& values, QString& out, int* indent) {
bool first = true;
if (!out.endsWith(": ")) out += QString(*indent * 2, ' ');
if (!out.endsWith(": "))
out += QString(*indent * 2, ' ');
out += "{\n";
*indent += 1;
for (auto kv : values) {
@ -149,7 +160,6 @@ static void dump(const Json::object &values, QString &out, int *indent) {
out += "\n" + QString(*indent * 2, ' ') + "}";
}
void Json::dump(QString& out, int* indent) const {
m_ptr->dump(out, indent);
}
@ -158,13 +168,13 @@ void Json::dump(QString &out, int *indent) const {
* Value wrappers
*/
template <Json::Type tag, typename T>
class Value : public JsonValue {
template <Json::Type tag, typename T> class Value : public JsonValue {
protected:
// Constructors
explicit Value(const T &value) : m_value(value) {}
explicit Value(T &&value) : m_value(move(value)) {}
explicit Value(const T& value) : m_value(value) {
}
explicit Value(T&& value) : m_value(move(value)) {
}
// Get type tag
Json::Type type() const override {
@ -180,59 +190,101 @@ protected:
}
const T m_value;
void dump(QString &out, int *indent) const override { poryjson::dump(m_value, out, indent); }
void dump(QString& out, int* indent) const override {
poryjson::dump(m_value, out, indent);
}
};
class JsonDouble final : public Value<Json::NUMBER, double> {
double number_value() const override { return m_value; }
int int_value() const override { return static_cast<int>(m_value); }
bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
bool less(const JsonValue * other) const override { return m_value < other->number_value(); }
double number_value() const override {
return m_value;
}
int int_value() const override {
return static_cast<int>(m_value);
}
bool equals(const JsonValue* other) const override {
return m_value == other->number_value();
}
bool less(const JsonValue* other) const override {
return m_value < other->number_value();
}
public:
explicit JsonDouble(double value) : Value(value) {}
explicit JsonDouble(double value) : Value(value) {
}
};
class JsonInt final : public Value<Json::NUMBER, int> {
double number_value() const override { return m_value; }
int int_value() const override { return m_value; }
bool equals(const JsonValue * other) const override { return m_value == other->number_value(); }
bool less(const JsonValue * other) const override { return m_value < other->number_value(); }
double number_value() const override {
return m_value;
}
int int_value() const override {
return m_value;
}
bool equals(const JsonValue* other) const override {
return m_value == other->number_value();
}
bool less(const JsonValue* other) const override {
return m_value < other->number_value();
}
public:
explicit JsonInt(int value) : Value(value) {}
explicit JsonInt(int value) : Value(value) {
}
};
class JsonBoolean final : public Value<Json::BOOL, bool> {
bool bool_value() const override { return m_value; }
bool bool_value() const override {
return m_value;
}
public:
explicit JsonBoolean(bool value) : Value(value) {}
explicit JsonBoolean(bool value) : Value(value) {
}
};
class JsonString final : public Value<Json::STRING, QString> {
const QString &string_value() const override { return m_value; }
const QString& string_value() const override {
return m_value;
}
public:
explicit JsonString(const QString &value) : Value(value) {}
explicit JsonString(QString &&value) : Value(move(value)) {}
explicit JsonString(const QString& value) : Value(value) {
}
explicit JsonString(QString&& value) : Value(move(value)) {
}
};
class JsonArray final : public Value<Json::ARRAY, Json::array> {
const Json::array &array_items() const override { return m_value; }
const Json::array& array_items() const override {
return m_value;
}
const Json& operator[](int i) const override;
public:
explicit JsonArray(const Json::array &value) : Value(value) {}
explicit JsonArray(Json::array &&value) : Value(move(value)) {}
explicit JsonArray(const Json::array& value) : Value(value) {
}
explicit JsonArray(Json::array&& value) : Value(move(value)) {
}
};
class JsonObject final : public Value<Json::OBJECT, Json::object> {
const Json::object &object_items() const override { return m_value; }
const Json::object& object_items() const override {
return m_value;
}
const Json& operator[](const QString& key) const override;
public:
explicit JsonObject(const Json::object &value) : Value(value) {}
explicit JsonObject(Json::object &&value) : Value(move(value)) {}
explicit JsonObject(const Json::object& value) : Value(value) {
}
explicit JsonObject(Json::object&& value) : Value(move(value)) {
}
};
class JsonNull final : public Value<Json::NUL, NullStruct> {
public:
JsonNull() : Value({}) {}
JsonNull() : Value({}) {
}
};
/* * * * * * * * * * * * * * * * * * * *
@ -245,7 +297,8 @@ struct Statics {
const QString empty_string;
const QVector<Json> empty_vector;
const Json::object empty_map;
Statics() {}
Statics() {
}
};
static const Statics& statics() {
@ -263,49 +316,97 @@ static const Json & static_null() {
* Constructors
*/
Json::Json() noexcept : m_ptr(statics().null) {}
Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {}
Json::Json(double value) : m_ptr(make_shared<JsonDouble>(value)) {}
Json::Json(int value) : m_ptr(make_shared<JsonInt>(value)) {}
Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {}
Json::Json(const QString &value) : m_ptr(make_shared<JsonString>(value)) {}
Json::Json(QString &&value) : m_ptr(make_shared<JsonString>(move(value))) {}
Json::Json(const char * value) : m_ptr(make_shared<JsonString>(value)) {}
Json::Json(const Json::array &values) : m_ptr(make_shared<JsonArray>(values)) {}
Json::Json(Json::array &&values) : m_ptr(make_shared<JsonArray>(move(values))) {}
Json::Json(const Json::object &values) : m_ptr(make_shared<JsonObject>(values)) {}
Json::Json(Json::object &&values) : m_ptr(make_shared<JsonObject>(move(values))) {}
Json::Json() noexcept : m_ptr(statics().null) {
}
Json::Json(std::nullptr_t) noexcept : m_ptr(statics().null) {
}
Json::Json(double value) : m_ptr(make_shared<JsonDouble>(value)) {
}
Json::Json(int value) : m_ptr(make_shared<JsonInt>(value)) {
}
Json::Json(bool value) : m_ptr(value ? statics().t : statics().f) {
}
Json::Json(const QString& value) : m_ptr(make_shared<JsonString>(value)) {
}
Json::Json(QString&& value) : m_ptr(make_shared<JsonString>(move(value))) {
}
Json::Json(const char* value) : m_ptr(make_shared<JsonString>(value)) {
}
Json::Json(const Json::array& values) : m_ptr(make_shared<JsonArray>(values)) {
}
Json::Json(Json::array&& values) : m_ptr(make_shared<JsonArray>(move(values))) {
}
Json::Json(const Json::object& values) : m_ptr(make_shared<JsonObject>(values)) {
}
Json::Json(Json::object&& values) : m_ptr(make_shared<JsonObject>(move(values))) {
}
/* * * * * * * * * * * * * * * * * * * *
* Accessors
*/
Json::Type Json::type() const { return m_ptr->type(); }
double Json::number_value() const { return m_ptr->number_value(); }
int Json::int_value() const { return m_ptr->int_value(); }
bool Json::bool_value() const { return m_ptr->bool_value(); }
const QString & Json::string_value() const { return m_ptr->string_value(); }
const QVector<Json> & Json::array_items() const { return m_ptr->array_items(); }
const Json::object & Json::object_items() const { return m_ptr->object_items(); }
const Json & Json::operator[] (int i) const { return (*m_ptr)[i]; }
const Json & Json::operator[] (const QString &key) const { return (*m_ptr)[key]; }
Json::Type Json::type() const {
return m_ptr->type();
}
double Json::number_value() const {
return m_ptr->number_value();
}
int Json::int_value() const {
return m_ptr->int_value();
}
bool Json::bool_value() const {
return m_ptr->bool_value();
}
const QString& Json::string_value() const {
return m_ptr->string_value();
}
const QVector<Json>& Json::array_items() const {
return m_ptr->array_items();
}
const Json::object& Json::object_items() const {
return m_ptr->object_items();
}
const Json& Json::operator[](int i) const {
return (*m_ptr)[i];
}
const Json& Json::operator[](const QString& key) const {
return (*m_ptr)[key];
}
double JsonValue::number_value() const { return 0; }
int JsonValue::int_value() const { return 0; }
bool JsonValue::bool_value() const { return false; }
const QString & JsonValue::string_value() const { return statics().empty_string; }
const QVector<Json> & JsonValue::array_items() const { return statics().empty_vector; }
const Json::object & JsonValue::object_items() const { return statics().empty_map; }
const Json & JsonValue::operator[] (int) const { return static_null(); }
const Json & JsonValue::operator[] (const QString &) const { return static_null(); }
double JsonValue::number_value() const {
return 0;
}
int JsonValue::int_value() const {
return 0;
}
bool JsonValue::bool_value() const {
return false;
}
const QString& JsonValue::string_value() const {
return statics().empty_string;
}
const QVector<Json>& JsonValue::array_items() const {
return statics().empty_vector;
}
const Json::object& JsonValue::object_items() const {
return statics().empty_map;
}
const Json& JsonValue::operator[](int) const {
return static_null();
}
const Json& JsonValue::operator[](const QString&) const {
return static_null();
}
const Json& JsonObject::operator[](const QString& key) const {
static auto iter = m_value.find(key);
return (iter == m_value.end()) ? static_null() : (*iter).second;
}
const Json& JsonArray::operator[](int i) const {
if (i >= m_value.size()) return static_null();
else return m_value[i];
if (i >= m_value.size())
return static_null();
else
return m_value[i];
}
/* * * * * * * * * * * * * * * * * * * *
@ -375,8 +476,7 @@ struct JsonParser final {
return fail(move(msg), Json());
}
template <typename T>
T fail(QString &&msg, const T err_ret) {
template <typename T> T fail(QString&& msg, const T err_ret) {
if (!failed)
err = std::move(msg);
failed = true;
@ -409,8 +509,7 @@ struct JsonParser final {
i++;
}
comment_found = true;
}
else if (str[i] == '*') { // multiline comment
} else if (str[i] == '*') { // multiline comment
i++;
if (i > str.size() - 2)
return fail("unexpected end of input inside multi-line comment", false);
@ -418,13 +517,11 @@ struct JsonParser final {
while (!(str[i] == '*' && str[i + 1] == '/')) {
i++;
if (i > str.size() - 2)
return fail(
"unexpected end of input inside multi-line comment", false);
return fail("unexpected end of input inside multi-line comment", false);
}
i += 2;
comment_found = true;
}
else
} else
return fail("malformed comment", false);
}
return comment_found;
@ -440,10 +537,10 @@ struct JsonParser final {
bool comment_found = false;
do {
comment_found = consume_comment();
if (failed) return;
if (failed)
return;
consume_whitespace();
}
while(comment_found);
} while (comment_found);
}
}
@ -454,7 +551,8 @@ struct JsonParser final {
*/
char get_next_token() {
consume_garbage();
if (failed) return static_cast<char>(0);
if (failed)
return static_cast<char>(0);
if (i == str.size())
return fail("unexpected end of input", static_cast<char>(0));
@ -531,8 +629,7 @@ struct JsonParser final {
return fail(QString("bad \\u escape: " + esc), "");
}
for (unsigned j = 0; j < 4; j++) {
if (!in_range(esc[j].unicode(), 'a', 'f') && !in_range(esc[j].unicode(), 'A', 'F')
&& !in_range(esc[j].unicode(), '0', '9'))
if (!in_range(esc[j].unicode(), 'a', 'f') && !in_range(esc[j].unicode(), 'A', 'F') && !in_range(esc[j].unicode(), '0', '9'))
return fail(QString("bad \\u escape: " + esc), "");
}
@ -542,12 +639,10 @@ struct JsonParser final {
// of 4-hex-digit \u escapes encoding their surrogate pair components. Check
// whether we're in the middle of such a beast: the previous codepoint was an
// escaped lead (high) surrogate, and this is a trail (low) surrogate.
if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF)
&& in_range(codepoint, 0xDC00, 0xDFFF)) {
if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) && in_range(codepoint, 0xDC00, 0xDFFF)) {
// Reassemble the two surrogate pairs into one astral-plane character, per
// the UTF-16 algorithm.
encode_utf8((((last_escaped_codepoint - 0xD800) << 10)
| (codepoint - 0xDC00)) + 0x10000, out);
encode_utf8((((last_escaped_codepoint - 0xD800) << 10) | (codepoint - 0xDC00)) + 0x10000, out);
last_escaped_codepoint = -1;
} else {
encode_utf8(last_escaped_codepoint, out);
@ -602,8 +697,7 @@ struct JsonParser final {
return fail(QString("invalid " + esc(str[i].unicode()) + " in number"));
}
if (str[i] != '.' && str[i] != 'e' && str[i] != 'E'
&& (i - start_pos) <= static_cast<unsigned>(std::numeric_limits<int>::digits10)) {
if (str[i] != '.' && str[i] != 'e' && str[i] != 'E' && (i - start_pos) <= static_cast<unsigned>(std::numeric_limits<int>::digits10)) {
return std::atoi(str.toStdString().c_str() + start_pos);
}

View file

@ -35,8 +35,7 @@ void logError(QString message) {
QString colorizeMessage(QString message, LogType type) {
QString colorized = message;
switch (type)
{
switch (type) {
case LogType::LOG_INFO:
colorized = colorized.replace("INFO", INFO_COLOR "INFO" CLEAR_COLOR);
break;
@ -53,8 +52,7 @@ QString colorizeMessage(QString message, LogType type) {
void log(QString message, LogType type) {
QString now = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
QString typeString = "";
switch (type)
{
switch (type) {
case LogType::LOG_INFO:
typeString = " [INFO]";
break;

View file

@ -1,8 +1,7 @@
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
a.setStyle("fusion");
MainWindow w(nullptr);

File diff suppressed because it is too large Load diff

View file

@ -24,10 +24,8 @@ void MainWindow::tryCommitMapChanges(bool commitChanges) {
if (commitChanges) {
Map* map = this->editor->map;
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->editHistory.push(new ScriptEditMap(map, map->layout->lastCommitMapBlocks.dimensions, QSize(map->getWidth(), map->getHeight()),
map->layout->lastCommitMapBlocks.blocks, map->layout->blockdata));
}
}
}
@ -484,9 +482,7 @@ void MainWindow::registerAction(QString functionName, QString actionName, QStrin
QAction* section = this->ui->menuTools->addSection("Custom Actions");
this->registeredActions.append(section);
}
QAction *action = this->ui->menuTools->addAction(actionName, [actionName](){
Scripting::invokeAction(actionName);
});
QAction* action = this->ui->menuTools->addAction(actionName, [actionName]() { Scripting::invokeAction(actionName); });
if (!shortcut.isEmpty()) {
action->setShortcut(QKeySequence(shortcut));
}
@ -498,9 +494,7 @@ void MainWindow::setTimeout(QJSValue callback, int milliseconds) {
return;
QTimer* timer = new QTimer(0);
connect(timer, &QTimer::timeout, [=](){
this->invokeCallback(callback);
});
connect(timer, &QTimer::timeout, [=]() { this->invokeCallback(callback); });
connect(timer, &QTimer::timeout, timer, &QTimer::deleteLater);
timer->setSingleShot(true);
timer->start(milliseconds);

View file

@ -36,13 +36,11 @@ int Project::max_map_data_size = 10240; // 0x2800
int Project::default_map_size = 20;
int Project::max_object_events = 64;
Project::Project(QWidget *parent) : QObject(parent)
{
Project::Project(QWidget* parent) : QObject(parent) {
initSignals();
}
Project::~Project()
{
Project::~Project() {
clearMapCache();
clearTilesetCache();
}
@ -50,7 +48,8 @@ Project::~Project()
void Project::initSignals() {
// detect changes to specific filepaths being monitored
QObject::connect(&fileWatcher, &QFileSystemWatcher::fileChanged, [this](QString changed) {
if (!porymapConfig.getMonitorFiles()) return;
if (!porymapConfig.getMonitorFiles())
return;
if (modifiedFileTimestamps.contains(changed)) {
if (QDateTime::currentMSecsSinceEpoch() < modifiedFileTimestamps[changed]) {
return;
@ -59,12 +58,12 @@ void Project::initSignals() {
}
static bool showing = false;
if (showing) return;
if (showing)
return;
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 + "/")));
notice.setInformativeText(QString("The file %1 has changed on disk. Would you like to reload the project?").arg(changed.remove(this->root + "/")));
notice.setStandardButtons(QMessageBox::No | QMessageBox::Yes);
notice.setIcon(QMessageBox::Question);
@ -101,7 +100,8 @@ QString Project::getProjectTitle() {
void Project::clearMapCache() {
for (QString mapName : mapCache.keys()) {
Map* map = mapCache.take(mapName);
if (map) delete map;
if (map)
delete map;
}
emit mapCacheCleared();
}
@ -109,7 +109,8 @@ void Project::clearMapCache() {
void Project::clearTilesetCache() {
for (QString tilesetName : tilesetCache.keys()) {
Tileset* tileset = tilesetCache.take(tilesetName);
if (tileset) delete tileset;
if (tileset)
delete tileset;
}
}
@ -138,23 +139,9 @@ void Project::setNewMapConnections(Map *map) {
}
static QMap<QString, bool> defaultTopLevelMapFields{
{"id", true},
{"name", true},
{"layout", true},
{"music", true},
{"region_map_section", true},
{"requires_flash", true},
{"weather", true},
{"map_type", true},
{"show_map_name", true},
{"battle_scene", true},
{"connections", true},
{"object_events", true},
{"warp_events", true},
{"coord_events", true},
{"bg_events", true},
{"shared_events_map", true},
{"shared_scripts_map", true},
{ "id", true }, { "name", true }, { "layout", true }, { "music", true }, { "region_map_section", true }, { "requires_flash", true }, { "weather", true },
{ "map_type", true }, { "show_map_name", true }, { "battle_scene", true }, { "connections", true }, { "object_events", true }, { "warp_events", true },
{ "coord_events", true }, { "bg_events", true }, { "shared_events_map", true }, { "shared_scripts_map", true },
};
QMap<QString, bool> Project::getTopLevelMapFields() {
@ -280,7 +267,6 @@ bool Project::loadMapData(Map* map) {
}
map->events["heal_event_group"].append(heal);
}
}
map->events["coord_event_group"].clear();
@ -459,9 +445,7 @@ bool Project::loadMapLayout(Map* map) {
bool loadedBlockdata = loadBlockdata(map);
bool loadedBorder = loadMapBorder(map);
return loadedTilesets
&& loadedBlockdata
&& loadedBorder;
return loadedTilesets && loadedBlockdata && loadedBorder;
}
bool Project::readMapLayouts() {
@ -486,20 +470,11 @@ bool Project::readMapLayouts() {
layoutsLabel = layoutsObj["layouts_table_label"].toString();
if (layoutsLabel.isNull()) {
layoutsLabel = "gMapLayouts";
logWarn(QString("'layouts_table_label' value is missing from %1. Defaulting to %2")
.arg(layoutsFilepath)
.arg(layoutsLabel));
logWarn(QString("'layouts_table_label' value is missing from %1. Defaulting to %2").arg(layoutsFilepath).arg(layoutsLabel));
}
QList<QString> requiredFields = QList<QString>{
"id",
"name",
"width",
"height",
"primary_tileset",
"secondary_tileset",
"border_filepath",
"blockdata_filepath",
"id", "name", "width", "height", "primary_tileset", "secondary_tileset", "border_filepath", "blockdata_filepath",
};
bool useCustomBorderSize = projectConfig.getUseCustomBorderSize();
if (useCustomBorderSize) {
@ -540,13 +515,21 @@ bool Project::readMapLayouts() {
if (useCustomBorderSize) {
int bwidth = layoutObj["border_width"].toInt();
if (bwidth <= 0) { // 0 is an expected border width/height that should be handled, GF used it for the RS layouts in FRLG
logWarn(QString("Invalid layout 'border_width' value '%1' on layout %2 in %3. Must be greater than 0. Using default (%4) instead.").arg(bwidth).arg(i).arg(layoutsFilepath).arg(DEFAULT_BORDER_WIDTH));
logWarn(QString("Invalid layout 'border_width' value '%1' on layout %2 in %3. Must be greater than 0. Using default (%4) instead.")
.arg(bwidth)
.arg(i)
.arg(layoutsFilepath)
.arg(DEFAULT_BORDER_WIDTH));
bwidth = DEFAULT_BORDER_WIDTH;
}
layout->border_width = QString::number(bwidth);
int bheight = layoutObj["border_height"].toInt();
if (bheight <= 0) {
logWarn(QString("Invalid layout 'border_height' value '%1' on layout %2 in %3. Must be greater than 0. Using default (%4) instead.").arg(bheight).arg(i).arg(layoutsFilepath).arg(DEFAULT_BORDER_HEIGHT));
logWarn(QString("Invalid layout 'border_height' value '%1' on layout %2 in %3. Must be greater than 0. Using default (%4) instead.")
.arg(bheight)
.arg(i)
.arg(layoutsFilepath)
.arg(DEFAULT_BORDER_HEIGHT));
bheight = DEFAULT_BORDER_HEIGHT;
}
layout->border_height = QString::number(bheight);
@ -642,7 +625,8 @@ void Project::setNewMapLayout(Map* map) {
layout->border_path = QString("data/layouts/%1/border.bin").arg(map->name);
layout->blockdata_path = QString("data/layouts/%1/map.bin").arg(map->name);
layout->tileset_primary_label = tilesetLabels["primary"].value(0, "gTileset_General");
layout->tileset_secondary_label = tilesetLabels["secondary"].value(0, projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered ? "gTileset_PalletTown" : "gTileset_Petalburg");
layout->tileset_secondary_label = tilesetLabels["secondary"].value(
0, projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered ? "gTileset_PalletTown" : "gTileset_Petalburg");
map->layout = layout;
map->layoutId = layout->id;
@ -687,7 +671,8 @@ void Project::saveMapGroups() {
}
void Project::saveWildMonData() {
if (!projectConfig.getEncounterJsonActive()) return;
if (!projectConfig.getEncounterJsonActive())
return;
QString wildEncountersJsonFilepath = QString("%1/src/data/wild_encounters.json").arg(root);
QFile wildEncountersFile(wildEncountersJsonFilepath);
@ -725,7 +710,8 @@ void Project::saveWildMonData() {
}
groupsObject[groupName] = subGroupIndices;
}
if (!groupsObject.empty()) fieldObject["groups"] = groupsObject;
if (!groupsObject.empty())
fieldObject["groups"] = groupsObject;
fieldsInfoArray.append(fieldObject);
}
@ -872,15 +858,9 @@ void Project::saveHealLocationStruct(Map *map) {
// Save constants
if (map_in.index != 0) {
constants_text += QString("#define %1%2 %3\n")
.arg(constantPrefix)
.arg(map_in.idName)
.arg(map_in.index);
constants_text += QString("#define %1%2 %3\n").arg(constantPrefix).arg(map_in.idName).arg(map_in.index);
} else {
constants_text += QString("#define %1%2 %3\n")
.arg(constantPrefix)
.arg(map_in.idName)
.arg(i);
constants_text += QString("#define %1%2 %3\n").arg(constantPrefix).arg(map_in.idName).arg(i);
}
i++;
}
@ -890,10 +870,7 @@ void Project::saveHealLocationStruct(Map *map) {
.arg(dataQualifiers.value("heal_locations").isStatic ? "static " : "")
.arg(dataQualifiers.value("heal_locations").isConst ? "const " : "");
for (auto map_in : healLocations) {
data_text += QString(" [%1%2 - 1] = {MAP_GROUP(%3), MAP_NUM(%3)},\n")
.arg(constantPrefix)
.arg(map_in.idName)
.arg(map_in.respawnMap);
data_text += QString(" [%1%2 - 1] = {MAP_GROUP(%3), MAP_NUM(%3)},\n").arg(constantPrefix).arg(map_in.idName).arg(map_in.respawnMap);
}
// Save third array (object id of NPC player speaks to upon respawning for each heal location)
@ -901,10 +878,7 @@ void Project::saveHealLocationStruct(Map *map) {
.arg(dataQualifiers.value("heal_locations").isStatic ? "static " : "")
.arg(dataQualifiers.value("heal_locations").isConst ? "const " : "");
for (auto map_in : healLocations) {
data_text += QString(" [%1%2 - 1] = %3,\n")
.arg(constantPrefix)
.arg(map_in.idName)
.arg(map_in.respawnNPC);
data_text += QString(" [%1%2 - 1] = %3,\n").arg(constantPrefix).arg(map_in.idName).arg(map_in.respawnNPC);
}
}
@ -976,9 +950,7 @@ void Project::saveTilesetMetatileLabels(Tileset *primaryTileset, Tileset *second
return;
}
auto getTilesetFromLabel = [](QString labelName) {
return QRegularExpression("METATILE_(?<tileset>[A-Za-z0-9]+)_").match(labelName).captured("tileset");
};
auto getTilesetFromLabel = [](QString labelName) { return QRegularExpression("METATILE_(?<tileset>[A-Za-z0-9]+)_").match(labelName).captured("tileset"); };
QString outputText = "#ifndef GUARD_METATILE_LABELS_H\n";
outputText += "#define GUARD_METATILE_LABELS_H\n";
@ -1001,9 +973,7 @@ void Project::saveTilesetMetatileLabels(Tileset *primaryTileset, Tileset *second
}
for (QString defineName : definesOut.keys()) {
int value = defines[defineName];
QString line = QString("#define %1 0x%2\n")
.arg(defineName, -1 * longestLength)
.arg(QString("%1").arg(value, 3, 16, QChar('0')).toUpper());
QString line = QString("#define %1 0x%2\n").arg(defineName, -1 * longestLength).arg(QString("%1").arg(value, 3, 16, QChar('0')).toUpper());
outputText += line;
}
i += j;
@ -1023,11 +993,9 @@ void Project::saveTilesetMetatileAttributes(Tileset *tileset) {
if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) {
for (Metatile* metatile : tileset->metatiles) {
data.append(static_cast<char>(metatile->behavior));
data.append(static_cast<char>(metatile->behavior >> 8) |
static_cast<char>(metatile->terrainType << 1));
data.append(static_cast<char>(metatile->behavior >> 8) | static_cast<char>(metatile->terrainType << 1));
data.append(static_cast<char>(0));
data.append(static_cast<char>(metatile->encounterType) |
static_cast<char>(metatile->layerType << 5));
data.append(static_cast<char>(metatile->encounterType) | static_cast<char>(metatile->layerType << 5));
}
} else {
for (Metatile* metatile : tileset->metatiles) {
@ -1049,10 +1017,8 @@ void Project::saveTilesetMetatiles(Tileset *tileset) {
int numTiles = projectConfig.getTripleLayerMetatilesEnabled() ? 12 : 8;
for (int i = 0; i < numTiles; i++) {
Tile tile = metatile->tiles.at(i);
uint16_t value = static_cast<uint16_t>((tile.tile & 0x3ff)
| ((tile.xflip & 1) << 10)
| ((tile.yflip & 1) << 11)
| ((tile.palette & 0xf) << 12));
uint16_t value
= static_cast<uint16_t>((tile.tile & 0x3ff) | ((tile.xflip & 1) << 10) | ((tile.yflip & 1) << 11) | ((tile.palette & 0xf) << 12));
data.append(static_cast<char>(value & 0xff));
data.append(static_cast<char>((value >> 8) & 0xff));
}
@ -1084,7 +1050,10 @@ bool Project::loadMapTilesets(Map* map) {
map->layout->tileset_primary = getTileset(map->layout->tileset_primary_label);
if (!map->layout->tileset_primary) {
QString defaultTileset = tilesetLabels["primary"].value(0, "gTileset_General");
logWarn(QString("Map layout %1 has invalid primary tileset '%2'. Using default '%3'").arg(map->layout->id).arg(map->layout->tileset_primary_label).arg(defaultTileset));
logWarn(QString("Map layout %1 has invalid primary tileset '%2'. Using default '%3'")
.arg(map->layout->id)
.arg(map->layout->tileset_primary_label)
.arg(defaultTileset));
map->layout->tileset_primary_label = defaultTileset;
map->layout->tileset_primary = getTileset(map->layout->tileset_primary_label);
if (!map->layout->tileset_primary) {
@ -1095,8 +1064,12 @@ bool Project::loadMapTilesets(Map* map) {
map->layout->tileset_secondary = getTileset(map->layout->tileset_secondary_label);
if (!map->layout->tileset_secondary) {
QString defaultTileset = tilesetLabels["secondary"].value(0, projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered ? "gTileset_PalletTown" : "gTileset_Petalburg");
logWarn(QString("Map layout %1 has invalid secondary tileset '%2'. Using default '%3'").arg(map->layout->id).arg(map->layout->tileset_secondary_label).arg(defaultTileset));
QString defaultTileset = tilesetLabels["secondary"].value(
0, projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered ? "gTileset_PalletTown" : "gTileset_Petalburg");
logWarn(QString("Map layout %1 has invalid secondary tileset '%2'. Using default '%3'")
.arg(map->layout->id)
.arg(map->layout->tileset_secondary_label)
.arg(defaultTileset));
map->layout->tileset_secondary_label = defaultTileset;
map->layout->tileset_secondary = getTileset(map->layout->tileset_secondary_label);
if (!map->layout->tileset_secondary) {
@ -1175,9 +1148,7 @@ bool Project::loadMapBorder(Map *map) {
map->layout->border = readBlockdata(path);
int borderLength = map->getBorderWidth() * map->getBorderHeight();
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(borderLength));
logWarn(QString("Layout border blockdata length %1 must be %2. Resizing border blockdata.").arg(map->layout->border.count()).arg(borderLength));
map->layout->border.resize(borderLength);
}
return true;
@ -1596,16 +1567,15 @@ void Project::loadTilesetMetatiles(Tileset* tileset) {
if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokefirered) {
int num_metatileAttrs = data.length() / 4;
if (num_metatiles != num_metatileAttrs) {
logWarn(QString("Metatile count %1 does not match metatile attribute count %2 in %3").arg(num_metatiles).arg(num_metatileAttrs).arg(tileset->name));
logWarn(
QString("Metatile count %1 does not match metatile attribute count %2 in %3").arg(num_metatiles).arg(num_metatileAttrs).arg(tileset->name));
if (num_metatileAttrs > num_metatiles)
num_metatileAttrs = num_metatiles;
}
bool unusedAttribute = false;
for (int i = 0; i < num_metatileAttrs; i++) {
int value = (static_cast<unsigned char>(data.at(i * 4 + 3)) << 24) |
(static_cast<unsigned char>(data.at(i * 4 + 2)) << 16) |
(static_cast<unsigned char>(data.at(i * 4 + 1)) << 8) |
(static_cast<unsigned char>(data.at(i * 4 + 0)));
int value = (static_cast<unsigned char>(data.at(i * 4 + 3)) << 24) | (static_cast<unsigned char>(data.at(i * 4 + 2)) << 16)
| (static_cast<unsigned char>(data.at(i * 4 + 1)) << 8) | (static_cast<unsigned char>(data.at(i * 4 + 0)));
tileset->metatiles.at(i)->behavior = value & 0x1FF;
tileset->metatiles.at(i)->terrainType = (value & 0x3E00) >> 9;
tileset->metatiles.at(i)->encounterType = (value & 0x7000000) >> 24;
@ -1618,7 +1588,8 @@ void Project::loadTilesetMetatiles(Tileset* tileset) {
} else {
int num_metatileAttrs = data.length() / 2;
if (num_metatiles != num_metatileAttrs) {
logWarn(QString("Metatile count %1 does not match metatile attribute count %2 in %3").arg(num_metatiles).arg(num_metatileAttrs).arg(tileset->name));
logWarn(
QString("Metatile count %1 does not match metatile attribute count %2 in %3").arg(num_metatiles).arg(num_metatileAttrs).arg(tileset->name));
if (num_metatileAttrs > num_metatiles)
num_metatileAttrs = num_metatiles;
}
@ -1942,10 +1913,10 @@ QMap<QString, QStringList> Project::getTilesetLabels() {
QString tilesetLabel = match.captured("label");
QString secondaryTilesetValue = match.captured("isSecondary");
if (secondaryTilesetValue != "1" && secondaryTilesetValue != "TRUE"
&& secondaryTilesetValue != "0" && secondaryTilesetValue != "FALSE") {
if (secondaryTilesetValue != "1" && secondaryTilesetValue != "TRUE" && secondaryTilesetValue != "0" && secondaryTilesetValue != "FALSE") {
logWarn(QString("Unexpected secondary tileset flag found in %1. Expected 'TRUE', 'FALSE', '1', or '0', but found '%2'")
.arg(tilesetLabel).arg(secondaryTilesetValue));
.arg(tilesetLabel)
.arg(secondaryTilesetValue));
continue;
}
@ -1969,50 +1940,38 @@ bool Project::readTilesetProperties() {
auto it = defines.find("NUM_TILES_IN_PRIMARY");
if (it != defines.end()) {
Project::num_tiles_primary = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_TILES_IN_PRIMARY' not found. Using default (%1) instead.")
.arg(Project::num_tiles_primary));
} else {
logWarn(QString("Value for tileset property 'NUM_TILES_IN_PRIMARY' not found. Using default (%1) instead.").arg(Project::num_tiles_primary));
}
it = defines.find("NUM_TILES_TOTAL");
if (it != defines.end()) {
Project::num_tiles_total = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_TILES_TOTAL' not found. Using default (%1) instead.")
.arg(Project::num_tiles_total));
} else {
logWarn(QString("Value for tileset property 'NUM_TILES_TOTAL' not found. Using default (%1) instead.").arg(Project::num_tiles_total));
}
it = defines.find("NUM_METATILES_IN_PRIMARY");
if (it != defines.end()) {
Project::num_metatiles_primary = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_METATILES_IN_PRIMARY' not found. Using default (%1) instead.")
.arg(Project::num_metatiles_primary));
} else {
logWarn(QString("Value for tileset property 'NUM_METATILES_IN_PRIMARY' not found. Using default (%1) instead.").arg(Project::num_metatiles_primary));
}
it = defines.find("NUM_METATILES_TOTAL");
if (it != defines.end()) {
Project::num_metatiles_total = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_METATILES_TOTAL' not found. Using default (%1) instead.")
.arg(Project::num_metatiles_total));
} else {
logWarn(QString("Value for tileset property 'NUM_METATILES_TOTAL' not found. Using default (%1) instead.").arg(Project::num_metatiles_total));
}
it = defines.find("NUM_PALS_IN_PRIMARY");
if (it != defines.end()) {
Project::num_pals_primary = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_PALS_IN_PRIMARY' not found. Using default (%1) instead.")
.arg(Project::num_pals_primary));
} else {
logWarn(QString("Value for tileset property 'NUM_PALS_IN_PRIMARY' not found. Using default (%1) instead.").arg(Project::num_pals_primary));
}
it = defines.find("NUM_PALS_TOTAL");
if (it != defines.end()) {
Project::num_pals_total = it.value();
}
else {
logWarn(QString("Value for tileset property 'NUM_PALS_TOTAL' not found. Using default (%1) instead.")
.arg(Project::num_pals_total));
} else {
logWarn(QString("Value for tileset property 'NUM_PALS_TOTAL' not found. Using default (%1) instead.").arg(Project::num_pals_total));
}
return true;
}
@ -2036,10 +1995,8 @@ bool Project::readMaxMapDataSize() {
.arg(min)
.arg(Project::max_map_data_size));
}
}
else {
logWarn(QString("Value for map property 'MAX_MAP_DATA_SIZE' not found. Using default (%1) instead.")
.arg(Project::max_map_data_size));
} else {
logWarn(QString("Value for map property 'MAX_MAP_DATA_SIZE' not found. Using default (%1) instead.").arg(Project::max_map_data_size));
}
return true;
}
@ -2073,8 +2030,11 @@ bool Project::readHealLocations() {
if (projectConfig.getHealLocationRespawnDataEnabled()) {
dataQualifiers.insert("heal_locations", getDataQualifiers(text, "sSpawnPoints"));
QRegularExpression spawnRegex("SPAWN_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = \\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+,\\s*(?<x>[0-9A-Fa-fx]+),\\s*(?<y>[0-9A-Fa-fx]+)");
QRegularExpression respawnMapRegex("SPAWN_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = \\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+}");
QRegularExpression spawnRegex("SPAWN_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = "
"\\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+,\\s*(?<x>[0-9A-Fa-fx]+),\\s*(?<y>"
"[0-9A-Fa-fx]+)");
QRegularExpression respawnMapRegex(
"SPAWN_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = \\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+}");
QRegularExpression respawnNPCRegex("SPAWN_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = (?<npc>[0-9]+)");
QRegularExpressionMatchIterator spawns = spawnRegex.globalMatch(text);
QRegularExpressionMatchIterator respawnMaps = respawnMapRegex.globalMatch(text);
@ -2097,7 +2057,9 @@ bool Project::readHealLocations() {
} else {
dataQualifiers.insert("heal_locations", getDataQualifiers(text, "sHealLocations"));
QRegularExpression regex("HEAL_LOCATION_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = \\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+,\\s*(?<x>[0-9A-Fa-fx]+),\\s*(?<y>[0-9A-Fa-fx]+)");
QRegularExpression regex("HEAL_LOCATION_(?<id>[A-Za-z0-9_]+)\\s*- 1\\]\\s* = "
"\\{MAP_GROUP[\\(\\s]+(?<map>[A-Za-z0-9_]+)[\\s\\)]+,\\s*MAP_NUM[\\(\\s]+(\\2)[\\s\\)]+,\\s*(?<x>[0-9A-Fa-fx]+),\\s*(?<y>[0-"
"9A-Fa-fx]+)");
QRegularExpressionMatchIterator iter = regex.globalMatch(text);
for (int i = 1; iter.hasNext(); i++) {
QRegularExpressionMatch match = iter.next();
@ -2312,7 +2274,8 @@ bool Project::readMiscellaneousConstants() {
QString filename = "include/constants/pokemon.h";
fileWatcher.addPath(root + "/" + filename);
QMap<QString, int> 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(
"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);
}
@ -2330,10 +2293,8 @@ bool Project::readMiscellaneousConstants() {
.arg(it.value())
.arg(Project::max_object_events));
}
}
else {
logWarn(QString("Value for 'OBJECT_EVENT_TEMPLATES_COUNT' not found. Using default (%1) instead.")
.arg(Project::max_object_events));
} else {
logWarn(QString("Value for 'OBJECT_EVENT_TEMPLATES_COUNT' not found. Using default (%1) instead.").arg(Project::max_object_events));
}
return true;
@ -2421,7 +2382,8 @@ void Project::loadEventPixmaps(QList<Event*> objects) {
<< root + "/" + "src/data/object_events/object_event_pic_tables.h"
<< root + "/" + "src/data/object_events/object_event_graphics.h");
QMap<QString, QString> pointerHash = parser.readNamedIndexCArray("src/data/object_events/object_event_graphics_info_pointers.h", "gObjectEventGraphicsInfoPointers");
QMap<QString, QString> pointerHash
= parser.readNamedIndexCArray("src/data/object_events/object_event_graphics_info_pointers.h", "gObjectEventGraphicsInfoPointers");
for (Event* object : objects) {
if (!object->pixmap.isNull()) {
@ -2513,59 +2475,48 @@ void Project::setNewMapEvents(Map *map) {
map->events["bg_event_group"].clear();
}
int Project::getNumTilesPrimary()
{
int Project::getNumTilesPrimary() {
return Project::num_tiles_primary;
}
int Project::getNumTilesTotal()
{
int Project::getNumTilesTotal() {
return Project::num_tiles_total;
}
int Project::getNumMetatilesPrimary()
{
int Project::getNumMetatilesPrimary() {
return Project::num_metatiles_primary;
}
int Project::getNumMetatilesTotal()
{
int Project::getNumMetatilesTotal() {
return Project::num_metatiles_total;
}
int Project::getNumPalettesPrimary()
{
int Project::getNumPalettesPrimary() {
return Project::num_pals_primary;
}
int Project::getNumPalettesTotal()
{
int Project::getNumPalettesTotal() {
return Project::num_pals_total;
}
int Project::getMaxMapDataSize()
{
int Project::getMaxMapDataSize() {
return Project::max_map_data_size;
}
int Project::getMapDataSize(int width, int height)
{
int Project::getMapDataSize(int width, int height) {
// + 15 and + 14 come from fieldmap.c in pokeruby/pokeemerald/pokefirered.
return (width + 15) * (height + 14);
}
int Project::getDefaultMapSize()
{
int Project::getDefaultMapSize() {
return Project::default_map_size;
}
int Project::getMaxMapWidth()
{
int Project::getMaxMapWidth() {
return (getMaxMapDataSize() / (1 + 14)) - 15;
}
int Project::getMaxMapHeight()
{
int Project::getMaxMapHeight() {
return (getMaxMapDataSize() / (1 + 15)) - 14;
}
@ -2584,15 +2535,12 @@ bool Project::calculateDefaultMapSize(){
// x^2 + 29x + (210 - max), then complete the square and simplify
default_map_size = qFloor((qSqrt(4 * getMaxMapDataSize() + 1) - 29) / 2);
} else {
logError(QString("'MAX_MAP_DATA_SIZE' of %1 is too small to support a 1x1 map. Must be at least %2.")
.arg(max)
.arg(getMapDataSize(1, 1)));
logError(QString("'MAX_MAP_DATA_SIZE' of %1 is too small to support a 1x1 map. Must be at least %2.").arg(max).arg(getMapDataSize(1, 1)));
return false;
}
return true;
}
int Project::getMaxObjectEvents()
{
int Project::getMaxObjectEvents() {
return Project::max_object_events;
}

View file

@ -2,10 +2,7 @@
#include "log.h"
QMap<CallbackType, QString> callbackFunctions = {
{OnProjectOpened, "onProjectOpened"},
{OnProjectClosed, "onProjectClosed"},
{OnBlockChanged, "onBlockChanged"},
{OnMapOpened, "onMapOpened"},
{ OnProjectOpened, "onProjectOpened" }, { OnProjectClosed, "onProjectClosed" }, { OnBlockChanged, "onBlockChanged" }, { OnMapOpened, "onMapOpened" },
};
Scripting* instance = nullptr;
@ -68,18 +65,22 @@ void Scripting::invokeCallback(CallbackType type, QJSValueList args) {
}
void Scripting::registerAction(QString functionName, QString actionName) {
if (!instance) return;
if (!instance)
return;
instance->registeredActions.insert(actionName, functionName);
}
int Scripting::numRegisteredActions() {
if (!instance) return 0;
if (!instance)
return 0;
return instance->registeredActions.size();
}
void Scripting::invokeAction(QString actionName) {
if (!instance) return;
if (!instance->registeredActions.contains(actionName)) return;
if (!instance)
return;
if (!instance->registeredActions.contains(actionName))
return;
QString functionName = instance->registeredActions.value(actionName);
for (QJSValue module : instance->modules) {
@ -97,7 +98,8 @@ void Scripting::invokeAction(QString actionName) {
}
void Scripting::cb_ProjectOpened(QString projectPath) {
if (!instance) return;
if (!instance)
return;
QJSValueList args{
projectPath,
@ -106,7 +108,8 @@ void Scripting::cb_ProjectOpened(QString projectPath) {
}
void Scripting::cb_ProjectClosed(QString projectPath) {
if (!instance) return;
if (!instance)
return;
QJSValueList args{
projectPath,
@ -115,19 +118,18 @@ void Scripting::cb_ProjectClosed(QString projectPath) {
}
void Scripting::cb_MetatileChanged(int x, int y, Block prevBlock, Block newBlock) {
if (!instance) return;
if (!instance)
return;
QJSValueList args{
x,
y,
instance->fromBlock(prevBlock),
instance->fromBlock(newBlock),
x, y, instance->fromBlock(prevBlock), instance->fromBlock(newBlock),
};
instance->invokeCallback(OnBlockChanged, args);
}
void Scripting::cb_MapOpened(QString mapName) {
if (!instance) return;
if (!instance)
return;
QJSValueList args{
mapName,

View file

@ -1,7 +1,6 @@
#include "settings.h"
Settings::Settings()
{
Settings::Settings() {
this->smartPathsEnabled = false;
this->betterCursors = true;
this->playerViewRectEnabled = false;

View file

@ -1,14 +1,10 @@
#include "aboutporymap.h"
#include "ui_aboutporymap.h"
AboutPorymap::AboutPorymap(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::AboutPorymap)
{
AboutPorymap::AboutPorymap(QWidget* parent) : QMainWindow(parent), ui(new Ui::AboutPorymap) {
ui->setupUi(this);
}
AboutPorymap::~AboutPorymap()
{
AboutPorymap::~AboutPorymap() {
delete ui;
}

View file

@ -41,12 +41,8 @@ void BorderMetatilesPixmapItem::draw() {
int x = i * 16;
int y = j * 16;
int index = j * width + i;
QImage metatile_image = getMetatileImage(
map->layout->border.value(index).tile,
map->layout->tileset_primary,
map->layout->tileset_secondary,
map->metatileLayerOrder,
map->metatileLayerOpacity);
QImage metatile_image = getMetatileImage(map->layout->border.value(index).tile, map->layout->tileset_primary, map->layout->tileset_secondary,
map->metatileLayerOrder, map->metatileLayerOpacity);
QPoint metatile_origin = QPoint(x, y);
painter.drawImage(metatile_origin, metatile_image);
}

View file

@ -12,7 +12,8 @@ void CityMapPixmapItem::init() {
height_ = 10;
QFile binFile(file);
if (!binFile.open(QIODevice::ReadOnly)) return;
if (!binFile.open(QIODevice::ReadOnly))
return;
data = binFile.readAll();
if (projectConfig.getBaseGameVersion() == BaseGameVersion::pokeruby) {
@ -71,8 +72,7 @@ void CityMapPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
QPointF pos = event->pos();
int x = static_cast<int>(pos.x()) / 8;
int y = static_cast<int>(pos.y()) / 8;
if (x < width_ && x >= 0
&& y < height_ && y >= 0) {
if (x < width_ && x >= 0 && y < height_ && y >= 0) {
emit this->hoveredRegionMapTileChanged(x, y);
emit mouseEvent(event, this);
}

View file

@ -116,10 +116,14 @@ void CollisionPixmapItem::updateMovementPermissionSelection(QGraphicsSceneMouseE
QPoint pos = Metatile::coordFromPixmapCoord(event->pos());
// Snap point to within map bounds.
if (pos.x() < 0) pos.setX(0);
if (pos.x() >= map->getWidth()) pos.setX(map->getWidth() - 1);
if (pos.y() < 0) pos.setY(0);
if (pos.y() >= map->getHeight()) pos.setY(map->getHeight() - 1);
if (pos.x() < 0)
pos.setX(0);
if (pos.x() >= map->getWidth())
pos.setX(map->getWidth() - 1);
if (pos.y() < 0)
pos.setY(0);
if (pos.y() >= map->getHeight())
pos.setY(map->getHeight() - 1);
Block block;
if (map->getBlock(pos.x(), pos.y(), &block)) {

View file

@ -27,8 +27,7 @@ int ConnectionPixmapItem::getMaxOffset() {
return this->baseMapHeight + 6;
}
QVariant ConnectionPixmapItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
QVariant ConnectionPixmapItem::itemChange(GraphicsItemChange change, const QVariant& value) {
if (change == ItemPositionChange) {
QPointF newPos = value.toPointF();
@ -40,8 +39,7 @@ QVariant ConnectionPixmapItem::itemChange(GraphicsItemChange change, const QVari
newOffset = qMin(newOffset, this->getMaxOffset());
newOffset = qMax(newOffset, this->getMinOffset());
x = newOffset * 16;
}
else {
} else {
x = this->initialX;
}
@ -51,16 +49,14 @@ QVariant ConnectionPixmapItem::itemChange(GraphicsItemChange change, const QVari
newOffset = qMin(newOffset, this->getMaxOffset());
newOffset = qMax(newOffset, this->getMinOffset());
y = newOffset * 16;
}
else {
} else {
y = this->initialY;
}
this->connection->offset = QString::number(newOffset);
emit connectionMoved(this->connection);
return QPointF(x, y);
}
else {
} else {
return QGraphicsItem::itemChange(change, value);
}
}

View file

@ -16,11 +16,7 @@ void CurrentSelectedMetatilesPixmapItem::draw() {
int y = j * 16;
int index = j * selectionDimensions.x() + i;
QImage metatile_image = getMetatileImage(
selectedMetatiles->at(index),
map->layout->tileset_primary,
map->layout->tileset_secondary,
map->metatileLayerOrder,
map->metatileLayerOpacity);
selectedMetatiles->at(index), map->layout->tileset_primary, map->layout->tileset_secondary, map->metatileLayerOrder, map->metatileLayerOpacity);
QPoint metatile_origin = QPoint(x, y);
painter.drawImage(metatile_origin, metatile_image);
}

View file

@ -1,8 +1,7 @@
#include "cursortilerect.h"
#include "log.h"
CursorTileRect::CursorTileRect(bool *enabled, QRgb color)
{
CursorTileRect::CursorTileRect(bool* enabled, QRgb color) {
this->enabled = enabled;
this->visible = true;
this->color = color;
@ -19,37 +18,31 @@ CursorTileRect::CursorTileRect(bool *enabled, QRgb color)
this->selectionHeight = 1;
}
void CursorTileRect::setVisibility(bool visible)
{
void CursorTileRect::setVisibility(bool visible) {
this->visible = visible;
}
void CursorTileRect::initAnchor(int coordX, int coordY)
{
void CursorTileRect::initAnchor(int coordX, int coordY) {
this->anchorCoordX = coordX;
this->anchorCoordY = coordY;
this->anchored = true;
}
void CursorTileRect::stopAnchor()
{
void CursorTileRect::stopAnchor() {
this->anchored = false;
}
void CursorTileRect::initRightClickSelectionAnchor(int coordX, int coordY)
{
void CursorTileRect::initRightClickSelectionAnchor(int coordX, int coordY) {
this->anchorCoordX = coordX;
this->anchorCoordY = coordY;
this->rightClickSelectionAnchored = true;
}
void CursorTileRect::stopRightClickSelectionAnchor()
{
void CursorTileRect::stopRightClickSelectionAnchor() {
this->rightClickSelectionAnchored = false;
}
void CursorTileRect::updateSelectionSize(int width, int height)
{
void CursorTileRect::updateSelectionSize(int width, int height) {
this->selectionWidth = width;
this->selectionHeight = height;
this->width = width * 16;
@ -58,43 +51,38 @@ void CursorTileRect::updateSelectionSize(int width, int height)
this->update();
}
void CursorTileRect::setSmartPathMode(bool enable)
{
void CursorTileRect::setSmartPathMode(bool enable) {
this->smartPathMode = enable;
}
void CursorTileRect::setStraightPathMode(bool enable)
{
void CursorTileRect::setStraightPathMode(bool enable) {
this->straightPathMode = enable;
}
void CursorTileRect::setSingleTileMode()
{
void CursorTileRect::setSingleTileMode() {
this->singleTileMode = true;
}
void CursorTileRect::stopSingleTileMode()
{
void CursorTileRect::stopSingleTileMode() {
this->singleTileMode = false;
}
bool CursorTileRect::smartPathInEffect()
{
bool CursorTileRect::smartPathInEffect() {
return !this->rightClickSelectionAnchored && this->smartPathMode && this->selectionHeight == 3 && this->selectionWidth == 3;
}
void CursorTileRect::updateLocation(int coordX, int coordY)
{
void CursorTileRect::updateLocation(int coordX, int coordY) {
if (!this->singleTileMode) {
if (this->rightClickSelectionAnchored) {
coordX = qMin(coordX, this->anchorCoordX);
coordY = qMin(coordY, this->anchorCoordY);
}
else if (this->anchored && !this->smartPathInEffect()) {
} else if (this->anchored && !this->smartPathInEffect()) {
int xDiff = coordX - this->anchorCoordX;
int yDiff = coordY - this->anchorCoordY;
if (xDiff < 0 && xDiff % this->selectionWidth != 0) xDiff -= this->selectionWidth;
if (yDiff < 0 && yDiff % this->selectionHeight != 0) yDiff -= this->selectionHeight;
if (xDiff < 0 && xDiff % this->selectionWidth != 0)
xDiff -= this->selectionWidth;
if (yDiff < 0 && yDiff % this->selectionHeight != 0)
yDiff -= this->selectionHeight;
coordX = this->anchorCoordX + (xDiff / this->selectionWidth) * this->selectionWidth;
coordY = this->anchorCoordY + (yDiff / this->selectionHeight) * this->selectionHeight;

View file

@ -6,9 +6,7 @@
#include <QLabel>
#include <QScrollBar>
CustomAttributesTable::CustomAttributesTable(Event *event, QWidget *parent) :
QFrame(parent)
{
CustomAttributesTable::CustomAttributesTable(Event* event, QWidget* parent) : QFrame(parent) {
this->event = event;
QVBoxLayout* layout = new QVBoxLayout(this);
@ -71,15 +69,12 @@ CustomAttributesTable::CustomAttributesTable(Event *event, QWidget *parent) :
}
});
connect(this->table, &QTableWidget::cellChanged, [=]() {
this->event->customValues = this->getTableFields();
});
connect(this->table, &QTableWidget::cellChanged, [=]() { this->event->customValues = this->getTableFields(); });
this->resizeVertically();
}
CustomAttributesTable::~CustomAttributesTable()
{
CustomAttributesTable::~CustomAttributesTable() {
}
QMap<QString, QString> CustomAttributesTable::getTableFields() {
@ -89,8 +84,10 @@ QMap<QString, QString> CustomAttributesTable::getTableFields() {
QString valueStr = "";
QTableWidgetItem* key = table->item(row, 0);
QTableWidgetItem* value = table->item(row, 1);
if (key) keyStr = key->text();
if (value) valueStr = value->text();
if (key)
keyStr = key->text();
if (value)
valueStr = value->text();
fields[keyStr] = valueStr;
}
return fields;

View file

@ -6,7 +6,6 @@
static unsigned currentActionId = 0;
void DraggablePixmapItem::updatePosition() {
int x = event->getPixelX();
int y = event->getPixelY();
@ -36,12 +35,9 @@ void DraggablePixmapItem::updatePixmap() {
}
void DraggablePixmapItem::bind(QComboBox* combo, QString key) {
connect(combo, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentTextChanged),
this, [this, key](QString value){
this->event->put(key, value);
});
connect(this, &DraggablePixmapItem::onPropertyChanged,
this, [combo, key](QString key2, QString value){
connect(combo, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::currentTextChanged), this,
[this, key](QString value) { this->event->put(key, value); });
connect(this, &DraggablePixmapItem::onPropertyChanged, this, [combo, key](QString key2, QString value) {
if (key2 == key) {
combo->addItem(value);
combo->setCurrentText(value);
@ -50,10 +46,8 @@ void DraggablePixmapItem::bind(QComboBox *combo, QString key) {
}
void DraggablePixmapItem::bindToUserData(QComboBox* combo, QString key) {
connect(combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, [this, combo, key](int index) {
this->event->put(key, combo->itemData(index).toString());
});
connect(combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this,
[this, combo, key](int index) { this->event->put(key, combo->itemData(index).toString()); });
}
void DraggablePixmapItem::mousePressEvent(QGraphicsSceneMouseEvent* mouse) {
@ -103,8 +97,7 @@ void DraggablePixmapItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *) {
if (destMap != NONE_MAP_NAME) {
emit editor->warpEventDoubleClicked(this->event->get("destination_map_name"), this->event->get("destination_warp"));
}
}
else if (this->event->get("event_type") == EventType::SecretBase) {
} 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("_")));
if (destMap != NONE_MAP_NAME) {

View file

@ -3,17 +3,13 @@
#include "ui_eventpropertiesframe.h"
EventPropertiesFrame::EventPropertiesFrame(Event *event, QWidget *parent) :
QFrame(parent),
ui(new Ui::EventPropertiesFrame)
{
EventPropertiesFrame::EventPropertiesFrame(Event* event, QWidget* parent) : QFrame(parent), ui(new Ui::EventPropertiesFrame) {
ui->setupUi(this);
this->event = event;
this->firstShow = true;
}
EventPropertiesFrame::~EventPropertiesFrame()
{
EventPropertiesFrame::~EventPropertiesFrame() {
delete ui;
}

View file

@ -1,26 +1,18 @@
#include "filterchildrenproxymodel.h"
FilterChildrenProxyModel::FilterChildrenProxyModel(QObject *parent) :
QSortFilterProxyModel(parent)
{
FilterChildrenProxyModel::FilterChildrenProxyModel(QObject* parent) : QSortFilterProxyModel(parent) {
}
bool FilterChildrenProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
bool FilterChildrenProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const {
// custom behaviour :
if(filterRegExp().isEmpty() == false)
{
if (filterRegExp().isEmpty() == false) {
// get source-model index for current row
QModelIndex source_index = sourceModel()->index(source_row, this->filterKeyColumn(), source_parent);
if(source_index.isValid())
{
if (source_index.isValid()) {
// if any of children matches the filter, then current index matches the filter as well
int i, nb = sourceModel()->rowCount(source_index);
for (i = 0; i < nb; ++i)
{
if (filterAcceptsRow(i, source_index))
{
for (i = 0; i < nb; ++i) {
if (filterAcceptsRow(i, source_index)) {
return true;
}
}

View file

@ -2,24 +2,15 @@
#include <QWidget>
FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) :
QLayout(parent),
horzSpace(hSpacing),
vertSpace(vSpacing)
{
FlowLayout::FlowLayout(QWidget* parent, int margin, int hSpacing, int vSpacing) : QLayout(parent), horzSpace(hSpacing), vertSpace(vSpacing) {
setContentsMargins(margin, margin, margin, margin);
}
FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) :
horzSpace(hSpacing),
vertSpace(vSpacing)
{
FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) : horzSpace(hSpacing), vertSpace(vSpacing) {
setContentsMargins(margin, margin, margin, margin);
}
FlowLayout::~FlowLayout()
{
FlowLayout::~FlowLayout() {
QLayoutItem* item;
while ((item = takeAt(0)))
delete item;

View file

@ -15,13 +15,7 @@ QImage getCollisionMetatileImage(int collision, int elevation) {
}
QImage getMetatileImage(
uint16_t tile,
Tileset *primaryTileset,
Tileset *secondaryTileset,
QList<int> layerOrder,
QList<float> layerOpacity,
bool useTruePalettes)
{
uint16_t tile, Tileset* primaryTileset, Tileset* secondaryTileset, QList<int> layerOrder, QList<float> layerOpacity, bool useTruePalettes) {
QImage metatile_image(16, 16, QImage::Format_RGBA8888);
metatile_image.fill(Qt::black);

View file

@ -12,8 +12,7 @@
#define STITCH_MODE_BORDER_DISTANCE 2
QString getTitle(ImageExporterMode mode) {
switch (mode)
{
switch (mode) {
case ImageExporterMode::Normal:
return "Export Map Image";
case ImageExporterMode::Stitch:
@ -24,10 +23,7 @@ QString getTitle(ImageExporterMode mode) {
return "";
}
MapImageExporter::MapImageExporter(QWidget *parent_, Editor *editor_, ImageExporterMode mode) :
QDialog(parent_),
ui(new Ui::MapImageExporter)
{
MapImageExporter::MapImageExporter(QWidget* parent_, Editor* editor_, ImageExporterMode mode) : QDialog(parent_), ui(new Ui::MapImageExporter) {
ui->setupUi(this);
this->map = editor_->map;
this->editor = editor_;
@ -51,8 +47,7 @@ MapImageExporter::~MapImageExporter() {
void MapImageExporter::saveImage() {
QString title = getTitle(this->mode);
QString defaultFilename;
switch (this->mode)
{
switch (this->mode) {
case ImageExporterMode::Normal:
defaultFilename = map->name;
break;
@ -64,10 +59,8 @@ void MapImageExporter::saveImage() {
break;
}
QString defaultFilepath = QString("%1/%2.%3")
.arg(editor->project->root)
.arg(defaultFilename)
.arg(this->mode == ImageExporterMode::Timelapse ? "gif" : "png");
QString defaultFilepath
= QString("%1/%2.%3").arg(editor->project->root).arg(defaultFilename).arg(this->mode == ImageExporterMode::Timelapse ? "gif" : "png");
QString filter = this->mode == ImageExporterMode::Timelapse ? "Image Files (*.gif)" : "Image Files (*.png *.jpg *.bmp)";
QString filepath = QFileDialog::getSaveFileName(this, title, defaultFilepath, filter);
if (!filepath.isEmpty()) {
@ -137,8 +130,7 @@ void MapImageExporter::saveImage() {
}
return;
}
while (this->map->editHistory.canRedo() &&
!historyItemAppliesToFrame(this->map->editHistory.command(this->map->editHistory.index()))) {
while (this->map->editHistory.canRedo() && !historyItemAppliesToFrame(this->map->editHistory.command(this->map->editHistory.index()))) {
i--;
this->map->editHistory.redo();
}
@ -157,8 +149,7 @@ void MapImageExporter::saveImage() {
if (i > 0) {
i--;
this->map->editHistory.redo();
while (this->map->editHistory.canRedo() &&
!historyItemAppliesToFrame(this->map->editHistory.command(this->map->editHistory.index()))) {
while (this->map->editHistory.canRedo() && !historyItemAppliesToFrame(this->map->editHistory.command(this->map->editHistory.index()))) {
i--;
this->map->editHistory.redo();
}
@ -196,12 +187,9 @@ bool MapImageExporter::historyItemAppliesToFrame(const QUndoCommand *command) {
case CommandId::ID_EventCreate:
case CommandId::ID_EventDelete:
case CommandId::ID_EventDuplicate: {
bool eventTypeIsApplicable =
(this->showObjects && (command->id() & IDMask_EventType_Object) != 0)
|| (this->showWarps && (command->id() & IDMask_EventType_Warp) != 0)
|| (this->showBGs && (command->id() & IDMask_EventType_BG) != 0)
|| (this->showTriggers && (command->id() & IDMask_EventType_Trigger) != 0)
|| (this->showHealSpots && (command->id() & IDMask_EventType_Heal) != 0);
bool eventTypeIsApplicable = (this->showObjects && (command->id() & IDMask_EventType_Object) != 0)
|| (this->showWarps && (command->id() & IDMask_EventType_Warp) != 0) || (this->showBGs && (command->id() & IDMask_EventType_BG) != 0)
|| (this->showTriggers && (command->id() & IDMask_EventType_Trigger) != 0) || (this->showHealSpots && (command->id() & IDMask_EventType_Heal) != 0);
return eventTypeIsApplicable;
}
default:
@ -350,8 +338,7 @@ void MapImageExporter::updatePreview() {
this->scene->setSceneRect(this->scene->itemsBoundingRect());
this->ui->graphicsView_Preview->setScene(scene);
this->ui->graphicsView_Preview->setFixedSize(scene->itemsBoundingRect().width() + 2,
scene->itemsBoundingRect().height() + 2);
this->ui->graphicsView_Preview->setFixedSize(scene->itemsBoundingRect().width() + 2, scene->itemsBoundingRect().height() + 2);
}
QPixmap MapImageExporter::getFormattedMapPixmap(Map* map, bool ignoreBorder) {
@ -372,11 +359,8 @@ QPixmap MapImageExporter::getFormattedMapPixmap(Map *map, bool ignoreBorder) {
editor->project->loadEventPixmaps(events);
for (Event* event : events) {
QString group = event->get("event_group_type");
if ((showObjects && group == "object_event_group")
|| (showWarps && group == "warp_event_group")
|| (showBGs && group == "bg_event_group")
|| (showTriggers && group == "coord_event_group")
|| (showHealSpots && group == "heal_event_group"))
if ((showObjects && group == "object_event_group") || (showWarps && group == "warp_event_group") || (showBGs && group == "bg_event_group")
|| (showTriggers && group == "coord_event_group") || (showHealSpots && group == "heal_event_group"))
eventPainter.drawImage(QPoint(event->getPixelX(), event->getPixelY()), event->pixmap.toImage());
}
eventPainter.end();
@ -410,12 +394,10 @@ QPixmap MapImageExporter::getFormattedMapPixmap(Map *map, bool ignoreBorder) {
QPainter connectionPainter(&pixmap);
for (auto connectionItem : editor->connection_edit_items) {
QString direction = connectionItem->connection->direction;
if ((showUpConnections && direction == "up")
|| (showDownConnections && direction == "down")
|| (showLeftConnections && direction == "left")
if ((showUpConnections && direction == "up") || (showDownConnections && direction == "down") || (showLeftConnections && direction == "left")
|| (showRightConnections && direction == "right"))
connectionPainter.drawImage(connectionItem->initialX + borderWidth, connectionItem->initialY + borderHeight,
connectionItem->basePixmap.toImage());
connectionPainter.drawImage(
connectionItem->initialX + borderWidth, connectionItem->initialY + borderHeight, connectionItem->basePixmap.toImage());
}
connectionPainter.end();
}
@ -424,8 +406,10 @@ QPixmap MapImageExporter::getFormattedMapPixmap(Map *map, bool ignoreBorder) {
// since the last grid lines are outside of the pixmap, add a pixel to the bottom and right
if (showGrid) {
int addX = 1, addY = 1;
if (borderHeight) addY = 0;
if (borderWidth) addX = 0;
if (borderHeight)
addY = 0;
if (borderWidth)
addX = 0;
QPixmap newPixmap = QPixmap(pixmap.width() + addX, pixmap.height() + addY);
QPainter gridPainter(&newPixmap);

View file

@ -4,7 +4,14 @@
#include "editcommands.h"
#define SWAP(a, b) do { if (a != b) { a ^= b; b ^= a; a ^= b; } } while (0)
#define SWAP(a, b) \
do { \
if (a != b) { \
a ^= b; \
b ^= a; \
a ^= b; \
} \
} while (0)
void MapPixmapItem::paint(QGraphicsSceneMouseEvent* event) {
if (map) {
@ -83,9 +90,13 @@ void MapPixmapItem::shift(int xDelta, int yDelta, bool fromScriptCall) {
int destX = i + xDelta;
int destY = j + yDelta;
if (destX < 0)
do { destX += map->getWidth(); } while (destX < 0);
do {
destX += map->getWidth();
} while (destX < 0);
if (destY < 0)
do { destY += map->getHeight(); } while (destY < 0);
do {
destY += map->getHeight();
} while (destY < 0);
destX %= map->getWidth();
destY %= map->getHeight();
@ -110,8 +121,10 @@ void MapPixmapItem::paintNormal(int x, int y, bool fromScriptCall) {
// This allows painting via dragging the mouse to tile the painted region.
int xDiff = x - initialX;
int yDiff = y - initialY;
if (xDiff < 0 && xDiff % selectionDimensions.x() != 0) xDiff -= selectionDimensions.x();
if (yDiff < 0 && yDiff % selectionDimensions.y() != 0) yDiff -= selectionDimensions.y();
if (xDiff < 0 && xDiff % selectionDimensions.x() != 0)
xDiff -= selectionDimensions.x();
if (yDiff < 0 && yDiff % selectionDimensions.y() != 0)
yDiff -= selectionDimensions.y();
x = initialX + (xDiff / selectionDimensions.x()) * selectionDimensions.x();
y = initialY + (yDiff / selectionDimensions.y()) * selectionDimensions.y();
@ -170,7 +183,8 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) {
QList<QPair<uint16_t, uint16_t>>* selectedCollisions = this->metatileSelector->getSelectedCollisions();
// Smart path should never be enabled without a 3x3 block selection.
if (selectionDimensions.x() != 3 || selectionDimensions.y() != 3) return;
if (selectionDimensions.x() != 3 || selectionDimensions.y() != 3)
return;
// Shift to the middle tile of the smart path selection.
uint16_t openTile = selectedMetatiles->at(4);
@ -212,8 +226,7 @@ void MapPixmapItem::paintSmartPath(int x, int y, bool fromScriptCall) {
if (!(i + x < map->getWidth() && i + x >= 0 && j + y < map->getHeight() && j + y >= 0))
continue;
// Ignore the corners, which can't possible be affected by the smart path.
if ((i == -1 && j == -1) || (i == 2 && j == -1) ||
(i == -1 && j == 2) || (i == 2 && j == 2))
if ((i == -1 && j == -1) || (i == 2 && j == -1) || (i == -1 && j == 2) || (i == 2 && j == 2))
continue;
// Ignore tiles that aren't part of the smart path set.
@ -293,10 +306,14 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) {
QPoint pos = Metatile::coordFromPixmapCoord(event->pos());
// Snap point to within map bounds.
if (pos.x() < 0) pos.setX(0);
if (pos.x() >= map->getWidth()) pos.setX(map->getWidth() - 1);
if (pos.y() < 0) pos.setY(0);
if (pos.y() >= map->getHeight()) pos.setY(map->getHeight() - 1);
if (pos.x() < 0)
pos.setX(0);
if (pos.x() >= map->getWidth())
pos.setX(map->getWidth() - 1);
if (pos.y() < 0)
pos.setY(0);
if (pos.y() >= map->getHeight())
pos.setY(map->getHeight() - 1);
// Update/apply copied metatiles.
if (event->type() == QEvent::GraphicsSceneMousePress) {
@ -312,8 +329,10 @@ void MapPixmapItem::updateMetatileSelection(QGraphicsSceneMouseEvent *event) {
int y1 = selection_origin.y();
int x2 = pos.x();
int y2 = pos.y();
if (x1 > x2) SWAP(x1, x2);
if (y1 > y2) SWAP(y1, y2);
if (x1 > x2)
SWAP(x1, x2);
if (y1 > y2)
SWAP(y1, y2);
selection.clear();
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
@ -387,13 +406,8 @@ void MapPixmapItem::magicFill(int x, int y, bool fromScriptCall) {
this->magicFill(x, y, selectionDimensions, selectedMetatiles, selectedCollisions, fromScriptCall);
}
void MapPixmapItem::magicFill(
int initialX,
int initialY,
QPoint selectionDimensions,
QList<uint16_t> *selectedMetatiles,
QList<QPair<uint16_t, uint16_t>> *selectedCollisions,
bool fromScriptCall) {
void MapPixmapItem::magicFill(int initialX, int initialY, QPoint selectionDimensions, QList<uint16_t>* selectedMetatiles,
QList<QPair<uint16_t, uint16_t>>* selectedCollisions, bool fromScriptCall) {
Block block;
if (map->getBlock(initialX, initialY, &block)) {
if (selectedMetatiles->length() == 1 && selectedMetatiles->value(0) == block.tile) {
@ -411,8 +425,10 @@ void MapPixmapItem::magicFill(
int yDiff = y - initialY;
int i = xDiff % selectionDimensions.x();
int j = yDiff % selectionDimensions.y();
if (i < 0) i = selectionDimensions.x() + i;
if (j < 0) j = selectionDimensions.y() + j;
if (i < 0)
i = selectionDimensions.x() + i;
if (j < 0)
j = selectionDimensions.y() + j;
int index = j * selectionDimensions.x() + i;
block.tile = selectedMetatiles->at(index);
if (setCollisions) {
@ -444,13 +460,8 @@ void MapPixmapItem::floodFill(int initialX, int initialY, uint16_t metatileId, b
delete selectedMetatiles;
}
void MapPixmapItem::floodFill(
int initialX,
int initialY,
QPoint selectionDimensions,
QList<uint16_t> *selectedMetatiles,
QList<QPair<uint16_t, uint16_t>> *selectedCollisions,
bool fromScriptCall) {
void MapPixmapItem::floodFill(int initialX, int initialY, QPoint selectionDimensions, QList<uint16_t>* selectedMetatiles,
QList<QPair<uint16_t, uint16_t>>* selectedCollisions, bool fromScriptCall) {
bool setCollisions = selectedCollisions && selectedCollisions->length() == selectedMetatiles->length();
Blockdata oldMetatiles = !fromScriptCall ? map->layout->blockdata : Blockdata();
@ -471,8 +482,10 @@ void MapPixmapItem::floodFill(
int yDiff = y - initialY;
int i = xDiff % selectionDimensions.x();
int j = yDiff % selectionDimensions.y();
if (i < 0) i = selectionDimensions.x() + i;
if (j < 0) j = selectionDimensions.y() + j;
if (i < 0)
i = selectionDimensions.x() + i;
if (j < 0)
j = selectionDimensions.y() + j;
int index = j * selectionDimensions.x() + i;
uint16_t tile = selectedMetatiles->at(index);
uint16_t old_tile = block.tile;
@ -513,7 +526,8 @@ void MapPixmapItem::floodFillSmartPath(int initialX, int initialY, bool fromScri
QList<QPair<uint16_t, uint16_t>>* selectedCollisions = this->metatileSelector->getSelectedCollisions();
// Smart path should never be enabled without a 3x3 block selection.
if (selectionDimensions.x() != 3 || selectionDimensions.y() != 3) return;
if (selectionDimensions.x() != 3 || selectionDimensions.y() != 3)
return;
// Shift to the middle tile of the smart path selection.
uint16_t openTile = selectedMetatiles->at(4);
@ -651,8 +665,10 @@ void MapPixmapItem::select(QGraphicsSceneMouseEvent *event) {
int y1 = selection_origin.y();
int x2 = pos.x();
int y2 = pos.y();
if (x1 > x2) SWAP(x1, x2);
if (y1 > y2) SWAP(y1, y2);
if (x1 > x2)
SWAP(x1, x2);
if (y1 > y2)
SWAP(y1, y2);
selection.clear();
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {

View file

@ -6,9 +6,8 @@
#include <QColor>
#include <QVector>
MapRuler::MapRuler(int thickness, QColor innerColor, QColor borderColor) :
/* The logical representation of rectangles are always one less than
MapRuler::MapRuler(int thickness, QColor innerColor, QColor borderColor)
: /* The logical representation of rectangles are always one less than
* the rendered shape, so we subtract 1 from thickness. */
thickness(thickness - 1),
half_thickness(qreal(thickness - 1) / 2.0),
@ -19,8 +18,7 @@ MapRuler::MapRuler(int thickness, QColor innerColor, QColor borderColor) :
yRuler(QRectF()),
cornerTick(QLineF()),
anchored(false),
locked(false)
{
locked(false) {
connect(this, &QGraphicsObject::enabledChanged, [this]() {
if (!isEnabled() && anchored)
reset();
@ -164,25 +162,27 @@ void MapRuler::updateGeometry() {
void MapRuler::updateStatus(Qt::Corner corner) {
QString statusMessage;
switch (corner)
{
switch (corner) {
case Qt::TopLeftCorner:
statusMessage = QString("Ruler: Left %1, Up %2\nStart(%3, %4), End(%5, %6)").arg(width()).arg(height())
.arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
statusMessage = QString("Ruler: Left %1, Up %2\nStart(%3, %4), End(%5, %6)")
.arg(width())
.arg(height())
.arg(anchor().x())
.arg(anchor().y())
.arg(endPos().x())
.arg(endPos().y());
break;
case Qt::BottomLeftCorner:
statusMessage = QString("Ruler: Left %1").arg(width());
if (deltaY())
statusMessage += QString(", Down %1").arg(height());
statusMessage += QString("\nStart(%1, %2), End(%3, %4)")
.arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
statusMessage += QString("\nStart(%1, %2), End(%3, %4)").arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
break;
case Qt::TopRightCorner:
statusMessage = QString("Ruler: ");
if (deltaX())
statusMessage += QString("Right %1, ").arg(width());
statusMessage += QString("Up %1\nStart(%2, %3), End(%4, %5)").arg(height())
.arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
statusMessage += QString("Up %1\nStart(%2, %3), End(%4, %5)").arg(height()).arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
break;
case Qt::BottomRightCorner:
statusMessage = QString("Ruler: ");
@ -194,11 +194,9 @@ void MapRuler::updateStatus(Qt::Corner corner) {
statusMessage += ", ";
statusMessage += QString("Down: %1").arg(height());
}
statusMessage += QString("\nStart(%1, %2), End(%3, %4)")
.arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
statusMessage += QString("\nStart(%1, %2), End(%3, %4)").arg(anchor().x()).arg(anchor().y()).arg(endPos().x()).arg(endPos().y());
} else {
statusMessage += QString("0\nStart(%1, %2)")
.arg(anchor().x()).arg(anchor().y());
statusMessage += QString("0\nStart(%1, %2)").arg(anchor().x()).arg(anchor().y());
}
break;
}

View file

@ -2,18 +2,13 @@
#include <QEvent>
#include <QGraphicsSceneWheelEvent>
MapSceneEventFilter::MapSceneEventFilter(QObject *parent) : QObject(parent)
{
MapSceneEventFilter::MapSceneEventFilter(QObject* parent) : QObject(parent) {
}
bool MapSceneEventFilter::eventFilter(QObject*, QEvent *event)
{
if (event->type() == QEvent::GraphicsSceneWheel)
{
bool MapSceneEventFilter::eventFilter(QObject*, QEvent* event) {
if (event->type() == QEvent::GraphicsSceneWheel) {
QGraphicsSceneWheelEvent* wheelEvent = static_cast<QGraphicsSceneWheelEvent*>(event);
if (wheelEvent->modifiers() & Qt::ControlModifier)
{
if (wheelEvent->modifiers() & Qt::ControlModifier) {
emit wheelZoom(wheelEvent->delta() > 0 ? 1 : -1);
event->accept();
return true;

View file

@ -5,18 +5,8 @@
void MetatileLayersItem::draw() {
const QList<QPoint> tileCoords = QList<QPoint>{
QPoint(0, 0),
QPoint(16, 0),
QPoint(0, 16),
QPoint(16, 16),
QPoint(32, 0),
QPoint(48, 0),
QPoint(32, 16),
QPoint(48, 16),
QPoint(64, 0),
QPoint(80, 0),
QPoint(64, 16),
QPoint(80, 16),
QPoint(0, 0), QPoint(16, 0), QPoint(0, 16), QPoint(16, 16), QPoint(32, 0), QPoint(48, 0), QPoint(32, 16), QPoint(48, 16), QPoint(64, 0), QPoint(80, 0),
QPoint(64, 16), QPoint(80, 16),
};
bool isTripleLayerMetatile = projectConfig.getTripleLayerMetatilesEnabled();
@ -26,9 +16,8 @@ void MetatileLayersItem::draw() {
int numTiles = isTripleLayerMetatile ? 12 : 8;
for (int i = 0; i < numTiles; i++) {
Tile tile = this->metatile->tiles.at(i);
QImage tileImage = getPalettedTileImage(tile.tile, this->primaryTileset, this->secondaryTileset, tile.palette, true)
.mirrored(tile.xflip, tile.yflip)
.scaled(16, 16);
QImage tileImage
= getPalettedTileImage(tile.tile, this->primaryTileset, this->secondaryTileset, tile.palette, true).mirrored(tile.xflip, tile.yflip).scaled(16, 16);
painter.drawImage(tileCoords.at(i), tileImage);
}
@ -102,8 +91,12 @@ void MetatileLayersItem::getBoundedCoords(QPointF pos, int *x, int *y) {
int maxX = isTripleLayerMetatile ? 5 : 3;
*x = static_cast<int>(pos.x()) / 16;
*y = static_cast<int>(pos.y()) / 16;
if (*x < 0) *x = 0;
if (*y < 0) *y = 0;
if (*x > maxX) *x = maxX;
if (*y > 1) *y = 1;
if (*x < 0)
*x = 0;
if (*y < 0)
*y = 0;
if (*x > maxX)
*x = maxX;
if (*y > 1)
*y = 1;
}

View file

@ -46,7 +46,8 @@ void MetatileSelector::draw() {
}
bool MetatileSelector::select(uint16_t metatileId) {
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset)) return false;
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset))
return false;
this->externalSelection = false;
QPoint coords = this->getMetatileIdCoords(metatileId);
SelectablePixmapItem::select(coords.x(), coords.y(), 0, 0);
@ -55,7 +56,8 @@ bool MetatileSelector::select(uint16_t metatileId) {
}
bool MetatileSelector::selectFromMap(uint16_t metatileId, uint16_t collision, uint16_t elevation) {
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset)) return false;
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset))
return false;
this->select(metatileId);
this->selectedCollisions->append(QPair<uint16_t, uint16_t>(collision, elevation));
return true;
@ -111,13 +113,15 @@ bool MetatileSelector::shouldAcceptEvent(QGraphicsSceneMouseEvent *event) {
}
void MetatileSelector::mousePressEvent(QGraphicsSceneMouseEvent* event) {
if (!shouldAcceptEvent(event)) return;
if (!shouldAcceptEvent(event))
return;
SelectablePixmapItem::mousePressEvent(event);
this->updateSelectedMetatiles();
}
void MetatileSelector::mouseMoveEvent(QGraphicsSceneMouseEvent* event) {
if (!shouldAcceptEvent(event)) return;
if (!shouldAcceptEvent(event))
return;
SelectablePixmapItem::mouseMoveEvent(event);
this->updateSelectedMetatiles();
@ -127,7 +131,8 @@ void MetatileSelector::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
}
void MetatileSelector::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) {
if (!shouldAcceptEvent(event)) return;
if (!shouldAcceptEvent(event))
return;
SelectablePixmapItem::mouseReleaseEvent(event);
this->updateSelectedMetatiles();
}
@ -188,14 +193,12 @@ uint16_t MetatileSelector::getMetatileId(int x, int y) {
}
QPoint MetatileSelector::getMetatileIdCoords(uint16_t metatileId) {
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset))
{
if (!Tileset::metatileIsValid(metatileId, this->primaryTileset, this->secondaryTileset)) {
// Invalid metatile id.
return QPoint(0, 0);
}
int index = metatileId < Project::getNumMetatilesPrimary()
? metatileId
int index = metatileId < Project::getNumMetatilesPrimary() ? metatileId
: metatileId - Project::getNumMetatilesPrimary() + this->primaryTileset->metatiles.length();
return QPoint(index % this->numMetatilesWide, index / this->numMetatilesWide);
}

View file

@ -10,8 +10,7 @@ MonTabWidget::MonTabWidget(Editor *editor, QWidget *parent) : QTabWidget(parent)
bool MonTabWidget::eventFilter(QObject*, QEvent* event) {
// Press right mouse button to activate tab.
if (event->type() == QEvent::MouseButtonPress
&& static_cast<QMouseEvent *>(event)->button() == Qt::RightButton) {
if (event->type() == QEvent::MouseButtonPress && static_cast<QMouseEvent*>(event)->button() == Qt::RightButton) {
QPoint eventPos = static_cast<QMouseEvent*>(event)->pos();
int tabIndex = tabBar()->tabAt(eventPos);
if (tabIndex > -1) {
@ -37,7 +36,8 @@ void MonTabWidget::populate() {
}
void MonTabWidget::askActivateTab(int tabIndex, QPoint menuPos) {
if (activeTabs[tabIndex]) return;
if (activeTabs[tabIndex])
return;
QMenu contextMenu(this);
@ -67,20 +67,27 @@ void MonTabWidget::populateTab(int tabIndex, WildMonInfo monInfo, QString fieldN
int fieldIndex = 0;
for (EncounterField field : editor->project->wildMonFields) {
if (field.name == fieldName) break;
if (field.name == fieldName)
break;
fieldIndex++;
}
bool insertGroupLabel = false;
if (!editor->project->wildMonFields[fieldIndex].groups.isEmpty()) insertGroupLabel = true;
if (!editor->project->wildMonFields[fieldIndex].groups.isEmpty())
insertGroupLabel = true;
speciesTable->setRowCount(monInfo.wildPokemon.size());
speciesTable->setColumnCount(insertGroupLabel ? 8 : 7);
QStringList landMonTableHeaders;
landMonTableHeaders << "Slot";
if (insertGroupLabel) landMonTableHeaders << "Group";
landMonTableHeaders << "Species" << "Min Level" << "Max Level"
<< "Encounter Chance" << "Slot Ratio" << "Encounter Rate";
if (insertGroupLabel)
landMonTableHeaders << "Group";
landMonTableHeaders << "Species"
<< "Min Level"
<< "Max Level"
<< "Encounter Chance"
<< "Slot Ratio"
<< "Encounter Rate";
speciesTable->setHorizontalHeaderLabels(landMonTableHeaders);
speciesTable->horizontalHeader()->show();
speciesTable->verticalHeader()->hide();
@ -128,7 +135,8 @@ void MonTabWidget::createSpeciesTableRow(QTableWidget *table, WildPokemon mon, i
QPixmap monIcon = QPixmap(editor->project->speciesToIconPath.value(newSpecies)).copy(0, 0, 32, 32);
monLabel->setPixmap(monIcon);
emit editor->wildMonDataChanged();
if (!monIcon.isNull()) editor->saveEncounterTabData();
if (!monIcon.isNull())
editor->saveEncounterTabData();
});
QSpinBox* minLevel = new QSpinBox;
@ -154,7 +162,8 @@ void MonTabWidget::createSpeciesTableRow(QTableWidget *table, WildPokemon mon, i
int fieldIndex = 0;
for (EncounterField field : editor->project->wildMonFields) {
if (field.name == fieldName) break;
if (field.name == fieldName)
break;
fieldIndex++;
}
@ -174,12 +183,9 @@ void MonTabWidget::createSpeciesTableRow(QTableWidget *table, WildPokemon mon, i
}
}
QLabel *percentLabel = new QLabel(QString("%1%").arg(
QString::number(editor->project->wildMonFields[fieldIndex].encounterRates[index] / slotChanceTotal * 100.0, 'f', 2)
));
QLabel *ratioLabel = new QLabel(QString("%1").arg(
QString::number(editor->project->wildMonFields[fieldIndex].encounterRates[index]
)));
QLabel* percentLabel
= new QLabel(QString("%1%").arg(QString::number(editor->project->wildMonFields[fieldIndex].encounterRates[index] / slotChanceTotal * 100.0, 'f', 2)));
QLabel* ratioLabel = new QLabel(QString("%1").arg(QString::number(editor->project->wildMonFields[fieldIndex].encounterRates[index])));
QFrame* speciesSelector = new QFrame;
QHBoxLayout* speciesSelectorLayout = new QHBoxLayout;
@ -198,7 +204,8 @@ void MonTabWidget::createSpeciesTableRow(QTableWidget *table, WildPokemon mon, i
maxLevelFrame->setLayout(maxLevelSpinboxLayout);
bool insertGroupLabel = false;
if (!editor->project->wildMonFields[fieldIndex].groups.isEmpty()) insertGroupLabel = true;
if (!editor->project->wildMonFields[fieldIndex].groups.isEmpty())
insertGroupLabel = true;
table->setCellWidget(index, 0, monNum);
if (insertGroupLabel) {
QString groupName = QString();

Some files were not shown because too many files have changed in this diff Show more