#include "project.h" #include "config.h" #include "history.h" #include "log.h" #include "parseutil.h" #include "paletteutil.h" #include "tile.h" #include "tileset.h" #include "map.h" #include "filedialog.h" #include "validator.h" #include "orderedjson.h" #include "utility.h" #include #include #include #include #include #include #include #include #include #include #include int Project::num_tiles_primary = 512; int Project::num_tiles_total = 1024; int Project::num_metatiles_primary = 512; int Project::num_pals_primary = 6; int Project::num_pals_total = 13; int Project::max_map_data_size = 10240; // 0x2800 int Project::default_map_dimension = 20; Project::Project(QObject *parent) : QObject(parent), re_gbapalExtension(projectConfig.getIdentifier(ProjectIdentifier::regex_gbapal)), re_bppExtension(projectConfig.getIdentifier(ProjectIdentifier::regex_bpp)) { QObject::connect(&this->fileWatcher, &QFileSystemWatcher::fileChanged, this, &Project::recordFileChange); } Project::~Project() { clearMaps(); clearTilesetCache(); clearMapLayouts(); clearEventGraphics(); clearHealLocations(); QPixmapCache::clear(); } void Project::set_root(QString dir) { this->root = dir; FileDialog::setDirectory(dir); this->parser.set_root(dir); } // Before attempting the initial project load we should check for a few notable files. // If all are missing then we can warn the user, they may have accidentally selected the wrong folder. bool Project::sanityCheck() { // The goal with the file selection is to pick files that are important enough that any reasonable project would have // at least 1 in the expected location, but unique enough that they're unlikely to overlap with a completely unrelated // directory (e.g. checking for 'data/maps/' is a bad choice because it's too generic, pokeyellow would pass for instance) static const QSet pathsToCheck = { ProjectFilePath::json_map_groups, ProjectFilePath::json_layouts, ProjectFilePath::tilesets_headers, ProjectFilePath::global_fieldmap, }; for (auto pathId : pathsToCheck) { const QString path = QString("%1/%2").arg(this->root).arg(projectConfig.getFilePath(pathId)); QFileInfo fileInfo(path); if (fileInfo.exists() && fileInfo.isFile()) return true; } return false; } bool Project::load() { resetFileCache(); this->disabledSettingsNames.clear(); bool success = readMapLayouts() && readRegionMapSections() && readItemNames() && readFlagNames() && readVarNames() && readMovementTypes() && readInitialFacingDirections() && readMapTypes() && readMapBattleScenes() && readWeatherNames() && readCoordEventWeatherNames() && readSecretBaseIds() && readBgEventFacingDirections() && readTrainerTypes() && readMetatileBehaviors() && readFieldmapProperties() && readFieldmapMasks() && readTilesetLabels() && readTilesetMetatileLabels() && readMiscellaneousConstants() && readSpeciesIconPaths() && readWildMonData() && readEventScriptLabels() && readObjEventGfxConstants() && readEventGraphics() && readSongNames() && readMapGroups() && readHealLocations(); if (success) { // No need to do this if something failed to load. // (and in fact we shouldn't, because they contain // assumptions that some things have loaded correctly). initNewLayoutSettings(); initNewMapSettings(); applyParsedLimits(); } return success; } void Project::resetFileCache() { this->parser.clearFileCache(); const QSet filepaths = { // Whenever we load a tileset we'll need to parse some data from these files, so we cache them to avoid the overhead of opening the files. // We don't know yet whether the project uses C or asm tileset data, so try to cache both (we'll ignore errors from missing files). projectConfig.getFilePath(ProjectFilePath::tilesets_headers_asm), projectConfig.getFilePath(ProjectFilePath::tilesets_graphics_asm), projectConfig.getFilePath(ProjectFilePath::tilesets_metatiles_asm), projectConfig.getFilePath(ProjectFilePath::tilesets_headers), projectConfig.getFilePath(ProjectFilePath::tilesets_graphics), projectConfig.getFilePath(ProjectFilePath::tilesets_metatiles), // We need separate sets of constants from these files projectConfig.getFilePath(ProjectFilePath::constants_map_types), projectConfig.getFilePath(ProjectFilePath::global_fieldmap), }; for (const auto &path : filepaths) { this->parser.cacheFile(path); } } QString Project::getProjectTitle() const { if (!root.isNull()) { return root.section('/', -1); } else { return QString(); } } void Project::clearMaps() { qDeleteAll(this->maps); this->maps.clear(); this->loadedMapNames.clear(); } void Project::clearTilesetCache() { qDeleteAll(this->tilesetCache); this->tilesetCache.clear(); } Map* Project::loadMap(const QString &mapName) { Map* map = this->maps.value(mapName); if (!map) return nullptr; if (isMapLoaded(map)) return map; if (!(loadMapData(map) && loadMapLayout(map))) return nullptr; this->loadedMapNames.insert(mapName); emit mapLoaded(map); return map; } void Project::initTopLevelMapFields() { static const QSet defaultTopLevelMapFields = { "id", "name", "layout", "music", "region_map_section", "requires_flash", "weather", "map_type", "show_map_name", "battle_scene", "connections", "object_events", "warp_events", "coord_events", "bg_events", "shared_events_map", "shared_scripts_map", }; this->topLevelMapFields = defaultTopLevelMapFields; if (projectConfig.mapAllowFlagsEnabled) { this->topLevelMapFields.insert("allow_cycling"); this->topLevelMapFields.insert("allow_escaping"); this->topLevelMapFields.insert("allow_running"); } if (projectConfig.floorNumberEnabled) { this->topLevelMapFields.insert("floor_number"); } } bool Project::readMapJson(const QString &mapName, QJsonDocument * out) { const QString mapFilepath = QString("%1%2/map.json").arg(projectConfig.getFilePath(ProjectFilePath::data_map_folders)).arg(mapName); QString error; if (!parser.tryParseJsonFile(out, mapFilepath, &error)) { logError(QString("Failed to read map data from '%1': %2").arg(mapFilepath).arg(error)); return false; } return true; } bool Project::loadMapEvent(Map *map, const QJsonObject &json, Event::Type defaultType) { QString typeString = ParseUtil::jsonToQString(json["type"]); Event::Type type = typeString.isEmpty() ? defaultType : Event::typeFromJsonKey(typeString); Event* event = Event::create(type); if (!event) { return false; } if (!event->loadFromJson(json, this)) { delete event; return false; } map->addEvent(event); return true; } bool Project::loadMapData(Map* map) { if (!map->isPersistedToFile()) { return true; } QJsonDocument mapDoc; if (!readMapJson(map->name(), &mapDoc)) return false; QJsonObject mapObj = mapDoc.object(); // We should already know the map constant ID from the initial project launch, but we'll ensure it's correct here anyway. map->setConstantName(ParseUtil::jsonToQString(mapObj["id"])); this->mapConstantsToMapNames.insert(map->constantName(), map->name()); const QString layoutId = ParseUtil::jsonToQString(mapObj["layout"]); Layout* layout = this->mapLayouts.value(layoutId); if (!layout) { // We've already verified layout IDs on project launch and ignored maps with invalid IDs, so this shouldn't happen. logError(QString("Cannot load map with unknown layout ID '%1'").arg(layoutId)); return false; } map->setLayout(layout); map->header()->setSong(ParseUtil::jsonToQString(mapObj["music"])); map->header()->setLocation(ParseUtil::jsonToQString(mapObj["region_map_section"])); map->header()->setRequiresFlash(ParseUtil::jsonToBool(mapObj["requires_flash"])); map->header()->setWeather(ParseUtil::jsonToQString(mapObj["weather"])); map->header()->setType(ParseUtil::jsonToQString(mapObj["map_type"])); map->header()->setShowsLocationName(ParseUtil::jsonToBool(mapObj["show_map_name"])); map->header()->setBattleScene(ParseUtil::jsonToQString(mapObj["battle_scene"])); if (projectConfig.mapAllowFlagsEnabled) { map->header()->setAllowsBiking(ParseUtil::jsonToBool(mapObj["allow_cycling"])); map->header()->setAllowsEscaping(ParseUtil::jsonToBool(mapObj["allow_escaping"])); map->header()->setAllowsRunning(ParseUtil::jsonToBool(mapObj["allow_running"])); } if (projectConfig.floorNumberEnabled) { map->header()->setFloorNumber(ParseUtil::jsonToInt(mapObj["floor_number"])); } map->setSharedEventsMap(ParseUtil::jsonToQString(mapObj["shared_events_map"])); map->setSharedScriptsMap(ParseUtil::jsonToQString(mapObj["shared_scripts_map"])); // Events map->resetEvents(); static const QMap defaultEventTypes = { // Map of the expected keys for each event group, and the default type of that group. // If the default type is Type::None then each event must specify its type, or its an error. {"object_events", Event::Type::Object}, {"warp_events", Event::Type::Warp}, {"coord_events", Event::Type::None}, {"bg_events", Event::Type::None}, }; for (auto i = defaultEventTypes.constBegin(); i != defaultEventTypes.constEnd(); i++) { QString eventGroupKey = i.key(); Event::Type defaultType = i.value(); const QJsonArray eventsJsonArr = mapObj[eventGroupKey].toArray(); for (int i = 0; i < eventsJsonArr.size(); i++) { if (!loadMapEvent(map, eventsJsonArr.at(i).toObject(), defaultType)) { logError(QString("Failed to load event for %1, in %2 at index %3.").arg(map->name()).arg(eventGroupKey).arg(i)); } } } // Heal locations are global. Populate the Map's heal location events using our global array. const QList hlEvents = this->healLocations.value(map->constantName()); for (const auto &event : hlEvents) { map->addEvent(event->duplicate()); } map->deleteConnections(); QJsonArray connectionsArr = mapObj["connections"].toArray(); if (!connectionsArr.isEmpty()) { for (int i = 0; i < connectionsArr.size(); i++) { QJsonObject connectionObj = connectionsArr[i].toObject(); const QString direction = ParseUtil::jsonToQString(connectionObj.take("direction")); const int offset = ParseUtil::jsonToInt(connectionObj.take("offset")); const QString mapConstant = ParseUtil::jsonToQString(connectionObj.take("map")); auto connection = new MapConnection(this->mapConstantsToMapNames.value(mapConstant, mapConstant), direction, offset); connection->setCustomData(connectionObj); map->loadConnection(connection); } } QMap customAttributes; for (auto i = mapObj.constBegin(); i != mapObj.constEnd(); i++) { if (!this->topLevelMapFields.contains(i.key())) { customAttributes.insert(i.key(), i.value()); } } map->setCustomAttributes(customAttributes); return true; } Map *Project::createNewMap(const Project::NewMapSettings &settings, const Map* toDuplicate) { Map *map = toDuplicate ? new Map(*toDuplicate) : new Map; map->setName(settings.name); map->setHeader(settings.header); map->setNeedsHealLocation(settings.canFlyTo); // Generate a unique MAP constant. map->setConstantName(toUniqueIdentifier(map->expectedConstantName())); // Make sure we keep the order of the map names the same as in the map group order. int mapNamePos; if (this->groupNames.contains(settings.group)) { mapNamePos = 0; for (const auto &name : this->groupNames) { mapNamePos += this->groupNameToMapNames[name].length(); if (name == settings.group) break; } } else if (isValidNewIdentifier(settings.group)) { // Adding map to a map group that doesn't exist yet. // Create the group, and we already know the map will be last in the list. addNewMapGroup(settings.group); mapNamePos = this->mapNames.length(); } else { logError(QString("Cannot create new map with invalid map group name '%1'.").arg(settings.group)); delete map; return nullptr; } Layout *layout = this->mapLayouts.value(settings.layout.id); if (!layout) { // Layout doesn't already exist, create it. layout = createNewLayout(settings.layout, toDuplicate ? toDuplicate->layout() : nullptr); if (!layout) { // Layout creation failed. delete map; return nullptr; } } else { // This layout already exists. Make sure it's loaded. loadLayout(layout); } map->setLayout(layout); // Try to record the MAPSEC name in case this is a new name. addNewMapsec(map->header()->location()); this->mapNames.insert(mapNamePos, map->name()); this->groupNameToMapNames[settings.group].append(map->name()); this->mapConstantsToMapNames.insert(map->constantName(), map->name()); map->setIsPersistedToFile(false); this->maps.insert(map->name(), map); emit mapCreated(map, settings.group); return map; } Layout *Project::createNewLayout(const Layout::Settings &settings, const Layout *toDuplicate) { if (this->layoutIds.contains(settings.id)) return nullptr; Layout *layout = toDuplicate ? new Layout(*toDuplicate) : new Layout(); layout->id = settings.id; layout->name = settings.name; layout->width = settings.width; layout->height = settings.height; layout->border_width = settings.borderWidth; layout->border_height = settings.borderHeight; layout->tileset_primary_label = settings.primaryTilesetLabel; layout->tileset_secondary_label = settings.secondaryTilesetLabel; // If a special folder name was specified (as in the case when we're creating a layout for a new map) then use that name. // Otherwise the new layout's folder name will just be the layout's name. const QString folderName = !settings.folderName.isEmpty() ? settings.folderName : layout->name; const QString folderPath = projectConfig.getFilePath(ProjectFilePath::data_layouts_folders) + folderName; layout->newFolderPath = folderPath; layout->border_path = folderPath + "/border.bin"; layout->blockdata_path = folderPath + "/map.bin"; if (layout->blockdata.isEmpty()) { // Fill layout using default fill settings setNewLayoutBlockdata(layout); } if (layout->border.isEmpty()) { // Fill border using default fill settings setNewLayoutBorder(layout); } // No need for a full load, we already have all the blockdata. if (!loadLayoutTilesets(layout)) { delete layout; return nullptr; } this->mapLayouts.insert(layout->id, layout); this->layoutIds.append(layout->id); this->loadedLayoutIds.insert(layout->id); emit layoutCreated(layout); return layout; } bool Project::loadLayout(Layout *layout) { if (!isLayoutLoaded(layout)) { // Force these to run even if one fails bool loadedTilesets = loadLayoutTilesets(layout); bool loadedBlockdata = loadBlockdata(layout); bool loadedBorder = loadLayoutBorder(layout); if (loadedTilesets && loadedBlockdata && loadedBorder) { this->loadedLayoutIds.insert(layout->id); return true; } else { return false; } } return true; } Layout *Project::loadLayout(QString layoutId) { Layout *layout = this->mapLayouts.value(layoutId); if (!layout || !loadLayout(layout)) { logError(QString("Failed to load layout '%1'").arg(layoutId)); return nullptr; } return layout; } bool Project::loadMapLayout(Map* map) { if (!map->isPersistedToFile() || map->hasUnsavedChanges()) { return true; } else { return loadLayout(map->layout()); } } void Project::clearMapLayouts() { qDeleteAll(this->mapLayouts); this->mapLayouts.clear(); qDeleteAll(this->mapLayoutsMaster); this->mapLayoutsMaster.clear(); this->layoutIds.clear(); this->layoutIdsMaster.clear(); this->loadedLayoutIds.clear(); this->customLayoutsData = QJsonObject(); } bool Project::readMapLayouts() { clearMapLayouts(); const QString layoutsFilepath = projectConfig.getFilePath(ProjectFilePath::json_layouts); fileWatcher.addPath(QString("%1/%2").arg(this->root).arg(layoutsFilepath)); QJsonDocument layoutsDoc; QString error; if (!parser.tryParseJsonFile(&layoutsDoc, layoutsFilepath, &error)) { logError(QString("Failed to read map layouts from '%1': %2").arg(layoutsFilepath).arg(error)); return false; } QJsonObject layoutsObj = layoutsDoc.object(); this->layoutsLabel = ParseUtil::jsonToQString(layoutsObj.take("layouts_table_label")); if (this->layoutsLabel.isEmpty()) { this->layoutsLabel = "gMapLayouts"; logWarn(QString("'layouts_table_label' value is missing from %1. Defaulting to %2") .arg(layoutsFilepath) .arg(layoutsLabel)); } QJsonArray layouts = layoutsObj.take("layouts").toArray(); for (int i = 0; i < layouts.size(); i++) { QJsonObject layoutObj = layouts[i].toObject(); if (layoutObj.isEmpty()) continue; Layout *layout = new Layout(); layout->id = ParseUtil::jsonToQString(layoutObj.take("id")); if (layout->id.isEmpty()) { logError(QString("Missing 'id' value on layout %1 in %2").arg(i).arg(layoutsFilepath)); delete layout; return false; } if (mapLayouts.contains(layout->id)) { logWarn(QString("Duplicate layout entry for %1 in %2 will be ignored.").arg(layout->id).arg(layoutsFilepath)); delete layout; continue; } layout->name = ParseUtil::jsonToQString(layoutObj.take("name")); if (layout->name.isEmpty()) { logError(QString("Missing 'name' value for %1 in %2").arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } int lwidth = ParseUtil::jsonToInt(layoutObj.take("width")); if (lwidth <= 0) { logError(QString("Invalid 'width' value '%1' for %2 in %3. Must be greater than 0.").arg(lwidth).arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->width = lwidth; int lheight = ParseUtil::jsonToInt(layoutObj.take("height")); if (lheight <= 0) { logError(QString("Invalid 'height' value '%1' for %2 in %3. Must be greater than 0.").arg(lheight).arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->height = lheight; if (projectConfig.useCustomBorderSize) { int bwidth = ParseUtil::jsonToInt(layoutObj.take("border_width")); if (bwidth <= 0) { // 0 is an expected border width/height that should be handled, GF used it for the RS layouts in FRLG bwidth = DEFAULT_BORDER_WIDTH; } layout->border_width = bwidth; int bheight = ParseUtil::jsonToInt(layoutObj.take("border_height")); if (bheight <= 0) { bheight = DEFAULT_BORDER_HEIGHT; } layout->border_height = bheight; } else { layout->border_width = DEFAULT_BORDER_WIDTH; layout->border_height = DEFAULT_BORDER_HEIGHT; } layout->tileset_primary_label = ParseUtil::jsonToQString(layoutObj.take("primary_tileset")); if (layout->tileset_primary_label.isEmpty()) { logError(QString("Missing 'primary_tileset' value for %1 in %2").arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->tileset_secondary_label = ParseUtil::jsonToQString(layoutObj.take("secondary_tileset")); if (layout->tileset_secondary_label.isEmpty()) { logError(QString("Missing 'secondary_tileset' value for %1 in %2").arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->border_path = ParseUtil::jsonToQString(layoutObj.take("border_filepath")); if (layout->border_path.isEmpty()) { logError(QString("Missing 'border_filepath' value for %1 in %2").arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->blockdata_path = ParseUtil::jsonToQString(layoutObj.take("blockdata_filepath")); if (layout->blockdata_path.isEmpty()) { logError(QString("Missing 'blockdata_filepath' value for %1 in %2").arg(layout->id).arg(layoutsFilepath)); delete layout; return false; } layout->customData = layoutObj; this->mapLayouts.insert(layout->id, layout); this->mapLayoutsMaster.insert(layout->id, layout->copy()); this->layoutIds.append(layout->id); this->layoutIdsMaster.append(layout->id); } if (this->mapLayouts.isEmpty()) { logError(QString("Failed to read any map layouts from '%1'. At least one map layout is required.").arg(layoutsFilepath)); return false; } this->customLayoutsData = layoutsObj; return true; } void Project::saveMapLayouts() { QString layoutsFilepath = root + "/" + projectConfig.getFilePath(ProjectFilePath::json_layouts); QFile layoutsFile(layoutsFilepath); if (!layoutsFile.open(QIODevice::WriteOnly)) { logError(QString("Error: Could not open %1 for writing").arg(layoutsFilepath)); return; } OrderedJson::object layoutsObj; layoutsObj["layouts_table_label"] = this->layoutsLabel; OrderedJson::array layoutsArr; for (const QString &layoutId : this->layoutIdsMaster) { Layout *layout = this->mapLayoutsMaster.value(layoutId); OrderedJson::object layoutObj; layoutObj["id"] = layout->id; layoutObj["name"] = layout->name; layoutObj["width"] = layout->width; layoutObj["height"] = layout->height; if (projectConfig.useCustomBorderSize) { layoutObj["border_width"] = layout->border_width; layoutObj["border_height"] = layout->border_height; } layoutObj["primary_tileset"] = layout->tileset_primary_label; layoutObj["secondary_tileset"] = layout->tileset_secondary_label; layoutObj["border_filepath"] = layout->border_path; layoutObj["blockdata_filepath"] = layout->blockdata_path; for (auto it = layout->customData.constBegin(); it != layout->customData.constEnd(); it++) { layoutObj[it.key()] = OrderedJson::fromQJsonValue(it.value()); } layoutsArr.push_back(layoutObj); } layoutsObj["layouts"] = layoutsArr; for (auto it = this->customLayoutsData.constBegin(); it != this->customLayoutsData.constEnd(); it++) { layoutsObj[it.key()] = OrderedJson::fromQJsonValue(it.value()); } ignoreWatchedFileTemporarily(layoutsFilepath); OrderedJson layoutJson(layoutsObj); OrderedJsonDoc jsonDoc(&layoutJson); jsonDoc.dump(&layoutsFile); layoutsFile.close(); } void Project::ignoreWatchedFileTemporarily(QString filepath) { // Ignore any file-change events for this filepath for the next 5 seconds. this->modifiedFileTimestamps.insert(filepath, QDateTime::currentMSecsSinceEpoch() + 5000); } void Project::recordFileChange(const QString &filepath) { if (this->modifiedFiles.contains(filepath)) { // We already recorded a change to this file return; } if (this->modifiedFileTimestamps.contains(filepath)) { if (QDateTime::currentMSecsSinceEpoch() < this->modifiedFileTimestamps[filepath]) { // We're still ignoring changes to this file return; } this->modifiedFileTimestamps.remove(filepath); } this->modifiedFiles.insert(filepath); emit fileChanged(filepath); } void Project::saveMapGroups() { QString mapGroupsFilepath = QString("%1/%2").arg(root).arg(projectConfig.getFilePath(ProjectFilePath::json_map_groups)); QFile mapGroupsFile(mapGroupsFilepath); if (!mapGroupsFile.open(QIODevice::WriteOnly)) { logError(QString("Error: Could not open %1 for writing").arg(mapGroupsFilepath)); return; } OrderedJson::object mapGroupsObj; OrderedJson::array groupNamesArr; for (QString groupName : this->groupNames) { groupNamesArr.push_back(groupName); } mapGroupsObj["group_order"] = groupNamesArr; for (const auto &groupName : this->groupNames) { OrderedJson::array groupArr; for (const auto &mapName : this->groupNameToMapNames.value(groupName)) { if (this->maps.value(mapName) && !this->maps.value(mapName)->isPersistedToFile()) { // This is a new map that hasn't been saved yet, don't add it to the global map groups list yet. continue; } groupArr.push_back(mapName); } mapGroupsObj[groupName] = groupArr; } for (auto it = this->customMapGroupsData.constBegin(); it != this->customMapGroupsData.constEnd(); it++) { mapGroupsObj[it.key()] = OrderedJson::fromQJsonValue(it.value()); } ignoreWatchedFileTemporarily(mapGroupsFilepath); OrderedJson mapGroupJson(mapGroupsObj); OrderedJsonDoc jsonDoc(&mapGroupJson); jsonDoc.dump(&mapGroupsFile); mapGroupsFile.close(); } void Project::saveRegionMapSections() { const QString filepath = QString("%1/%2").arg(this->root).arg(projectConfig.getFilePath(ProjectFilePath::json_region_map_entries)); QFile file(filepath); if (!file.open(QIODevice::WriteOnly)) { logError(QString("Could not open '%1' for writing").arg(filepath)); return; } OrderedJson::array mapSectionArray; for (const auto &idName : this->mapSectionIdNamesSaveOrder) { const LocationData location = this->locationData.value(idName); OrderedJson::object mapSectionObj; mapSectionObj["id"] = idName; if (!location.displayName.isEmpty()) { mapSectionObj["name"] = location.displayName; } if (location.map.valid) { mapSectionObj["x"] = location.map.x; mapSectionObj["y"] = location.map.y; mapSectionObj["width"] = location.map.width; mapSectionObj["height"] = location.map.height; } for (auto it = location.custom.constBegin(); it != location.custom.constEnd(); it++) { mapSectionObj[it.key()] = OrderedJson::fromQJsonValue(it.value()); } mapSectionArray.append(mapSectionObj); } OrderedJson::object object; object["map_sections"] = mapSectionArray; for (auto it = this->customMapSectionsData.constBegin(); it != this->customMapSectionsData.constEnd(); it++) { object[it.key()] = OrderedJson::fromQJsonValue(it.value()); } ignoreWatchedFileTemporarily(filepath); OrderedJson json(object); OrderedJsonDoc jsonDoc(&json); jsonDoc.dump(&file); file.close(); } void Project::saveWildMonData() { if (!this->wildEncountersLoaded) return; QString wildEncountersJsonFilepath = QString("%1/%2").arg(root).arg(projectConfig.getFilePath(ProjectFilePath::json_wild_encounters)); QFile wildEncountersFile(wildEncountersJsonFilepath); if (!wildEncountersFile.open(QIODevice::WriteOnly)) { logError(QString("Error: Could not open %1 for writing").arg(wildEncountersJsonFilepath)); return; } OrderedJson::object wildEncountersObject; OrderedJson::array wildEncounterGroups; OrderedJson::object monHeadersObject; monHeadersObject["label"] = this->wildMonTableName; monHeadersObject["for_maps"] = true; OrderedJson::array fieldsInfoArray; for (EncounterField fieldInfo : wildMonFields) { OrderedJson::object fieldObject; OrderedJson::array rateArray; for (int rate : fieldInfo.encounterRates) { rateArray.push_back(rate); } fieldObject["type"] = fieldInfo.name; fieldObject["encounter_rates"] = rateArray; OrderedJson::object groupsObject; for (auto groupNamePair : fieldInfo.groups) { QString groupName = groupNamePair.first; OrderedJson::array subGroupIndices; std::sort(fieldInfo.groups[groupName].begin(), fieldInfo.groups[groupName].end()); for (int slotIndex : fieldInfo.groups[groupName]) { subGroupIndices.push_back(slotIndex); } groupsObject[groupName] = subGroupIndices; } if (!groupsObject.empty()) fieldObject["groups"] = groupsObject; fieldsInfoArray.append(fieldObject); } monHeadersObject["fields"] = fieldsInfoArray; OrderedJson::array encountersArray; for (auto keyPair : wildMonData) { QString key = keyPair.first; for (auto grouplLabelPair : wildMonData[key]) { QString groupLabel = grouplLabelPair.first; OrderedJson::object encounterObject; encounterObject["map"] = key; encounterObject["base_label"] = groupLabel; WildPokemonHeader encounterHeader = wildMonData[key][groupLabel]; for (auto fieldNamePair : encounterHeader.wildMons) { QString fieldName = fieldNamePair.first; OrderedJson::object fieldObject; WildMonInfo monInfo = encounterHeader.wildMons[fieldName]; fieldObject["encounter_rate"] = monInfo.encounterRate; OrderedJson::array monArray; for (WildPokemon wildMon : monInfo.wildPokemon) { OrderedJson::object monEntry; monEntry["min_level"] = wildMon.minLevel; monEntry["max_level"] = wildMon.maxLevel; monEntry["species"] = wildMon.species; monArray.push_back(monEntry); } fieldObject["mons"] = monArray; encounterObject[fieldName] = fieldObject; } encountersArray.push_back(encounterObject); } } monHeadersObject["encounters"] = encountersArray; wildEncounterGroups.push_back(monHeadersObject); // add extra Json objects that are not associated with maps to the file for (auto extraObject : extraEncounterGroups) { wildEncounterGroups.push_back(extraObject); } wildEncountersObject["wild_encounter_groups"] = wildEncounterGroups; ignoreWatchedFileTemporarily(wildEncountersJsonFilepath); OrderedJson encounterJson(wildEncountersObject); OrderedJsonDoc jsonDoc(&encounterJson); jsonDoc.dump(&wildEncountersFile); wildEncountersFile.close(); } // For a map with a constant of 'MAP_FOO', returns a unique 'HEAL_LOCATION_FOO'. // Because of how event ID names are checked it doesn't guarantee that the name // won't be in-use by some map that hasn't been loaded yet. QString Project::getNewHealLocationName(const Map* map) const { if (!map) return QString(); QString idName = map->constantName(); const QString mapPrefix = projectConfig.getIdentifier(ProjectIdentifier::define_map_prefix); if (idName.startsWith(mapPrefix)) { idName.remove(0, mapPrefix.length()); } return toUniqueIdentifier(projectConfig.getIdentifier(ProjectIdentifier::define_heal_locations_prefix) + idName); } void Project::saveHealLocations() { const QString filepath = QString("%1/%2").arg(this->root).arg(projectConfig.getFilePath(ProjectFilePath::json_heal_locations)); QFile file(filepath); if (!file.open(QIODevice::WriteOnly)) { logError(QString("Could not open '%1' for writing").arg(filepath)); return; } // Build the JSON data for output. QMap> idNameToJson; for (auto i = this->healLocations.constBegin(); i != this->healLocations.constEnd(); i++) { const QString mapConstant = i.key(); for (const auto &event : i.value()) { // Heal location events don't need to track the "map" field, we're already tracking it either with // the keys in the healLocations map or by virtue of the event being added to a particular Map object. // The global JSON data needs this field, so we add it back here. auto eventJson = event->buildEventJson(this); eventJson["map"] = mapConstant; idNameToJson[event->getIdName()].append(eventJson); } } // We store Heal Locations in a QMap with map name keys. This makes retrieval by map name easy, // but it will sort them alphabetically. Project::healLocationSaveOrder lets us better support // the (perhaps unlikely) user who has designed something with assumptions about the order of the data. // This also avoids a bunch of diff noise on the first save from Porymap reordering the data. OrderedJson::array eventJsonArr; for (const auto &idName : this->healLocationSaveOrder) { if (!idNameToJson.value(idName).isEmpty()) { eventJsonArr.push_back(idNameToJson[idName].takeFirst()); } } // Save any heal locations that weren't covered above (should be any new data). for (auto i = idNameToJson.constBegin(); i != idNameToJson.constEnd(); i++) { for (const auto &object : i.value()) { eventJsonArr.push_back(object); } } OrderedJson::object object; object["heal_locations"] = eventJsonArr; for (auto it = this->customHealLocationsData.constBegin(); it != this->customHealLocationsData.constEnd(); it++) { object[it.key()] = OrderedJson::fromQJsonValue(it.value()); } ignoreWatchedFileTemporarily(filepath); OrderedJson json(object); OrderedJsonDoc jsonDoc(&json); jsonDoc.dump(&file); file.close(); } void Project::saveTilesets(Tileset *primaryTileset, Tileset *secondaryTileset) { saveTilesetMetatileLabels(primaryTileset, secondaryTileset); if (primaryTileset) primaryTileset->save(); if (secondaryTileset) secondaryTileset->save(); } void Project::updateTilesetMetatileLabels(Tileset *tileset) { // Erase old labels, then repopulate with new labels const QString prefix = tileset->getMetatileLabelPrefix(); this->metatileLabelsMap[tileset->name].clear(); for (auto i = tileset->metatileLabels.constBegin(); i != tileset->metatileLabels.constEnd(); i++) { uint16_t metatileId = i.key(); QString label = i.value(); if (!label.isEmpty()) { this->metatileLabelsMap[tileset->name][prefix + label] = metatileId; } } } // Given a map of define names to define values, returns a formatted list of #defines QString Project::buildMetatileLabelsText(const QMap defines) { QStringList labels = defines.keys(); // Setup for pretty formatting. int longestLength = 0; for (QString label : labels) { if (label.size() > longestLength) longestLength = label.size(); } // Generate defines text QString output = QString(); for (QString label : labels) { QString line = QString("#define %1 %2\n") .arg(label, -1 * longestLength) .arg(Metatile::getMetatileIdString(defines[label])); output += line; } return output; } void Project::saveTilesetMetatileLabels(Tileset *primaryTileset, Tileset *secondaryTileset) { // Skip writing the file if there are no labels in both the new and old sets if (metatileLabelsMap[primaryTileset->name].size() == 0 && primaryTileset->metatileLabels.size() == 0 && metatileLabelsMap[secondaryTileset->name].size() == 0 && secondaryTileset->metatileLabels.size() == 0) return; updateTilesetMetatileLabels(primaryTileset); updateTilesetMetatileLabels(secondaryTileset); // Recreate metatile labels file const QString guardName = "GUARD_METATILE_LABELS_H"; QString outputText = QString("#ifndef %1\n#define %1\n").arg(guardName); for (auto i = this->metatileLabelsMap.constBegin(); i != this->metatileLabelsMap.constEnd(); i++) { const QString tilesetName = i.key(); const QMap tilesetMetatileLabels = i.value(); if (tilesetMetatileLabels.isEmpty()) continue; outputText += QString("\n// %1\n%2").arg(tilesetName).arg(buildMetatileLabelsText(tilesetMetatileLabels)); } if (unusedMetatileLabels.size() != 0) { // Append any defines originally read from the file that aren't associated with any tileset. outputText += QString("\n// Other\n"); outputText += buildMetatileLabelsText(unusedMetatileLabels); } outputText += QString("\n#endif // %1\n").arg(guardName); QString filename = projectConfig.getFilePath(ProjectFilePath::constants_metatile_labels); ignoreWatchedFileTemporarily(root + "/" + filename); saveTextFile(root + "/" + filename, outputText); } bool Project::loadLayoutTilesets(Layout *layout) { layout->tileset_primary = getTileset(layout->tileset_primary_label); if (!layout->tileset_primary) { QString defaultTileset = this->getDefaultPrimaryTilesetLabel(); layout->tileset_primary_label = defaultTileset; layout->tileset_primary = getTileset(layout->tileset_primary_label); if (!layout->tileset_primary) { logError(QString("%1 has invalid primary tileset '%2'.").arg(layout->name).arg(layout->tileset_primary_label)); return false; } logWarn(QString("%1 has invalid primary tileset '%2'. Using default '%3'").arg(layout->name).arg(layout->tileset_primary_label).arg(defaultTileset)); } layout->tileset_secondary = getTileset(layout->tileset_secondary_label); if (!layout->tileset_secondary) { QString defaultTileset = this->getDefaultSecondaryTilesetLabel(); layout->tileset_secondary_label = defaultTileset; layout->tileset_secondary = getTileset(layout->tileset_secondary_label); if (!layout->tileset_secondary) { logError(QString("%1 has invalid secondary tileset '%2'.").arg(layout->name).arg(layout->tileset_secondary_label)); return false; } logWarn(QString("%1 has invalid secondary tileset '%2'. Using default '%3'").arg(layout->name).arg(layout->tileset_secondary_label).arg(defaultTileset)); } return true; } Tileset* Project::loadTileset(QString label, Tileset *tileset) { auto memberMap = Tileset::getHeaderMemberMap(this->usingAsmTilesets); if (this->usingAsmTilesets) { // Read asm tileset header. Backwards compatibility const QStringList values = parser.getLabelValues(parser.parseAsm(projectConfig.getFilePath(ProjectFilePath::tilesets_headers_asm)), label); if (values.isEmpty()) { return nullptr; } if (tileset == nullptr) { tileset = new Tileset; } tileset->name = label; tileset->is_secondary = ParseUtil::gameStringToBool(values.value(memberMap.key("isSecondary"))); tileset->tiles_label = values.value(memberMap.key("tiles")); tileset->palettes_label = values.value(memberMap.key("palettes")); tileset->metatiles_label = values.value(memberMap.key("metatiles")); tileset->metatile_attrs_label = values.value(memberMap.key("metatileAttributes")); } else { // Read C tileset header auto structs = parser.readCStructs(projectConfig.getFilePath(ProjectFilePath::tilesets_headers), label, memberMap); if (!structs.contains(label)) { return nullptr; } if (tileset == nullptr) { tileset = new Tileset; } auto tilesetAttributes = structs[label]; tileset->name = label; tileset->is_secondary = ParseUtil::gameStringToBool(tilesetAttributes.value("isSecondary")); tileset->tiles_label = tilesetAttributes.value("tiles"); tileset->palettes_label = tilesetAttributes.value("palettes"); tileset->metatiles_label = tilesetAttributes.value("metatiles"); tileset->metatile_attrs_label = tilesetAttributes.value("metatileAttributes"); } loadTilesetAssets(tileset); tilesetCache.insert(label, tileset); return tileset; } bool Project::loadBlockdata(Layout *layout) { bool ok = true; QString path = QString("%1/%2").arg(root).arg(layout->blockdata_path); auto blockdata = readBlockdata(path, &ok); if (!ok) { logError(QString("Failed to load layout blockdata from '%1'").arg(path)); return false; } layout->blockdata = blockdata; layout->lastCommitBlocks.blocks = blockdata; layout->lastCommitBlocks.layoutDimensions = QSize(layout->getWidth(), layout->getHeight()); if (layout->blockdata.count() != layout->getWidth() * layout->getHeight()) { logWarn(QString("%1 blockdata length %2 does not match dimensions %3x%4 (should be %5). Resizing blockdata.") .arg(layout->name) .arg(layout->blockdata.count()) .arg(layout->getWidth()) .arg(layout->getHeight()) .arg(layout->getWidth() * layout->getHeight())); layout->blockdata.resize(layout->getWidth() * layout->getHeight()); } return true; } void Project::setNewLayoutBlockdata(Layout *layout) { layout->blockdata.clear(); int width = layout->getWidth(); int height = layout->getHeight(); Block block(projectConfig.defaultMetatileId, projectConfig.defaultCollision, projectConfig.defaultElevation); for (int i = 0; i < width * height; i++) { layout->blockdata.append(block); } layout->lastCommitBlocks.blocks = layout->blockdata; layout->lastCommitBlocks.layoutDimensions = QSize(width, height); } bool Project::loadLayoutBorder(Layout *layout) { bool ok = true; QString path = QString("%1/%2").arg(root).arg(layout->border_path); auto blockdata = readBlockdata(path, &ok); if (!ok) { logError(QString("Failed to load layout border from '%1'").arg(path)); return false; } layout->border = blockdata; layout->lastCommitBlocks.border = blockdata; layout->lastCommitBlocks.borderDimensions = QSize(layout->getBorderWidth(), layout->getBorderHeight()); int borderLength = layout->getBorderWidth() * layout->getBorderHeight(); if (layout->border.count() != borderLength) { logWarn(QString("%1 border blockdata length %2 must be %3. Resizing border blockdata.") .arg(layout->name) .arg(layout->border.count()) .arg(borderLength)); layout->border.resize(borderLength); } return true; } void Project::setNewLayoutBorder(Layout *layout) { layout->border.clear(); int width = layout->getBorderWidth(); int height = layout->getBorderHeight(); if (projectConfig.newMapBorderMetatileIds.length() != width * height) { // Border size doesn't match the number of default border metatiles. // Fill the border with empty metatiles. for (int i = 0; i < width * height; i++) { layout->border.append(0); } } else { // Fill the border with the default metatiles from the config. for (int i = 0; i < width * height; i++) { layout->border.append(projectConfig.newMapBorderMetatileIds.at(i)); } } layout->lastCommitBlocks.border = layout->border; layout->lastCommitBlocks.borderDimensions = QSize(width, height); } void Project::saveLayoutBorder(Layout *layout) { QString path = QString("%1/%2").arg(root).arg(layout->border_path); writeBlockdata(path, layout->border); } void Project::saveLayoutBlockdata(Layout *layout) { QString path = QString("%1/%2").arg(root).arg(layout->blockdata_path); writeBlockdata(path, layout->blockdata); } void Project::writeBlockdata(QString path, const Blockdata &blockdata) { QFile file(path); if (file.open(QIODevice::WriteOnly)) { QByteArray data = blockdata.serialize(); file.write(data); } else { logError(QString("Failed to open blockdata file for writing: '%1'").arg(path)); } } void Project::saveAll() { for (auto map : this->maps) { saveMap(map, true); // Avoid double-saving the layouts } for (auto layout : this->mapLayouts) { saveLayout(layout); } saveGlobalData(); } void Project::saveMap(Map *map, bool skipLayout) { if (!map || !isMapLoaded(map)) return; // Create/Modify a few collateral files for brand new maps. const QString folderPath = projectConfig.getFilePath(ProjectFilePath::data_map_folders) + map->name(); const QString fullPath = QString("%1/%2").arg(this->root).arg(folderPath); if (!map->isPersistedToFile()) { if (!QDir::root().mkpath(fullPath)) { logError(QString("Failed to create directory for new map: '%1'").arg(fullPath)); return; } // Create file data/maps//scripts.inc QString text = this->getScriptDefaultString(projectConfig.usePoryScript, map->name()); saveTextFile(fullPath + "/scripts" + this->getScriptFileExtension(projectConfig.usePoryScript), text); if (projectConfig.createMapTextFileEnabled) { // Create file data/maps//text.inc saveTextFile(fullPath + "/text" + this->getScriptFileExtension(projectConfig.usePoryScript), "\n"); } // Simply append to data/event_scripts.s. text = QString("\n\t.include \"%1/scripts.inc\"\n").arg(folderPath); if (projectConfig.createMapTextFileEnabled) { text += QString("\t.include \"%1/text.inc\"\n").arg(folderPath); } appendTextFile(root + "/" + projectConfig.getFilePath(ProjectFilePath::data_event_scripts), text); } // Create map.json for map data. QString mapFilepath = fullPath + "/map.json"; QFile mapFile(mapFilepath); if (!mapFile.open(QIODevice::WriteOnly)) { logError(QString("Error: Could not open %1 for writing").arg(mapFilepath)); return; } OrderedJson::object mapObj; // Header values. mapObj["id"] = map->constantName(); mapObj["name"] = map->name(); mapObj["layout"] = map->layout()->id; mapObj["music"] = map->header()->song(); mapObj["region_map_section"] = map->header()->location(); mapObj["requires_flash"] = map->header()->requiresFlash(); mapObj["weather"] = map->header()->weather(); mapObj["map_type"] = map->header()->type(); if (projectConfig.mapAllowFlagsEnabled) { mapObj["allow_cycling"] = map->header()->allowsBiking(); mapObj["allow_escaping"] = map->header()->allowsEscaping(); mapObj["allow_running"] = map->header()->allowsRunning(); } mapObj["show_map_name"] = map->header()->showsLocationName(); if (projectConfig.floorNumberEnabled) { mapObj["floor_number"] = map->header()->floorNumber(); } mapObj["battle_scene"] = map->header()->battleScene(); // Connections const auto connections = map->getConnections(); if (connections.length() > 0) { OrderedJson::array connectionsArr; for (const auto &connection : connections) { OrderedJson::object connectionObj; connectionObj["map"] = getMapConstant(connection->targetMapName(), connection->targetMapName()); connectionObj["offset"] = connection->offset(); connectionObj["direction"] = connection->direction(); auto customData = connection->customData(); for (auto it = customData.constBegin(); it != customData.constEnd(); it++) { connectionObj[it.key()] = OrderedJson::fromQJsonValue(it.value()); } connectionsArr.append(connectionObj); } mapObj["connections"] = connectionsArr; } else { mapObj["connections"] = OrderedJson(); } if (map->sharedEventsMap().isEmpty()) { // Object events OrderedJson::array objectEventsArr; for (const auto &event : map->getEvents(Event::Group::Object)){ objectEventsArr.push_back(event->buildEventJson(this)); } mapObj["object_events"] = objectEventsArr; // Warp events OrderedJson::array warpEventsArr; for (const auto &event : map->getEvents(Event::Group::Warp)) { warpEventsArr.push_back(event->buildEventJson(this)); } mapObj["warp_events"] = warpEventsArr; // Coord events OrderedJson::array coordEventsArr; for (const auto &event : map->getEvents(Event::Group::Coord)) { coordEventsArr.push_back(event->buildEventJson(this)); } mapObj["coord_events"] = coordEventsArr; // Bg Events OrderedJson::array bgEventsArr; for (const auto &event : map->getEvents(Event::Group::Bg)) { bgEventsArr.push_back(event->buildEventJson(this)); } mapObj["bg_events"] = bgEventsArr; } else { mapObj["shared_events_map"] = map->sharedEventsMap(); } if (!map->sharedScriptsMap().isEmpty()) { mapObj["shared_scripts_map"] = map->sharedScriptsMap(); } // Update the global heal locations array using the Map's heal location events. // This won't get saved to disc until Project::saveHealLocations is called. QList hlEvents; for (const auto &event : map->getEvents(Event::Group::Heal)) { auto hl = static_cast(event); hlEvents.append(static_cast(hl->duplicate())); } qDeleteAll(this->healLocations[map->constantName()]); this->healLocations[map->constantName()] = hlEvents; // Custom header fields. const auto customAttributes = map->customAttributes(); for (auto i = customAttributes.constBegin(); i != customAttributes.constEnd(); i++) { mapObj[i.key()] = OrderedJson::fromQJsonValue(i.value()); } OrderedJson mapJson(mapObj); OrderedJsonDoc jsonDoc(&mapJson); jsonDoc.dump(&mapFile); mapFile.close(); if (!skipLayout) saveLayout(map->layout()); // Try to record the MAPSEC name in case this is a new name. addNewMapsec(map->header()->location()); map->setClean(); } void Project::saveLayout(Layout *layout) { if (!layout || !isLayoutLoaded(layout)) return; if (!layout->newFolderPath.isEmpty()) { // Layout directory doesn't exist yet, create it now. const QString fullPath = QString("%1/%2").arg(this->root).arg(layout->newFolderPath); if (!QDir::root().mkpath(fullPath)) { logError(QString("Failed to create directory for new layout: '%1'").arg(fullPath)); return; } layout->newFolderPath = QString(); } saveLayoutBorder(layout); saveLayoutBlockdata(layout); // Update global data structures with current map data. updateLayout(layout); layout->setClean(); } void Project::updateLayout(Layout *layout) { if (!this->layoutIdsMaster.contains(layout->id)) { this->layoutIdsMaster.append(layout->id); } if (this->mapLayoutsMaster.contains(layout->id)) { this->mapLayoutsMaster[layout->id]->copyFrom(layout); } else { this->mapLayoutsMaster.insert(layout->id, layout->copy()); } } void Project::saveGlobalData() { saveMapLayouts(); saveMapGroups(); saveRegionMapSections(); saveHealLocations(); saveWildMonData(); saveConfig(); this->hasUnsavedDataChanges = false; } void Project::saveConfig() { projectConfig.save(); userConfig.save(); } void Project::loadTilesetAssets(Tileset* tileset) { if (tileset->name.isNull()) { return; } readTilesetPaths(tileset); loadTilesetMetatileLabels(tileset); tileset->load(); } void Project::readTilesetPaths(Tileset* tileset) { // Parse the tileset data files to try and get explicit file paths for this tileset's assets const QString rootDir = this->root + "/"; if (this->usingAsmTilesets) { // Read asm tileset data files. Backwards compatibility const QList graphics = parser.parseAsm(projectConfig.getFilePath(ProjectFilePath::tilesets_graphics_asm)); const QList metatiles_macros = parser.parseAsm(projectConfig.getFilePath(ProjectFilePath::tilesets_metatiles_asm)); const QStringList tiles_values = parser.getLabelValues(graphics, tileset->tiles_label); const QStringList palettes_values = parser.getLabelValues(graphics, tileset->palettes_label); const QStringList metatiles_values = parser.getLabelValues(metatiles_macros, tileset->metatiles_label); const QStringList metatile_attrs_values = parser.getLabelValues(metatiles_macros, tileset->metatile_attrs_label); if (!tiles_values.isEmpty()) tileset->tilesImagePath = this->fixGraphicPath(rootDir + tiles_values.value(0).section('"', 1, 1)); if (!metatiles_values.isEmpty()) tileset->metatiles_path = rootDir + metatiles_values.value(0).section('"', 1, 1); if (!metatile_attrs_values.isEmpty()) tileset->metatile_attrs_path = rootDir + metatile_attrs_values.value(0).section('"', 1, 1); for (const auto &value : palettes_values) tileset->palettePaths.append(this->fixPalettePath(rootDir + value.section('"', 1, 1))); } else { // Read C tileset data files const QString graphicsFile = projectConfig.getFilePath(ProjectFilePath::tilesets_graphics); const QString metatilesFile = projectConfig.getFilePath(ProjectFilePath::tilesets_metatiles); const QString tilesImagePath = parser.readCIncbin(graphicsFile, tileset->tiles_label); const QStringList palettePaths = parser.readCIncbinArray(graphicsFile, tileset->palettes_label); const QString metatilesPath = parser.readCIncbin(metatilesFile, tileset->metatiles_label); const QString metatileAttrsPath = parser.readCIncbin(metatilesFile, tileset->metatile_attrs_label); if (!tilesImagePath.isEmpty()) tileset->tilesImagePath = this->fixGraphicPath(rootDir + tilesImagePath); if (!metatilesPath.isEmpty()) tileset->metatiles_path = rootDir + metatilesPath; if (!metatileAttrsPath.isEmpty()) tileset->metatile_attrs_path = rootDir + metatileAttrsPath; for (const auto &path : palettePaths) tileset->palettePaths.append(this->fixPalettePath(rootDir + path)); } // Try to set default paths, if any weren't found by reading the files above QString defaultPath = rootDir + tileset->getExpectedDir(); if (tileset->tilesImagePath.isEmpty()) tileset->tilesImagePath = defaultPath + "/tiles.png"; if (tileset->metatiles_path.isEmpty()) tileset->metatiles_path = defaultPath + "/metatiles.bin"; if (tileset->metatile_attrs_path.isEmpty()) tileset->metatile_attrs_path = defaultPath + "/metatile_attributes.bin"; if (tileset->palettePaths.isEmpty()) { QString palettes_dir_path = defaultPath + "/palettes/"; for (int i = 0; i < 16; i++) { tileset->palettePaths.append(palettes_dir_path + QString("%1").arg(i, 2, 10, QLatin1Char('0')) + ".pal"); } } } Tileset *Project::createNewTileset(QString name, bool secondary, bool checkerboardFill) { const QString prefix = projectConfig.getIdentifier(ProjectIdentifier::symbol_tilesets_prefix); if (!name.startsWith(prefix)) { logError(QString("Tileset name '%1' doesn't begin with the prefix '%2'.").arg(name).arg(prefix)); return nullptr; } auto tileset = new Tileset(); tileset->name = name; tileset->is_secondary = secondary; // Create tileset directories const QString fullDirectoryPath = QString("%1/%2").arg(this->root).arg(tileset->getExpectedDir()); QDir directory; if (!directory.mkpath(fullDirectoryPath)) { logError(QString("Failed to create directory '%1' for new tileset '%2'").arg(fullDirectoryPath).arg(tileset->name)); delete tileset; return nullptr; } const QString palettesPath = fullDirectoryPath + "/palettes"; if (!directory.mkpath(palettesPath)) { logError(QString("Failed to create palettes directory '%1' for new tileset '%2'").arg(palettesPath).arg(tileset->name)); delete tileset; return nullptr; } tileset->tilesImagePath = fullDirectoryPath + "/tiles.png"; tileset->metatiles_path = fullDirectoryPath + "/metatiles.bin"; tileset->metatile_attrs_path = fullDirectoryPath + "/metatile_attributes.bin"; // Set default tiles image QImage tilesImage(":/images/blank_tileset.png"); tileset->loadTilesImage(&tilesImage); // Create default metatiles const int numMetatiles = tileset->is_secondary ? (Project::getNumMetatilesTotal() - Project::getNumMetatilesPrimary()) : Project::getNumMetatilesPrimary(); const int tilesPerMetatile = projectConfig.getNumTilesInMetatile(); for (int i = 0; i < numMetatiles; ++i) { auto metatile = new Metatile(); for(int j = 0; j < tilesPerMetatile; ++j){ Tile tile = Tile(); if (checkerboardFill) { // Create a checkerboard-style dummy tileset if (((i / 8) % 2) == 0) tile.tileId = ((i % 2) == 0) ? 1 : 2; else tile.tileId = ((i % 2) == 1) ? 1 : 2; if (tileset->is_secondary) tile.tileId += Project::getNumTilesPrimary(); } metatile->tiles.append(tile); } tileset->addMetatile(metatile); } // Create default palettes for(int i = 0; i < 16; ++i) { QList currentPal; for(int i = 0; i < 16;++i) { currentPal.append(qRgb(0,0,0)); } tileset->palettes.append(currentPal); tileset->palettePreviews.append(currentPal); tileset->palettePaths.append(QString("%1/%2.pal").arg(palettesPath).arg(i, 2, 10, QLatin1Char('0'))); } tileset->palettes[0][1] = qRgb(255,0,255); tileset->palettePreviews[0][1] = qRgb(255,0,255); // Update tileset label arrays QStringList *labelList = tileset->is_secondary ? &this->secondaryTilesetLabels : &this->primaryTilesetLabels; int i = 0; for (; i < labelList->length(); i++) { if (labelList->at(i) > tileset->name) { break; } } labelList->insert(i, tileset->name); this->tilesetLabelsOrdered.append(tileset->name); // TODO: Ideally we wouldn't save new Tilesets immediately // Append to tileset specific files. Strip prefix from name to get base name for use in other symbols. name.remove(0, prefix.length()); tileset->appendToHeaders(this->root, name, this->usingAsmTilesets); tileset->appendToGraphics(this->root, name, this->usingAsmTilesets); tileset->appendToMetatiles(this->root, name, this->usingAsmTilesets); tileset->save(); this->tilesetCache.insert(tileset->name, tileset); emit tilesetCreated(tileset); return tileset; } QString Project::findMetatileLabelsTileset(QString label) { for (const QString &tilesetName : this->tilesetLabelsOrdered) { QString metatileLabelPrefix = Tileset::getMetatileLabelPrefix(tilesetName); if (label.startsWith(metatileLabelPrefix)) return tilesetName; } return QString(); } bool Project::readTilesetMetatileLabels() { metatileLabelsMap.clear(); unusedMetatileLabels.clear(); QString metatileLabelsFilename = projectConfig.getFilePath(ProjectFilePath::constants_metatile_labels); fileWatcher.addPath(root + "/" + metatileLabelsFilename); const QSet regexList = {QString("\\b%1").arg(projectConfig.getIdentifier(ProjectIdentifier::define_metatile_label_prefix))}; const QMap defines = parser.readCDefinesByRegex(metatileLabelsFilename, regexList); for (auto i = defines.constBegin(); i != defines.constEnd(); i++) { QString label = i.key(); uint32_t metatileId = i.value(); if (metatileId > Block::maxValue) { metatileId &= Block::maxValue; logWarn(QString("Value of metatile label '%1' truncated to %2").arg(label).arg(Metatile::getMetatileIdString(metatileId))); } QString tilesetName = findMetatileLabelsTileset(label); if (!tilesetName.isEmpty()) { metatileLabelsMap[tilesetName][label] = metatileId; } else { // This #define name does not match any existing tileset. // Save it separately to be outputted later. unusedMetatileLabels[label] = metatileId; } } return true; } void Project::loadTilesetMetatileLabels(Tileset* tileset) { QString metatileLabelPrefix = tileset->getMetatileLabelPrefix(); // Reverse map for faster lookup by metatile id for (auto it = this->metatileLabelsMap[tileset->name].constBegin(); it != this->metatileLabelsMap[tileset->name].constEnd(); it++) { QString labelName = it.key(); tileset->metatileLabels[it.value()] = labelName.replace(metatileLabelPrefix, ""); } } Blockdata Project::readBlockdata(QString path, bool *ok) { Blockdata blockdata; QFile file(path); if (file.open(QIODevice::ReadOnly)) { QByteArray data = file.readAll(); for (int i = 0; (i + 1) < data.length(); i += 2) { uint16_t word = static_cast((data[i] & 0xff) + ((data[i + 1] & 0xff) << 8)); blockdata.append(word); } if (ok) *ok = true; } else { // Failed if (ok) *ok = false; } return blockdata; } Tileset* Project::getTileset(QString label, bool forceLoad) { Tileset *existingTileset = nullptr; if (tilesetCache.contains(label)) { existingTileset = tilesetCache.value(label); } if (existingTileset && !forceLoad) { return existingTileset; } else { Tileset *tileset = loadTileset(label, existingTileset); return tileset; } } void Project::saveTextFile(QString path, QString text) { QFile file(path); if (file.open(QIODevice::WriteOnly)) { file.write(text.toUtf8()); } else { logError(QString("Could not open '%1' for writing: ").arg(path) + file.errorString()); } } void Project::appendTextFile(QString path, QString text) { QFile file(path); if (file.open(QIODevice::Append)) { file.write(text.toUtf8()); } else { logError(QString("Could not open '%1' for appending: ").arg(path) + file.errorString()); } } void Project::deleteFile(QString path) { QFile file(path); if (file.exists() && !file.remove()) { logError(QString("Could not delete file '%1': ").arg(path) + file.errorString()); } } bool Project::readWildMonData() { this->extraEncounterGroups.clear(); this->wildMonFields.clear(); this->wildMonData.clear(); this->wildMonTableName.clear(); this->encounterGroupLabels.clear(); this->pokemonMinLevel = 0; this->pokemonMaxLevel = 100; this->maxEncounterRate = 2880/16; this->wildEncountersLoaded = false; if (!userConfig.useEncounterJson) { return true; } // Read max encounter rate. The games multiply the encounter rate value in the map data by 16, so our input limit is the max/16. const QString encounterRateFile = projectConfig.getFilePath(ProjectFilePath::wild_encounter); const QString maxEncounterRateName = projectConfig.getIdentifier(ProjectIdentifier::define_max_encounter_rate); fileWatcher.addPath(QString("%1/%2").arg(root).arg(encounterRateFile)); auto defines = parser.readCDefinesByName(encounterRateFile, {maxEncounterRateName}); if (defines.contains(maxEncounterRateName)) this->maxEncounterRate = defines.value(maxEncounterRateName)/16; // Read min/max level const QString levelRangeFile = projectConfig.getFilePath(ProjectFilePath::constants_pokemon); const QString minLevelName = projectConfig.getIdentifier(ProjectIdentifier::define_min_level); const QString maxLevelName = projectConfig.getIdentifier(ProjectIdentifier::define_max_level); fileWatcher.addPath(QString("%1/%2").arg(root).arg(levelRangeFile)); defines = parser.readCDefinesByName(levelRangeFile, {minLevelName, maxLevelName}); if (defines.contains(minLevelName)) this->pokemonMinLevel = defines.value(minLevelName); if (defines.contains(maxLevelName)) this->pokemonMaxLevel = defines.value(maxLevelName); this->pokemonMinLevel = qMin(this->pokemonMinLevel, this->pokemonMaxLevel); this->pokemonMaxLevel = qMax(this->pokemonMinLevel, this->pokemonMaxLevel); // Read encounter data const QString wildMonJsonFilepath = projectConfig.getFilePath(ProjectFilePath::json_wild_encounters); fileWatcher.addPath(QString("%1/%2").arg(this->root).arg(wildMonJsonFilepath)); OrderedJson::object wildMonObj; QString error; if (!parser.tryParseOrderedJsonFile(&wildMonObj, wildMonJsonFilepath, &error)) { // Failing to read wild encounters data is not a critical error, the encounter editor will just be disabled logWarn(QString("Failed to read wild encounters from '%1': %2").arg(wildMonJsonFilepath).arg(error)); return true; } // For each encounter type, count the number of times each encounter rate value occurs. // The most common value will be used as the default for new groups. QMap> encounterRateFrequencyMaps; // Parse "wild_encounter_groups". This is the main object array containing all the data in this file. for (OrderedJson mainArrayJson : wildMonObj["wild_encounter_groups"].array_items()) { OrderedJson::object mainArrayObject = mainArrayJson.object_items(); // We're only interested in wild encounter data that's associated with maps ("for_maps" == true). // Any other wild encounter data (e.g. for Battle Pike / Battle Pyramid) will be ignored. // We'll record any data that's not for maps in extraEncounterGroups to be outputted when we save. if (!mainArrayObject["for_maps"].bool_value()) { this->extraEncounterGroups.push_back(mainArrayObject); continue; } // If multiple "for_maps" data sets are found they will be collapsed into a single set. QString label = mainArrayObject["label"].string_value(); if (this->wildMonTableName.isEmpty()) { this->wildMonTableName = label; } else { logWarn(QString("Wild encounters table '%1' will be combined with '%2'. Only one table with \"for_maps\" set to 'true' is expected.") .arg(label) .arg(this->wildMonTableName)); } // Parse the "fields" data. This is like the header for the wild encounters data. // Each element describes a type of wild encounter Porymap can expect to find, and we represent this data with an EncounterField. // They should contain a name ("type"), the number of encounter slots and the ratio at which they occur ("encounter_rates"), // and whether the encounters are divided into groups (like fishing rods). for (const OrderedJson &fieldJson : mainArrayObject["fields"].array_items()) { OrderedJson::object fieldObject = fieldJson.object_items(); EncounterField encounterField; encounterField.name = fieldObject["type"].string_value(); for (auto val : fieldObject["encounter_rates"].array_items()) { encounterField.encounterRates.append(val.int_value()); } // Each element of the "groups" array is an object with the group name as the key (e.g. "old_rod") // and an array of slot numbers indicating which encounter slots in this encounter type belong to that group. for (auto groupPair : fieldObject["groups"].object_items()) { const QString groupName = groupPair.first; for (auto slotNum : groupPair.second.array_items()) { encounterField.groups[groupName].append(slotNum.int_value()); } } encounterRateFrequencyMaps.insert(encounterField.name, QMap()); this->wildMonFields.append(encounterField); } // Parse the "encounters" data. This is the meat of the wild encounters data. // Each element is an object that will tell us which map it's associated with, // its symbol name (which we will display in the Groups dropdown) and a list of // pokémon associated with any of the encounter types described by the data we parsed above. for (const auto &encounterJson : mainArrayObject["encounters"].array_items()) { OrderedJson::object encounterObj = encounterJson.object_items(); WildPokemonHeader header; // Check for each possible encounter type. for (const EncounterField &monField : this->wildMonFields) { const QString field = monField.name; if (encounterObj[field].is_null()) { // Encounter type isn't present continue; } OrderedJson::object encounterFieldObj = encounterObj[field].object_items(); WildMonInfo monInfo; monInfo.active = true; // Read encounter rate monInfo.encounterRate = encounterFieldObj["encounter_rate"].int_value(); encounterRateFrequencyMaps[field][monInfo.encounterRate]++; // Read wild pokémon list for (auto monJson : encounterFieldObj["mons"].array_items()) { OrderedJson::object monObj = monJson.object_items(); WildPokemon newMon; newMon.minLevel = monObj["min_level"].int_value(); newMon.maxLevel = monObj["max_level"].int_value(); newMon.species = monObj["species"].string_value(); monInfo.wildPokemon.append(newMon); } // If the user supplied too few pokémon for this group then we fill in the rest with default values. for (int i = monInfo.wildPokemon.length(); i < monField.encounterRates.length(); i++) { monInfo.wildPokemon.append(WildPokemon()); } header.wildMons[field] = monInfo; } const QString mapConstant = encounterObj["map"].string_value(); const QString baseLabel = encounterObj["base_label"].string_value(); this->wildMonData[mapConstant].insert({baseLabel, header}); this->encounterGroupLabels.append(baseLabel); } } // For each encounter type, set default encounter rate to most common value. // Iterate over map of encounter type names to frequency maps... for (auto i = encounterRateFrequencyMaps.cbegin(), i_end = encounterRateFrequencyMaps.cend(); i != i_end; i++) { int frequency = 0; int rate = 1; const QMap frequencyMap = i.value(); // Iterate over frequency map (encounter rate to number of occurrences)... for (auto j = frequencyMap.cbegin(), j_end = frequencyMap.cend(); j != j_end; j++) { if (j.value() > frequency) { frequency = j.value(); rate = j.key(); } } setDefaultEncounterRate(i.key(), rate); } this->wildEncountersLoaded = true; return true; } bool Project::readMapGroups() { clearMaps(); this->mapConstantsToMapNames.clear(); this->mapNames.clear(); this->groupNames.clear(); this->groupNameToMapNames.clear(); this->customMapGroupsData = QJsonObject(); this->initTopLevelMapFields(); const QString filepath = projectConfig.getFilePath(ProjectFilePath::json_map_groups); fileWatcher.addPath(root + "/" + filepath); QJsonDocument mapGroupsDoc; QString error; if (!parser.tryParseJsonFile(&mapGroupsDoc, filepath, &error)) { logError(QString("Failed to read map groups from '%1': %2").arg(filepath).arg(error)); return false; } QJsonObject mapGroupsObj = mapGroupsDoc.object(); QJsonArray mapGroupOrder = mapGroupsObj["group_order"].toArray(); const QString dynamicMapName = getDynamicMapName(); const QString dynamicMapConstant = getDynamicMapDefineName(); // Process the map group lists QStringList failedMapNames; for (int groupIndex = 0; groupIndex < mapGroupOrder.size(); groupIndex++) { const QString groupName = ParseUtil::jsonToQString(mapGroupOrder.at(groupIndex)); if (this->groupNames.contains(groupName)) { logWarn(QString("Ignoring repeated map group name '%1'.").arg(groupName)); continue; } const QJsonArray mapNamesJson = mapGroupsObj.take(groupName).toArray(); this->groupNames.append(groupName); // Process the names in this map group for (int j = 0; j < mapNamesJson.size(); j++) { const QString mapName = ParseUtil::jsonToQString(mapNamesJson.at(j)); if (mapName == dynamicMapName) { logWarn(QString("Ignoring map with reserved name '%1'.").arg(mapName)); failedMapNames.append(mapName); continue; } if (this->mapNames.contains(mapName)) { logWarn(QString("Ignoring repeated map name '%1'.").arg(mapName)); failedMapNames.append(mapName); continue; } // Load the map's json file so we can get its ID constant (and two other constants we use for the map list). QJsonDocument mapDoc; if (!readMapJson(mapName, &mapDoc)) { failedMapNames.append(mapName); continue; // Error message has already been logged } // Read and validate the map's ID from its JSON data. const QJsonObject mapObj = mapDoc.object(); const QString mapConstant = ParseUtil::jsonToQString(mapObj["id"]); if (mapConstant.isEmpty()) { logWarn(QString("Map '%1' is missing an \"id\" value and will be ignored.").arg(mapName)); failedMapNames.append(mapName); continue; } if (mapConstant == dynamicMapConstant) { logWarn(QString("Ignoring map with reserved \"id\" value '%1'.").arg(mapName)); failedMapNames.append(mapName); continue; } const QString expectedPrefix = projectConfig.getIdentifier(ProjectIdentifier::define_map_prefix); if (!mapConstant.startsWith(expectedPrefix)) { logWarn(QString("Map '%1' has invalid \"id\" value '%2' and will be ignored. Value must begin with '%3'.").arg(mapName).arg(mapConstant).arg(expectedPrefix)); failedMapNames.append(mapName); continue; } auto it = this->mapConstantsToMapNames.constFind(mapConstant); if (it != this->mapConstantsToMapNames.constEnd()) { logWarn(QString("Map '%1' has the same \"id\" value '%2' as map '%3' and will be ignored.").arg(mapName).arg(it.key()).arg(it.value())); failedMapNames.append(mapName); continue; } // Read layout ID for map list const QString layoutId = ParseUtil::jsonToQString(mapObj["layout"]); if (!this->layoutIds.contains(layoutId)) { // If a map has an unknown layout ID it won't be able to load it at all anyway, so skip it. // Skipping these will let us assume all the map layout IDs are valid, which simplies some handling elsewhere. logWarn(QString("Map '%1' has unknown \"layout\" value '%2' and will be ignored.").arg(mapName).arg(layoutId)); failedMapNames.append(mapName); continue; } // Read MAPSEC name for map list const QString mapSectionName = ParseUtil::jsonToQString(mapObj["region_map_section"]); if (!this->mapSectionIdNames.contains(mapSectionName)) { // An unknown location is OK. Aside from that name not appearing in the dropdowns this shouldn't cause problems. // We'll log a warning, but allow this map to be displayed. logWarn(QString("Map '%1' has unknown \"region_map_section\" value '%2'.").arg(mapName).arg(mapSectionName)); } // Success, create the Map object auto map = new Map; map->setName(mapName); map->setConstantName(mapConstant); map->setLayout(this->mapLayouts.value(layoutId)); map->header()->setLocation(mapSectionName); this->maps.insert(mapName, map); this->mapNames.append(mapName); this->groupNameToMapNames[groupName].append(mapName); this->mapConstantsToMapNames.insert(mapConstant, mapName); } } // Note: Not successfully reading any maps or map groups is ok. We only require at least 1 map layout. if (!failedMapNames.isEmpty()) { // At least 1 map was excluded due to an error. // User should be alerted of this, rather than just silently logging the details. emit mapsExcluded(failedMapNames); } // Save special "Dynamic" constant this->mapConstantsToMapNames.insert(dynamicMapConstant, dynamicMapName); this->mapNames.append(dynamicMapName); // Chuck the "connections_include_order" field, this is only for matching. if (!projectConfig.preserveMatchingOnlyData) { mapGroupsObj.remove("connections_include_order"); } // Preserve any remaining fields for when we save. this->customMapGroupsData = mapGroupsObj; return true; } void Project::addNewMapGroup(const QString &groupName) { if (this->groupNames.contains(groupName)) return; this->groupNames.append(groupName); this->groupNameToMapNames.insert(groupName, QStringList()); this->hasUnsavedDataChanges = true; emit mapGroupAdded(groupName); } QString Project::mapNameToMapGroup(const QString &mapName) const { for (auto it = this->groupNameToMapNames.constBegin(); it != this->groupNameToMapNames.constEnd(); it++) { const QStringList mapNames = it.value(); if (mapNames.contains(mapName)) { return it.key(); } } return QString(); } QString Project::getMapConstant(const QString &mapName, const QString &defaultValue) const { if (mapName == getDynamicMapName()) return getDynamicMapDefineName(); Map* map = this->maps.value(mapName); return map ? map->constantName() : defaultValue; } QString Project::getMapLayoutId(const QString &mapName, const QString &defaultValue) const { Map* map = this->maps.value(mapName); return (map && map->layout()) ? map->layout()->id : defaultValue; } QString Project::getMapLocation(const QString &mapName, const QString &defaultValue) const { Map* map = this->maps.value(mapName); return map ? map->header()->location() : defaultValue; } // When we ask the user to provide a new identifier for something (like a map name or MAPSEC id) // we use this to make sure that it doesn't collide with any known identifiers first. // Porymap knows of many more identifiers than this, but for simplicity we only check the lists that users can add to via Porymap. // In general this only matters to Porymap if the identifier will be added to the group it collides with, // but name collisions are likely undesirable in the project. bool Project::isIdentifierUnique(const QString &identifier) const { if (this->mapNames.contains(identifier)) return false; if (this->mapConstantsToMapNames.contains(identifier)) return false; if (this->groupNames.contains(identifier)) return false; if (this->mapSectionIdNames.contains(identifier)) return false; if (this->tilesetLabelsOrdered.contains(identifier)) return false; if (this->layoutIds.contains(identifier)) return false; for (const auto &layout : this->mapLayouts) { if (layout->name == identifier) { return false; } } if (identifier == getEmptyMapDefineName()) return false; if (this->encounterGroupLabels.contains(identifier)) return false; // Check event IDs for (const auto &mapName : this->loadedMapNames) { for (const auto &event : this->maps.value(mapName)->getEvents()) { QString idName = event->getIdName(); if (!idName.isEmpty() && idName == identifier) return false; } } return true; } // For some arbitrary string, return true if it's both a valid identifier name and not one that's already in-use. bool Project::isValidNewIdentifier(const QString &identifier) const { static const IdentifierValidator validator; return validator.isValid(identifier) && isIdentifierUnique(identifier); } // Assumes 'identifier' is a valid name. If 'identifier' is unique, returns 'identifier'. // Otherwise returns the identifier with a numbered suffix added to make it unique. QString Project::toUniqueIdentifier(const QString &identifier) const { int suffix = 2; QString uniqueIdentifier = identifier; while (!isIdentifierUnique(uniqueIdentifier)) { uniqueIdentifier = QString("%1_%2").arg(identifier).arg(suffix++); } return uniqueIdentifier; } void Project::initNewMapSettings() { this->newMapSettings.name = QString(); this->newMapSettings.group = this->groupNames.value(0); this->newMapSettings.canFlyTo = false; this->newMapSettings.layout.folderName = this->newMapSettings.name; this->newMapSettings.layout.name = QString(); this->newMapSettings.layout.id = Layout::layoutConstantFromName(this->newMapSettings.name); this->newMapSettings.layout.width = getDefaultMapDimension(); this->newMapSettings.layout.height = getDefaultMapDimension(); this->newMapSettings.layout.borderWidth = DEFAULT_BORDER_WIDTH; this->newMapSettings.layout.borderHeight = DEFAULT_BORDER_HEIGHT; this->newMapSettings.layout.primaryTilesetLabel = getDefaultPrimaryTilesetLabel(); this->newMapSettings.layout.secondaryTilesetLabel = getDefaultSecondaryTilesetLabel(); this->newMapSettings.header.setSong(this->defaultSong); this->newMapSettings.header.setLocation(this->mapSectionIdNames.value(0, "0")); this->newMapSettings.header.setRequiresFlash(false); this->newMapSettings.header.setWeather(this->weatherNames.value(0, "0")); this->newMapSettings.header.setType(this->mapTypes.value(0, "0")); this->newMapSettings.header.setBattleScene(this->mapBattleScenes.value(0, "0")); this->newMapSettings.header.setShowsLocationName(true); this->newMapSettings.header.setAllowsRunning(false); this->newMapSettings.header.setAllowsBiking(false); this->newMapSettings.header.setAllowsEscaping(false); this->newMapSettings.header.setFloorNumber(0); } void Project::initNewLayoutSettings() { this->newLayoutSettings.name = QString(); this->newLayoutSettings.id = Layout::layoutConstantFromName(this->newLayoutSettings.name); this->newLayoutSettings.width = getDefaultMapDimension(); this->newLayoutSettings.height = getDefaultMapDimension(); this->newLayoutSettings.borderWidth = DEFAULT_BORDER_WIDTH; this->newLayoutSettings.borderHeight = DEFAULT_BORDER_HEIGHT; this->newLayoutSettings.primaryTilesetLabel = getDefaultPrimaryTilesetLabel(); this->newLayoutSettings.secondaryTilesetLabel = getDefaultSecondaryTilesetLabel(); } QString Project::getDefaultPrimaryTilesetLabel() const { QString defaultLabel = projectConfig.defaultPrimaryTileset; if (!this->primaryTilesetLabels.contains(defaultLabel)) { QString firstLabel = this->primaryTilesetLabels.first(); logWarn(QString("Unable to find default primary tileset '%1', using '%2' instead.").arg(defaultLabel).arg(firstLabel)); defaultLabel = firstLabel; } return defaultLabel; } QString Project::getDefaultSecondaryTilesetLabel() const { QString defaultLabel = projectConfig.defaultSecondaryTileset; if (!this->secondaryTilesetLabels.contains(defaultLabel)) { QString firstLabel = this->secondaryTilesetLabels.first(); logWarn(QString("Unable to find default secondary tileset '%1', using '%2' instead.").arg(defaultLabel).arg(firstLabel)); defaultLabel = firstLabel; } return defaultLabel; } void Project::appendTilesetLabel(const QString &label, const QString &isSecondaryStr) { bool ok; bool isSecondary = ParseUtil::gameStringToBool(isSecondaryStr, &ok); if (!ok) { logError(QString("Unable to convert value '%1' of isSecondary to bool for tileset %2.").arg(isSecondaryStr).arg(label)); return; } QStringList * list = isSecondary ? &this->secondaryTilesetLabels : &this->primaryTilesetLabels; list->append(label); this->tilesetLabelsOrdered.append(label); } bool Project::readTilesetLabels() { this->primaryTilesetLabels.clear(); this->secondaryTilesetLabels.clear(); this->tilesetLabelsOrdered.clear(); QString filename = projectConfig.getFilePath(ProjectFilePath::tilesets_headers); QFileInfo fileInfo(this->root + "/" + filename); if (!fileInfo.exists() || !fileInfo.isFile()) { // If the tileset headers file is missing, the user may still have the old assembly format. this->usingAsmTilesets = true; QString asm_filename = projectConfig.getFilePath(ProjectFilePath::tilesets_headers_asm); QString text = parser.readTextFile(this->root + "/" + asm_filename); if (text.isEmpty()) { logError(QString("Failed to read tileset labels from '%1' or '%2'.").arg(filename).arg(asm_filename)); return false; } static const QRegularExpression re("(?