diff --git a/src/openrct2/CommandLineSprite.cpp b/src/openrct2/CommandLineSprite.cpp deleted file mode 100644 index 73a105a034..0000000000 --- a/src/openrct2/CommandLineSprite.cpp +++ /dev/null @@ -1,677 +0,0 @@ -/***************************************************************************** - * Copyright (c) 2014-2025 OpenRCT2 developers - * - * For a complete list of all authors, please refer to contributors.md - * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 - * - * OpenRCT2 is licensed under the GNU General Public License version 3. - *****************************************************************************/ - -#include "CommandLineSprite.h" - -#include "Context.h" -#include "Diagnostic.h" -#include "OpenRCT2.h" -#include "core/FileStream.h" -#include "core/Imaging.h" -#include "core/Json.hpp" -#include "core/Path.hpp" -#include "core/String.hpp" -#include "drawing/Drawing.h" -#include "drawing/ImageImporter.h" -#include "object/ObjectFactory.h" -#include "object/ObjectLimits.h" -#include "object/ObjectManager.h" -#include "object/ObjectRepository.h" - -#include -#include -#include - -// TODO: Remove when C++20 is enabled and std::format can be used -#include -#include - -namespace OpenRCT2 -{ - using namespace OpenRCT2::Drawing; - - static int32_t CommandLineForSpriteExportObject(const char** argv, int32_t argc); - static int32_t CommandLineForSpriteCombine(const char** argv, int32_t argc); - - class SpriteFile - { - public: - RCTG1Header Header{}; - std::vector Entries; - std::vector Data; - void AddImage(ImageImporter::ImportResult& image); - bool Save(const utf8* path); - static std::optional Open(const utf8* path); - - private: - class ScopedRelativeSpriteFile - { - private: - SpriteFile& _SpriteFile; - bool _WasAbsolute; - - public: - ScopedRelativeSpriteFile(SpriteFile& sFile) - : _SpriteFile(sFile) - , _WasAbsolute(sFile.isAbsolute) - { - if (_WasAbsolute) - _SpriteFile.MakeEntriesRelative(); - } - - ~ScopedRelativeSpriteFile() - { - if (_WasAbsolute) - _SpriteFile.MakeEntriesAbsolute(); - } - }; - bool isAbsolute = false; - void MakeEntriesAbsolute(); - void MakeEntriesRelative(); - }; - - void SpriteFile::MakeEntriesAbsolute() - { - if (!isAbsolute) - { - for (auto& entry : Entries) - entry.offset += reinterpret_cast(Data.data()); - } - isAbsolute = true; - } - - void SpriteFile::MakeEntriesRelative() - { - if (isAbsolute) - { - for (auto& entry : Entries) - entry.offset -= reinterpret_cast(Data.data()); - } - isAbsolute = false; - } - - void SpriteFile::AddImage(ImageImporter::ImportResult& image) - { - Header.num_entries++; - // New image will have its data inserted after previous image - uint8_t* newElementOffset = reinterpret_cast(static_cast(Header.total_size)); - Header.total_size += static_cast(image.Buffer.size()); - Entries.reserve(Header.num_entries); - - { - ScopedRelativeSpriteFile scopedRelative(*this); - Data.reserve(Header.total_size); - Entries.push_back(image.Element); - Entries.back().offset = newElementOffset; - const auto& buffer = image.Buffer; - std::copy(buffer.begin(), buffer.end(), std::back_inserter(Data)); - } - } - - std::optional SpriteFile::Open(const utf8* path) - { - try - { - FileStream stream(path, FileMode::open); - - SpriteFile spriteFile; - stream.Read(&spriteFile.Header, sizeof(RCTG1Header)); - - if (spriteFile.Header.num_entries > 0) - { - spriteFile.Entries.reserve(spriteFile.Header.num_entries); - - for (uint32_t i = 0; i < spriteFile.Header.num_entries; ++i) - { - RCTG1Element entry32bit{}; - stream.Read(&entry32bit, sizeof(entry32bit)); - G1Element entry{}; - - entry.offset = reinterpret_cast(static_cast(entry32bit.offset)); - entry.width = entry32bit.width; - entry.height = entry32bit.height; - entry.x_offset = entry32bit.x_offset; - entry.y_offset = entry32bit.y_offset; - entry.flags = entry32bit.flags; - entry.zoomed_offset = entry32bit.zoomed_offset; - spriteFile.Entries.push_back(std::move(entry)); - } - spriteFile.Data.resize(spriteFile.Header.total_size); - stream.Read(spriteFile.Data.data(), spriteFile.Header.total_size); - } - spriteFile.MakeEntriesAbsolute(); - return spriteFile; - } - catch (IOException&) - { - return std::nullopt; - } - } - - bool SpriteFile::Save(const utf8* path) - { - try - { - FileStream stream(path, FileMode::write); - stream.Write(&Header, sizeof(RCTG1Header)); - - if (Header.num_entries > 0) - { - ScopedRelativeSpriteFile scopedRelative(*this); - - for (const auto& entry : Entries) - { - RCTG1Element entry32bit{}; - - entry32bit.offset = static_cast(reinterpret_cast(const_cast(entry.offset))); - entry32bit.width = entry.width; - entry32bit.height = entry.height; - entry32bit.x_offset = entry.x_offset; - entry32bit.y_offset = entry.y_offset; - entry32bit.flags = entry.flags; - entry32bit.zoomed_offset = entry.zoomed_offset; - - stream.Write(&entry32bit, sizeof(entry32bit)); - } - stream.Write(Data.data(), Header.total_size); - } - return true; - } - catch (IOException&) - { - return false; - } - } - - static bool SpriteImageExport(const G1Element& spriteElement, u8string_view outPath) - { - const size_t pixelBufferSize = static_cast(spriteElement.width) * spriteElement.height; - auto pixelBuffer = std::make_unique(pixelBufferSize); - auto pixels = pixelBuffer.get(); - - RenderTarget rt; - rt.bits = pixels; - rt.x = 0; - rt.y = 0; - rt.width = spriteElement.width; - rt.height = spriteElement.height; - rt.pitch = 0; - rt.zoom_level = ZoomLevel{ 0 }; - - DrawSpriteArgs args( - ImageId(), PaletteMap::GetDefault(), spriteElement, 0, 0, spriteElement.width, spriteElement.height, pixels); - GfxSpriteToBuffer(rt, args); - - auto const pixels8 = rt.bits; - auto const pixelsLen = rt.LineStride() * rt.WorldHeight(); - try - { - Image image; - image.Width = rt.width; - image.Height = rt.height; - image.Depth = 8; - image.Stride = rt.LineStride(); - image.Palette = StandardPalette; - image.Pixels = std::vector(pixels8, pixels8 + pixelsLen); - Imaging::WriteToFile(outPath, image, ImageFormat::png); - return true; - } - catch (const std::exception& e) - { - fprintf(stderr, "Unable to write png: %s", e.what()); - return false; - } - } - - static std::optional SpriteImageImport(u8string_view path, ImageImportMeta meta) - { - try - { - auto format = ImageFormat::png32; - if (meta.palette == Palette::KeepIndices) - { - format = ImageFormat::png; - } - - ImageImporter importer; - auto image = Imaging::ReadFromFile(path, format); - - return importer.Import(image, meta); - } - catch (const std::exception& e) - { - fprintf(stderr, "%s\n", e.what()); - return std::nullopt; - } - } - - // TODO: Remove when C++20 is enabled and std::format can be used - static std::string PopStr(std::ostringstream& oss) - { - auto str = oss.str(); - oss.str(""); - oss.clear(); - return str; - } - - int32_t CommandLineForSprite(const char** argv, int32_t argc) - { - gOpenRCT2Headless = true; - if (argc == 0) - return -1; - - if (String::iequals(argv[0], "details")) - { - if (argc < 2) - { - fprintf(stdout, "usage: sprite details [idx]\n"); - return -1; - } - - if (argc == 2) - { - const utf8* spriteFilePath = argv[1]; - auto spriteFile = SpriteFile::Open(spriteFilePath); - if (!spriteFile.has_value()) - { - fprintf(stderr, "Unable to open input sprite file.\n"); - return -1; - } - - printf("sprites: %u\n", spriteFile->Header.num_entries); - printf("data size: %u\n", spriteFile->Header.total_size); - return 1; - } - - const utf8* spriteFilePath = argv[1]; - int32_t spriteIndex = atoi(argv[2]); - auto spriteFile = SpriteFile::Open(spriteFilePath); - if (!spriteFile.has_value()) - { - fprintf(stderr, "Unable to open input sprite file.\n"); - return -1; - } - - if (spriteIndex < 0 || spriteIndex >= static_cast(spriteFile->Header.num_entries)) - { - fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex); - return -1; - } - - G1Element* g1 = &spriteFile->Entries[spriteIndex]; - printf("width: %d\n", g1->width); - printf("height: %d\n", g1->height); - printf("x offset: %d\n", g1->x_offset); - printf("y offset: %d\n", g1->y_offset); - printf("data offset: %p\n", g1->offset); - return 1; - } - - if (String::iequals(argv[0], "export")) - { - if (argc < 4) - { - fprintf(stdout, "usage: sprite export \n"); - return -1; - } - - const utf8* spriteFilePath = argv[1]; - int32_t spriteIndex = atoi(argv[2]); - const utf8* outputPath = argv[3]; - auto spriteFile = SpriteFile::Open(spriteFilePath); - if (!spriteFile.has_value()) - { - fprintf(stderr, "Unable to open input sprite file.\n"); - return -1; - } - - if (spriteIndex < 0 || spriteIndex >= static_cast(spriteFile->Header.num_entries)) - { - fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex); - return -1; - } - - const auto& spriteHeader = spriteFile->Entries[spriteIndex]; - if (!SpriteImageExport(spriteHeader, outputPath)) - { - fprintf(stderr, "Could not export\n"); - return -1; - } - fprintf(stdout, "{ \"x\": %d, \"y\": %d }\n", spriteHeader.x_offset, spriteHeader.y_offset); - return 1; - } - - if (String::iequals(argv[0], "exportall")) - { - if (argc < 3) - { - fprintf(stdout, "usage: sprite exportall \n"); - return -1; - } - - const utf8* spriteFilePath = argv[1]; - const utf8* outputPath = argv[2]; - - auto spriteFile = SpriteFile::Open(spriteFilePath); - if (!spriteFile.has_value()) - { - fprintf(stderr, "Unable to open input sprite file.\n"); - return -1; - } - - if (!Path::CreateDirectory(outputPath)) - { - fprintf(stderr, "Unable to create directory.\n"); - return -1; - } - - const uint32_t maxIndex = spriteFile->Header.num_entries; - const int32_t numbers = static_cast(std::floor(std::log10(maxIndex) + 1)); - - std::ostringstream oss; // TODO: Remove when C++20 is enabled and std::format can be used - for (uint32_t spriteIndex = 0; spriteIndex < maxIndex; spriteIndex++) - { - // Status indicator - printf("\r%u / %u, %u%%", spriteIndex + 1, maxIndex, ((spriteIndex + 1) * 100) / maxIndex); - - oss << std::setw(numbers) << std::setfill('0') << spriteIndex << ".png"; - - const auto& spriteHeader = spriteFile->Entries[spriteIndex]; - if (!SpriteImageExport(spriteHeader, Path::Combine(outputPath, PopStr(oss)))) - { - fprintf(stderr, "Could not export\n"); - return -1; - } - } - return 1; - } - - if (String::iequals(argv[0], "exportobject")) - { - return CommandLineForSpriteExportObject(argv, argc); - } - - if (String::iequals(argv[0], "create")) - { - if (argc < 2) - { - fprintf(stderr, "usage: sprite create \n"); - return -1; - } - - const utf8* spriteFilePath = argv[1]; - - SpriteFile spriteFile; - spriteFile.Save(spriteFilePath); - return 1; - } - - if (String::iequals(argv[0], "append")) - { - if (argc != 3 && argc != 5) - { - fprintf(stderr, "usage: sprite append [ ]\n"); - return -1; - } - - const utf8* spriteFilePath = argv[1]; - const utf8* imagePath = argv[2]; - int16_t xOffset = 0; - int16_t yOffset = 0; - - if (argc == 5) - { - char* endptr; - - xOffset = strtol(argv[3], &endptr, 0); - if (*endptr != 0) - { - fprintf(stderr, "X offset must be an integer\n"); - return -1; - } - - yOffset = strtol(argv[4], &endptr, 0); - if (*endptr != 0) - { - fprintf(stderr, "Y offset must be an integer\n"); - return -1; - } - } - - constexpr uint8_t importFlags = EnumToFlag(ImportFlags::RLE); - ImageImportMeta meta = { { xOffset, yOffset }, Palette::OpenRCT2, importFlags, gSpriteMode }; - auto importResult = SpriteImageImport(imagePath, meta); - if (!importResult.has_value()) - return -1; - - auto spriteFile = SpriteFile::Open(spriteFilePath); - if (!spriteFile.has_value()) - { - fprintf(stderr, "Unable to open input sprite file.\n"); - return -1; - } - - spriteFile->AddImage(importResult.value()); - - if (!spriteFile->Save(spriteFilePath)) - return -1; - - return 1; - } - - if (String::iequals(argv[0], "build")) - { - if (argc < 3) - { - fprintf(stdout, "usage: sprite build [silent]\n"); - return -1; - } - - const utf8* spriteFilePath = argv[1]; - const utf8* spriteDescriptionPath = argv[2]; - const auto directoryPath = Path::GetDirectory(spriteDescriptionPath); - - json_t jsonSprites = Json::ReadFromFile(spriteDescriptionPath); - if (jsonSprites.is_null()) - { - fprintf(stderr, "Unable to read sprite description file: %s\n", spriteDescriptionPath); - return -1; - } - - if (jsonSprites.is_object() && !jsonSprites["images"].is_null()) - jsonSprites = jsonSprites["images"]; - - if (!jsonSprites.is_array()) - { - fprintf(stderr, "Error: expected array\n"); - return -1; - } - - bool silent = (argc >= 4 && strcmp(argv[3], "silent") == 0); - - // keep sprite file entirely in memory until ready to write out a complete, - // correct file - SpriteFile spriteFile; - spriteFile.Header.num_entries = 0; - spriteFile.Header.total_size = 0; - - fprintf(stdout, "Building: %s\n", spriteFilePath); - - json_t sprite_description; - - uint32_t numSuccessful = 0; - - // Note: jsonSprite is deliberately left non-const: json_t behaviour changes when const - for (auto& [jsonKey, jsonSprite] : jsonSprites.items()) - { - if (!jsonSprite.is_object()) - { - fprintf(stderr, "Error: expected object for sprite %s\n", jsonKey.c_str()); - return -1; - } - - json_t path = jsonSprite["path"]; - if (!path.is_string()) - { - fprintf(stderr, "Error: no path provided for sprite %s\n", jsonKey.c_str()); - return -1; - } - std::string strPath = Json::GetString(path); - - auto meta = createImageImportMetaFromJson(jsonSprite); - meta.importMode = gSpriteMode; - - auto imagePath = Path::GetAbsolute(Path::Combine(directoryPath, strPath)); - - auto importResult = SpriteImageImport(imagePath, meta); - if (importResult == std::nullopt) - { - fprintf(stderr, "Could not import image file: %s\nCanceling\n", imagePath.c_str()); - return -1; - } - - spriteFile.AddImage(importResult.value()); - - if (!silent) - fprintf(stdout, "Added: %s\n", imagePath.c_str()); - - numSuccessful++; - } - - if (!spriteFile.Save(spriteFilePath)) - { - LOG_ERROR("Could not save sprite file, cancelling."); - return -1; - } - - fprintf(stdout, "Finished building graphics repository with %u images\n", numSuccessful); - - if (numSuccessful > 0) - { - printf("Replace the object's images table entries with this:\n"); - const auto spriteFileName = Path::GetFileName(spriteFilePath); - fprintf(stdout, "\"$LGX:%s[0..%u]\"\n", spriteFileName.c_str(), numSuccessful - 1); - } - - return 1; - } - - if (String::iequals(argv[0], "combine")) - { - return CommandLineForSpriteCombine(argv, argc); - } - - fprintf(stderr, "Unknown sprite command.\n"); - return 1; - } - - static int32_t CommandLineForSpriteExportObject(const char** argv, int32_t argc) - { - if (argc < 3) - { - fprintf(stdout, "usage: sprite exportobject \n"); - return -1; - } - - const char* objectPath = argv[1]; - const utf8* outputPath = argv[2]; - auto context = CreateContext(); - context->Initialise(); - - std::unique_ptr metaObject = OpenRCT2::ObjectFactory::CreateObjectFromFile(objectPath, true); - if (metaObject == nullptr) - { - fprintf(stderr, "Could not load the object.\n"); - return -1; - } - - if (!Path::CreateDirectory(outputPath)) - { - fprintf(stderr, "Unable to create output directory.\n"); - return -1; - } - - const auto* imageTableStart = metaObject->GetImageTable().GetImages(); - const uint32_t maxIndex = metaObject->GetNumImages(); - const int32_t numbers = static_cast(std::floor(std::log10(maxIndex) + 1)); - - std::ostringstream oss; // TODO: Remove when C++20 is enabled and std::format can be used - for (uint32_t spriteIndex = 0; spriteIndex < maxIndex; spriteIndex++) - { - oss << std::setw(numbers) << std::setfill('0') << spriteIndex << ".png"; - auto path = Path::Combine(outputPath, PopStr(oss)); - - const auto& g1 = imageTableStart[spriteIndex]; - if (g1.width == 0 || g1.height == 0) - { - fprintf(stdout, "\"\""); - } - else - { - if (!SpriteImageExport(g1, path)) - { - fprintf(stderr, "Could not export\n"); - return -1; - } - - path = fs::u8path(path).generic_u8string(); - fprintf(stdout, "{ \"path\": \"%s\", \"x\": %d, \"y\": %d }", path.c_str(), g1.x_offset, g1.y_offset); - } - - fprintf(stdout, (spriteIndex + 1 != maxIndex) ? ",\n" : "\n"); - } - return 1; - } - - static int32_t CommandLineForSpriteCombine(const char** argv, int32_t argc) - { - if (argc < 4) - { - fprintf(stdout, "usage: sprite combine \n"); - return -1; - } - - const utf8* indexFile = argv[1]; - const utf8* dataFile = argv[2]; - const utf8* outputPath = argv[3]; - - auto fileHeader = FileStream(indexFile, FileMode::open); - auto fileData = FileStream(dataFile, FileMode::open); - auto fileHeaderSize = fileHeader.GetLength(); - auto fileDataSize = fileData.GetLength(); - - uint32_t numEntries = fileHeaderSize / sizeof(RCTG1Element); - - RCTG1Header header = {}; - header.num_entries = numEntries; - header.total_size = fileDataSize; - FileStream outputStream(outputPath, FileMode::write); - - outputStream.Write(&header, sizeof(RCTG1Header)); - auto g1Elements32 = std::make_unique(numEntries); - fileHeader.Read(g1Elements32.get(), numEntries * sizeof(RCTG1Element)); - for (uint32_t i = 0; i < numEntries; i++) - { - // RCT1 used zoomed offsets that counted from the beginning of the file, rather than from the current sprite. - if (g1Elements32[i].flags & G1_FLAG_HAS_ZOOM_SPRITE) - { - g1Elements32[i].zoomed_offset = i - g1Elements32[i].zoomed_offset; - } - - outputStream.Write(&g1Elements32[i], sizeof(RCTG1Element)); - } - - std::vector data; - data.resize(fileDataSize); - fileData.Read(data.data(), fileDataSize); - outputStream.Write(data.data(), fileDataSize); - - return 1; - } -} // namespace OpenRCT2 diff --git a/src/openrct2/CommandLineSprite.h b/src/openrct2/CommandLineSprite.h deleted file mode 100644 index 76976abd73..0000000000 --- a/src/openrct2/CommandLineSprite.h +++ /dev/null @@ -1,18 +0,0 @@ -/***************************************************************************** - * Copyright (c) 2014-2025 OpenRCT2 developers - * - * For a complete list of all authors, please refer to contributors.md - * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 - * - * OpenRCT2 is licensed under the GNU General Public License version 3. - *****************************************************************************/ - -#pragma once - -#include "drawing/ImageImporter.h" - -namespace OpenRCT2 -{ - int32_t CommandLineForSprite(const char** argv, int32_t argc); - extern Drawing::ImportMode gSpriteMode; -} // namespace OpenRCT2 diff --git a/src/openrct2/command_line/CommandLine.hpp b/src/openrct2/command_line/CommandLine.hpp index 4557bcd0a0..9d5dcdfd02 100644 --- a/src/openrct2/command_line/CommandLine.hpp +++ b/src/openrct2/command_line/CommandLine.hpp @@ -112,7 +112,10 @@ namespace OpenRCT2 extern const CommandLineCommand kRootCommands[]; extern const CommandLineCommand kConvertCommands[]; extern const CommandLineCommand kScreenshotCommands[]; - extern const CommandLineCommand kSpriteCommands[]; + namespace Sprite + { + extern const CommandLineCommand kSpriteCommands[]; + } extern const CommandLineCommand kSimulateCommands[]; extern const CommandLineCommand kParkInfoCommands[]; diff --git a/src/openrct2/command_line/RootCommands.cpp b/src/openrct2/command_line/RootCommands.cpp index abd9a4b844..66e26735e8 100644 --- a/src/openrct2/command_line/RootCommands.cpp +++ b/src/openrct2/command_line/RootCommands.cpp @@ -143,7 +143,7 @@ namespace OpenRCT2 // Sub-commands DefineSubCommand("convert", CommandLine::kConvertCommands ), DefineSubCommand("screenshot", CommandLine::kScreenshotCommands ), - DefineSubCommand("sprite", CommandLine::kSpriteCommands ), + DefineSubCommand("sprite", CommandLine::Sprite::kSpriteCommands ), DefineSubCommand("simulate", CommandLine::kSimulateCommands ), DefineSubCommand("parkinfo", CommandLine::kParkInfoCommands ), kCommandTableEnd diff --git a/src/openrct2/command_line/SpriteCommands.cpp b/src/openrct2/command_line/SpriteCommands.cpp deleted file mode 100644 index 4c0717f05f..0000000000 --- a/src/openrct2/command_line/SpriteCommands.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/***************************************************************************** - * Copyright (c) 2014-2025 OpenRCT2 developers - * - * For a complete list of all authors, please refer to contributors.md - * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 - * - * OpenRCT2 is licensed under the GNU General Public License version 3. - *****************************************************************************/ - -#include "../CommandLineSprite.h" -#include "../core/Memory.hpp" -#include "../core/String.hpp" -#include "CommandLine.hpp" - -#define SZ_DEFAULT "default" -#define SZ_CLOSEST "closest" -#define SZ_DITHERING "dithering" - -namespace OpenRCT2 -{ - using ImportMode = Drawing::ImportMode; - - ImportMode gSpriteMode = ImportMode::Default; - - static const char* _mode; - - // clang-format off - static constexpr CommandLineOptionDefinition kSpriteOptions[] - { - { CMDLINE_TYPE_STRING, &_mode, 'm', "mode", "the type of sprite conversion <" SZ_DEFAULT "|" SZ_CLOSEST "|" SZ_DITHERING ">" }, - kOptionTableEnd - }; - - static exitcode_t HandleSprite(CommandLineArgEnumerator *argEnumerator); - - const CommandLineCommand CommandLine::kSpriteCommands[] - { - // Main commands - DefineCommand("append", " [x_offset y_offset]", kSpriteOptions, HandleSprite), - DefineCommand("build", " [silent]", kSpriteOptions, HandleSprite), - DefineCommand("combine", " ", kSpriteOptions, HandleSprite), - DefineCommand("create", "", kSpriteOptions, HandleSprite), - DefineCommand("details", " [idx]", kSpriteOptions, HandleSprite), - DefineCommand("export", " ", kSpriteOptions, HandleSprite), - DefineCommand("exportall", " ", kSpriteOptions, HandleSprite), - DefineCommand("exportobject", " ", kSpriteOptions, HandleSprite), - - kCommandTableEnd - }; - // clang-format on - - static exitcode_t HandleSprite(CommandLineArgEnumerator* argEnumerator) - { - if (String::iequals(_mode, SZ_CLOSEST)) - gSpriteMode = ImportMode::Closest; - else if (String::iequals(_mode, SZ_DITHERING)) - gSpriteMode = ImportMode::Dithering; - Memory::Free(_mode); - - const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex() - 1; - int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex() + 1; - int32_t result = CommandLineForSprite(argv, argc); - if (result < 0) - { - return EXITCODE_FAIL; - } - return EXITCODE_OK; - } -} // namespace OpenRCT2 diff --git a/src/openrct2/command_line/sprite/SpriteAppend.cpp b/src/openrct2/command_line/sprite/SpriteAppend.cpp new file mode 100644 index 0000000000..a3a581da52 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteAppend.cpp @@ -0,0 +1,73 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include + +using namespace OpenRCT2::Drawing; + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t append(const char** argv, int32_t argc, ImportMode spriteMode) + { + if (argc != 3 && argc != 5) + { + fprintf(stderr, "usage: sprite append [ ]\n"); + return -1; + } + + const utf8* spriteFilePath = argv[1]; + const utf8* imagePath = argv[2]; + int16_t xOffset = 0; + int16_t yOffset = 0; + + if (argc == 5) + { + char* endptr; + + xOffset = strtol(argv[3], &endptr, 0); + if (*endptr != 0) + { + fprintf(stderr, "X offset must be an integer\n"); + return -1; + } + + yOffset = strtol(argv[4], &endptr, 0); + if (*endptr != 0) + { + fprintf(stderr, "Y offset must be an integer\n"); + return -1; + } + } + + constexpr uint8_t importFlags = EnumToFlag(ImportFlags::RLE); + ImageImportMeta meta = { { xOffset, yOffset }, Palette::OpenRCT2, importFlags, spriteMode }; + auto importResult = SpriteImageImport(imagePath, meta); + if (!importResult.has_value()) + return -1; + + auto spriteFile = SpriteFile::Open(spriteFilePath); + if (!spriteFile.has_value()) + { + fprintf(stderr, "Unable to open input sprite file.\n"); + return -1; + } + + spriteFile->AddImage(importResult.value()); + + if (!spriteFile->Save(spriteFilePath)) + return -1; + + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteBuild.cpp b/src/openrct2/command_line/sprite/SpriteBuild.cpp new file mode 100644 index 0000000000..d3bf7428ea --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteBuild.cpp @@ -0,0 +1,119 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../core/Json.hpp" +#include "../../core/Path.hpp" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include + +using namespace OpenRCT2::Drawing; + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t build(const char** argv, int32_t argc, ImportMode spriteMode) + { + if (argc < 3) + { + fprintf(stdout, "usage: sprite build [silent]\n"); + return -1; + } + + const utf8* spriteFilePath = argv[1]; + const utf8* spriteDescriptionPath = argv[2]; + const auto directoryPath = Path::GetDirectory(spriteDescriptionPath); + + json_t jsonSprites = Json::ReadFromFile(spriteDescriptionPath); + if (jsonSprites.is_null()) + { + fprintf(stderr, "Unable to read sprite description file: %s\n", spriteDescriptionPath); + return -1; + } + + if (jsonSprites.is_object() && !jsonSprites["images"].is_null()) + jsonSprites = jsonSprites["images"]; + + if (!jsonSprites.is_array()) + { + fprintf(stderr, "Error: expected array\n"); + return -1; + } + + bool silent = (argc >= 4 && strcmp(argv[3], "silent") == 0); + + // keep sprite file entirely in memory until ready to write out a complete, + // correct file + SpriteFile spriteFile; + spriteFile.Header.num_entries = 0; + spriteFile.Header.total_size = 0; + + fprintf(stdout, "Building: %s\n", spriteFilePath); + + json_t sprite_description; + + uint32_t numSuccessful = 0; + + // Note: jsonSprite is deliberately left non-const: json_t behaviour changes when const + for (auto& [jsonKey, jsonSprite] : jsonSprites.items()) + { + if (!jsonSprite.is_object()) + { + fprintf(stderr, "Error: expected object for sprite %s\n", jsonKey.c_str()); + return -1; + } + + json_t path = jsonSprite["path"]; + if (!path.is_string()) + { + fprintf(stderr, "Error: no path provided for sprite %s\n", jsonKey.c_str()); + return -1; + } + std::string strPath = Json::GetString(path); + + auto meta = createImageImportMetaFromJson(jsonSprite); + meta.importMode = spriteMode; + + auto imagePath = Path::GetAbsolute(Path::Combine(directoryPath, strPath)); + + auto importResult = SpriteImageImport(imagePath, meta); + if (importResult == std::nullopt) + { + fprintf(stderr, "Could not import image file: %s\nCanceling\n", imagePath.c_str()); + return -1; + } + + spriteFile.AddImage(importResult.value()); + + if (!silent) + fprintf(stdout, "Added: %s\n", imagePath.c_str()); + + numSuccessful++; + } + + if (!spriteFile.Save(spriteFilePath)) + { + fprintf(stderr, "Could not save sprite file, cancelling."); + return -1; + } + + fprintf(stdout, "Finished building graphics repository with %u images\n", numSuccessful); + + if (numSuccessful > 0) + { + printf("Replace the object's images table entries with this:\n"); + const auto spriteFileName = Path::GetFileName(spriteFilePath); + fprintf(stdout, "\"$LGX:%s[0..%u]\"\n", spriteFileName.c_str(), numSuccessful - 1); + } + + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteCombine.cpp b/src/openrct2/command_line/sprite/SpriteCombine.cpp new file mode 100644 index 0000000000..6b51873220 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteCombine.cpp @@ -0,0 +1,63 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" + +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t combine(const char** argv, int32_t argc) + { + if (argc < 4) + { + fprintf(stdout, "usage: sprite combine \n"); + return -1; + } + + const utf8* indexFile = argv[1]; + const utf8* dataFile = argv[2]; + const utf8* outputPath = argv[3]; + + auto fileHeader = FileStream(indexFile, FileMode::open); + auto fileData = FileStream(dataFile, FileMode::open); + auto fileHeaderSize = fileHeader.GetLength(); + auto fileDataSize = fileData.GetLength(); + + uint32_t numEntries = fileHeaderSize / sizeof(RCTG1Element); + + RCTG1Header header = {}; + header.num_entries = numEntries; + header.total_size = fileDataSize; + FileStream outputStream(outputPath, FileMode::write); + + outputStream.Write(&header, sizeof(RCTG1Header)); + auto g1Elements32 = std::make_unique(numEntries); + fileHeader.Read(g1Elements32.get(), numEntries * sizeof(RCTG1Element)); + for (uint32_t i = 0; i < numEntries; i++) + { + // RCT1 used zoomed offsets that counted from the beginning of the file, rather than from the current sprite. + if (g1Elements32[i].flags & G1_FLAG_HAS_ZOOM_SPRITE) + { + g1Elements32[i].zoomed_offset = i - g1Elements32[i].zoomed_offset; + } + + outputStream.Write(&g1Elements32[i], sizeof(RCTG1Element)); + } + + std::vector data; + data.resize(fileDataSize); + fileData.Read(data.data(), fileDataSize); + outputStream.Write(data.data(), fileDataSize); + + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteCommands.cpp b/src/openrct2/command_line/sprite/SpriteCommands.cpp new file mode 100644 index 0000000000..018261b725 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteCommands.cpp @@ -0,0 +1,195 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "SpriteCommands.h" + +#include "../../Context.h" +#include "../../OpenRCT2.h" +#include "../../core/Memory.hpp" +#include "../../core/String.hpp" +#include "../../object/ObjectFactory.h" +#include "../CommandLine.hpp" + +#include +#include + +// TODO: Remove when C++20 is enabled and std::format can be used +#include +#include + +// FIXME: replace with a constexpr that will also work for string interpolation. +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define SZ_DEFAULT "default" +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define SZ_CLOSEST "closest" +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define SZ_DITHERING "dithering" + +namespace OpenRCT2::CommandLine::Sprite +{ + using namespace OpenRCT2::Drawing; + + static const char* _mode; + + // clang-format off + static constexpr CommandLineOptionDefinition kSpriteOptions[] + { + { CMDLINE_TYPE_STRING, &_mode, 'm', "mode", "the type of sprite conversion <" SZ_DEFAULT "|" SZ_CLOSEST "|" SZ_DITHERING ">" }, + kOptionTableEnd + }; + + static exitcode_t HandleSprite(CommandLineArgEnumerator *argEnumerator); + + const CommandLineCommand kSpriteCommands[] + { + // Main commands + DefineCommand("append", " [x_offset y_offset]", kSpriteOptions, HandleSprite), + DefineCommand("build", " [silent]", kSpriteOptions, HandleSprite), + DefineCommand("combine", " ", kSpriteOptions, HandleSprite), + DefineCommand("create", "", kSpriteOptions, HandleSprite), + DefineCommand("details", " [idx]", kSpriteOptions, HandleSprite), + DefineCommand("export", " ", kSpriteOptions, HandleSprite), + DefineCommand("exportall", " ", kSpriteOptions, HandleSprite), + DefineCommand("exportobject", " ", kSpriteOptions, HandleSprite), + + kCommandTableEnd + }; + // clang-format on + + static exitcode_t HandleSprite(CommandLineArgEnumerator* argEnumerator) + { + auto spriteMode = ImportMode::Default; + if (String::iequals(_mode, SZ_CLOSEST)) + spriteMode = ImportMode::Closest; + else if (String::iequals(_mode, SZ_DITHERING)) + spriteMode = ImportMode::Dithering; + Memory::Free(_mode); + + const char** argv = const_cast(argEnumerator->GetArguments()) + argEnumerator->GetIndex() - 1; + int32_t argc = argEnumerator->GetCount() - argEnumerator->GetIndex() + 1; + + gOpenRCT2Headless = true; + if (argc == 0) + return -1; + + if (String::iequals(argv[0], "details")) + { + return details(argv, argc); + } + + if (String::iequals(argv[0], "export")) + { + return exportSingle(argv, argc); + } + + if (String::iequals(argv[0], "exportall")) + { + return exportAll(argv, argc); + } + + if (String::iequals(argv[0], "exportobject")) + { + return exportObject(argv, argc); + } + + if (String::iequals(argv[0], "create")) + { + return create(argv, argc); + } + + if (String::iequals(argv[0], "append")) + { + return append(argv, argc, spriteMode); + } + + if (String::iequals(argv[0], "build")) + { + return build(argv, argc, spriteMode); + } + + if (String::iequals(argv[0], "combine")) + { + return combine(argv, argc); + } + + fprintf(stderr, "Unknown sprite command.\n"); + return EXITCODE_FAIL; + } + + bool SpriteImageExport(const G1Element& spriteElement, u8string_view outPath) + { + const size_t pixelBufferSize = static_cast(spriteElement.width) * spriteElement.height; + auto pixelBuffer = std::make_unique(pixelBufferSize); + auto pixels = pixelBuffer.get(); + + RenderTarget rt; + rt.bits = pixels; + rt.x = 0; + rt.y = 0; + rt.width = spriteElement.width; + rt.height = spriteElement.height; + rt.pitch = 0; + rt.zoom_level = ZoomLevel{ 0 }; + + DrawSpriteArgs args( + ImageId(), PaletteMap::GetDefault(), spriteElement, 0, 0, spriteElement.width, spriteElement.height, pixels); + GfxSpriteToBuffer(rt, args); + + auto const pixels8 = rt.bits; + auto const pixelsLen = rt.LineStride() * rt.WorldHeight(); + try + { + Image image; + image.Width = rt.width; + image.Height = rt.height; + image.Depth = 8; + image.Stride = rt.LineStride(); + image.Palette = StandardPalette; + image.Pixels = std::vector(pixels8, pixels8 + pixelsLen); + Imaging::WriteToFile(outPath, image, ImageFormat::png); + return true; + } + catch (const std::exception& e) + { + fprintf(stderr, "Unable to write png: %s", e.what()); + return false; + } + } + + std::optional SpriteImageImport(u8string_view path, ImageImportMeta meta) + { + try + { + auto format = ImageFormat::png32; + if (meta.palette == Palette::KeepIndices) + { + format = ImageFormat::png; + } + + ImageImporter importer; + auto image = Imaging::ReadFromFile(path, format); + + return importer.Import(image, meta); + } + catch (const std::exception& e) + { + fprintf(stderr, "%s\n", e.what()); + return std::nullopt; + } + } + + // TODO: Remove when C++20 is enabled and std::format can be used + std::string PopStr(std::ostringstream& oss) + { + auto str = oss.str(); + oss.str(""); + oss.clear(); + return str; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteCommands.h b/src/openrct2/command_line/sprite/SpriteCommands.h new file mode 100644 index 0000000000..0a24147e6b --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteCommands.h @@ -0,0 +1,37 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#pragma once + +#include "../../drawing/ImageImporter.h" + +#include +#include +#include + +struct G1Element; +using utf8 = char; +using u8string_view = std::basic_string_view; + +namespace OpenRCT2::CommandLine::Sprite +{ + using namespace OpenRCT2::Drawing; + bool SpriteImageExport(const G1Element& spriteElement, u8string_view outPath); + std::optional SpriteImageImport(u8string_view path, ImageImportMeta meta); + std::string PopStr(std::ostringstream& oss); + + int32_t append(const char** argv, int32_t argc, ImportMode spriteMode); + int32_t build(const char** argv, int32_t argc, ImportMode spriteMode); + int32_t combine(const char** argv, int32_t argc); + int32_t create(const char** argv, int32_t argc); + int32_t details(const char** argv, int32_t argc); + int32_t exportAll(const char** argv, int32_t argc); + int32_t exportObject(const char** argv, int32_t argc); + int32_t exportSingle(const char** argv, int32_t argc); +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteCreate.cpp b/src/openrct2/command_line/sprite/SpriteCreate.cpp new file mode 100644 index 0000000000..c88564e79c --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteCreate.cpp @@ -0,0 +1,34 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../core/StringTypes.h" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t create(const char** argv, int32_t argc) + { + if (argc < 2) + { + fprintf(stderr, "usage: sprite create \n"); + return -1; + } + + const utf8* spriteFilePath = argv[1]; + + SpriteFile spriteFile; + spriteFile.Save(spriteFilePath); + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteDetails.cpp b/src/openrct2/command_line/sprite/SpriteDetails.cpp new file mode 100644 index 0000000000..98766c7ac6 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteDetails.cpp @@ -0,0 +1,66 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../core/StringTypes.h" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t details(const char** argv, int32_t argc) + { + if (argc < 2) + { + fprintf(stdout, "usage: sprite details [idx]\n"); + return -1; + } + + if (argc == 2) + { + const utf8* spriteFilePath = argv[1]; + auto spriteFile = SpriteFile::Open(spriteFilePath); + if (!spriteFile.has_value()) + { + fprintf(stderr, "Unable to open input sprite file.\n"); + return -1; + } + + printf("sprites: %u\n", spriteFile->Header.num_entries); + printf("data size: %u\n", spriteFile->Header.total_size); + return 0; + } + + const utf8* spriteFilePath = argv[1]; + int32_t spriteIndex = atoi(argv[2]); + auto spriteFile = SpriteFile::Open(spriteFilePath); + if (!spriteFile.has_value()) + { + fprintf(stderr, "Unable to open input sprite file.\n"); + return -1; + } + + if (spriteIndex < 0 || spriteIndex >= static_cast(spriteFile->Header.num_entries)) + { + fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex); + return -1; + } + + G1Element* g1 = &spriteFile->Entries[spriteIndex]; + printf("width: %d\n", g1->width); + printf("height: %d\n", g1->height); + printf("x offset: %d\n", g1->x_offset); + printf("y offset: %d\n", g1->y_offset); + printf("data offset: %p\n", g1->offset); + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteExport.cpp b/src/openrct2/command_line/sprite/SpriteExport.cpp new file mode 100644 index 0000000000..08b3c79e96 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteExport.cpp @@ -0,0 +1,53 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../core/FileStream.h" +#include "../../core/StringTypes.h" +#include "../../drawing/Drawing.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t exportSingle(const char** argv, int32_t argc) + { + if (argc < 4) + { + fprintf(stdout, "usage: sprite export \n"); + return -1; + } + + const utf8* spriteFilePath = argv[1]; + int32_t spriteIndex = atoi(argv[2]); + const utf8* outputPath = argv[3]; + auto spriteFile = SpriteFile::Open(spriteFilePath); + if (!spriteFile.has_value()) + { + fprintf(stderr, "Unable to open input sprite file.\n"); + return -1; + } + + if (spriteIndex < 0 || spriteIndex >= static_cast(spriteFile->Header.num_entries)) + { + fprintf(stderr, "Sprite #%d does not exist in sprite file.\n", spriteIndex); + return -1; + } + + const auto& spriteHeader = spriteFile->Entries[spriteIndex]; + if (!SpriteImageExport(spriteHeader, outputPath)) + { + fprintf(stderr, "Could not export\n"); + return -1; + } + fprintf(stdout, "{ \"x\": %d, \"y\": %d }\n", spriteHeader.x_offset, spriteHeader.y_offset); + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteExportAll.cpp b/src/openrct2/command_line/sprite/SpriteExportAll.cpp new file mode 100644 index 0000000000..567f91df5f --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteExportAll.cpp @@ -0,0 +1,69 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../Context.h" +#include "../../core/FileStream.h" +#include "../../core/Path.hpp" +#include "../../core/StringTypes.h" +#include "../../drawing/Drawing.h" +#include "../../object/Object.h" +#include "../../object/ObjectFactory.h" +#include "SpriteCommands.h" +#include "SpriteFile.h" + +#include +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t exportAll(const char** argv, int32_t argc) + { + if (argc < 3) + { + fprintf(stdout, "usage: sprite exportall \n"); + return -1; + } + + const utf8* spriteFilePath = argv[1]; + const utf8* outputPath = argv[2]; + + auto spriteFile = SpriteFile::Open(spriteFilePath); + if (!spriteFile.has_value()) + { + fprintf(stderr, "Unable to open input sprite file.\n"); + return -1; + } + + if (!Path::CreateDirectory(outputPath)) + { + fprintf(stderr, "Unable to create directory.\n"); + return -1; + } + + const uint32_t maxIndex = spriteFile->Header.num_entries; + const int32_t numbers = static_cast(std::floor(std::log10(maxIndex) + 1)); + + std::ostringstream oss; // TODO: Remove when C++20 is enabled and std::format can be used + for (uint32_t spriteIndex = 0; spriteIndex < maxIndex; spriteIndex++) + { + // Status indicator + printf("\r%u / %u, %u%%", spriteIndex + 1, maxIndex, ((spriteIndex + 1) * 100) / maxIndex); + + oss << std::setw(numbers) << std::setfill('0') << spriteIndex << ".png"; + + const auto& spriteHeader = spriteFile->Entries[spriteIndex]; + if (!SpriteImageExport(spriteHeader, Path::Combine(outputPath, PopStr(oss)))) + { + fprintf(stderr, "Could not export\n"); + return -1; + } + } + return 0; + } +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteExportObject.cpp b/src/openrct2/command_line/sprite/SpriteExportObject.cpp new file mode 100644 index 0000000000..a29f5828d7 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteExportObject.cpp @@ -0,0 +1,82 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "../../Context.h" +#include "../../core/FileStream.h" +#include "../../core/Path.hpp" +#include "../../core/StringTypes.h" +#include "../../drawing/Drawing.h" +#include "../../object/Object.h" +#include "../../object/ObjectFactory.h" +#include "SpriteCommands.h" + +#include +#include + +namespace OpenRCT2::CommandLine::Sprite +{ + int32_t exportObject(const char** argv, int32_t argc) + { + if (argc < 3) + { + fprintf(stdout, "usage: sprite exportobject \n"); + return -1; + } + + const char* objectPath = argv[1]; + const utf8* outputPath = argv[2]; + auto context = CreateContext(); + context->Initialise(); + + std::unique_ptr metaObject = OpenRCT2::ObjectFactory::CreateObjectFromFile(objectPath, true); + if (metaObject == nullptr) + { + fprintf(stderr, "Could not load the object.\n"); + return -1; + } + + if (!Path::CreateDirectory(outputPath)) + { + fprintf(stderr, "Unable to create output directory.\n"); + return -1; + } + + const auto* imageTableStart = metaObject->GetImageTable().GetImages(); + const uint32_t maxIndex = metaObject->GetNumImages(); + const int32_t numbers = static_cast(std::floor(std::log10(maxIndex) + 1)); + + std::ostringstream oss; // TODO: Remove when C++20 is enabled and std::format can be used + for (uint32_t spriteIndex = 0; spriteIndex < maxIndex; spriteIndex++) + { + oss << std::setw(numbers) << std::setfill('0') << spriteIndex << ".png"; + auto path = Path::Combine(outputPath, PopStr(oss)); + + const auto& g1 = imageTableStart[spriteIndex]; + if (g1.width == 0 || g1.height == 0) + { + fprintf(stdout, "\"\""); + } + else + { + if (!SpriteImageExport(g1, path)) + { + fprintf(stderr, "Could not export\n"); + return -1; + } + + path = fs::u8path(path).generic_u8string(); + fprintf(stdout, "{ \"path\": \"%s\", \"x\": %d, \"y\": %d }", path.c_str(), g1.x_offset, g1.y_offset); + } + + fprintf(stdout, (spriteIndex + 1 != maxIndex) ? ",\n" : "\n"); + } + return 0; + } + +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteFile.cpp b/src/openrct2/command_line/sprite/SpriteFile.cpp new file mode 100644 index 0000000000..6bbaae440e --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteFile.cpp @@ -0,0 +1,129 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include "SpriteFile.h" + +#include "../../core/FileStream.h" + +namespace OpenRCT2::CommandLine::Sprite +{ + std::optional SpriteFile::Open(const utf8* path) + { + try + { + FileStream stream(path, FileMode::open); + + SpriteFile spriteFile; + stream.Read(&spriteFile.Header, sizeof(RCTG1Header)); + + if (spriteFile.Header.num_entries > 0) + { + spriteFile.Entries.reserve(spriteFile.Header.num_entries); + + for (uint32_t i = 0; i < spriteFile.Header.num_entries; ++i) + { + RCTG1Element entry32bit{}; + stream.Read(&entry32bit, sizeof(entry32bit)); + G1Element entry{}; + + entry.offset = reinterpret_cast(static_cast(entry32bit.offset)); + entry.width = entry32bit.width; + entry.height = entry32bit.height; + entry.x_offset = entry32bit.x_offset; + entry.y_offset = entry32bit.y_offset; + entry.flags = entry32bit.flags; + entry.zoomed_offset = entry32bit.zoomed_offset; + spriteFile.Entries.push_back(std::move(entry)); + } + spriteFile.Data.resize(spriteFile.Header.total_size); + stream.Read(spriteFile.Data.data(), spriteFile.Header.total_size); + } + spriteFile.MakeEntriesAbsolute(); + return spriteFile; + } + catch (IOException&) + { + return std::nullopt; + } + } + + void SpriteFile::MakeEntriesAbsolute() + { + if (!isAbsolute) + { + for (auto& entry : Entries) + entry.offset += reinterpret_cast(Data.data()); + } + isAbsolute = true; + } + + void SpriteFile::MakeEntriesRelative() + { + if (isAbsolute) + { + for (auto& entry : Entries) + entry.offset -= reinterpret_cast(Data.data()); + } + isAbsolute = false; + } + + void SpriteFile::AddImage(ImageImporter::ImportResult& image) + { + Header.num_entries++; + // New image will have its data inserted after previous image + uint8_t* newElementOffset = reinterpret_cast(static_cast(Header.total_size)); + Header.total_size += static_cast(image.Buffer.size()); + Entries.reserve(Header.num_entries); + + { + ScopedRelativeSpriteFile scopedRelative(*this); + Data.reserve(Header.total_size); + Entries.push_back(image.Element); + Entries.back().offset = newElementOffset; + const auto& buffer = image.Buffer; + std::copy(buffer.begin(), buffer.end(), std::back_inserter(Data)); + } + } + + bool SpriteFile::Save(const utf8* path) + { + try + { + FileStream stream(path, FileMode::write); + stream.Write(&Header, sizeof(RCTG1Header)); + + if (Header.num_entries > 0) + { + ScopedRelativeSpriteFile scopedRelative(*this); + + for (const auto& entry : Entries) + { + RCTG1Element entry32bit{}; + + entry32bit.offset = static_cast(reinterpret_cast(const_cast(entry.offset))); + entry32bit.width = entry.width; + entry32bit.height = entry.height; + entry32bit.x_offset = entry.x_offset; + entry32bit.y_offset = entry.y_offset; + entry32bit.flags = entry.flags; + entry32bit.zoomed_offset = entry.zoomed_offset; + + stream.Write(&entry32bit, sizeof(entry32bit)); + } + stream.Write(Data.data(), Header.total_size); + } + return true; + } + catch (IOException&) + { + return false; + } + } + +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/command_line/sprite/SpriteFile.h b/src/openrct2/command_line/sprite/SpriteFile.h new file mode 100644 index 0000000000..4344288f38 --- /dev/null +++ b/src/openrct2/command_line/sprite/SpriteFile.h @@ -0,0 +1,55 @@ +/***************************************************************************** + * Copyright (c) 2014-2025 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#pragma once + +#include "../../drawing/Drawing.h" +#include "../../drawing/ImageImporter.h" + +namespace OpenRCT2::CommandLine::Sprite +{ + using OpenRCT2::Drawing::ImageImporter; + + class SpriteFile + { + public: + RCTG1Header Header{}; + std::vector Entries; + std::vector Data; + void AddImage(ImageImporter::ImportResult& image); + bool Save(const utf8* path); + static std::optional Open(const utf8* path); + + private: + class ScopedRelativeSpriteFile + { + private: + SpriteFile& _SpriteFile; + bool _WasAbsolute; + + public: + ScopedRelativeSpriteFile(SpriteFile& sFile) + : _SpriteFile(sFile) + , _WasAbsolute(sFile.isAbsolute) + { + if (_WasAbsolute) + _SpriteFile.MakeEntriesRelative(); + } + + ~ScopedRelativeSpriteFile() + { + if (_WasAbsolute) + _SpriteFile.MakeEntriesAbsolute(); + } + }; + bool isAbsolute = false; + void MakeEntriesAbsolute(); + void MakeEntriesRelative(); + }; +} // namespace OpenRCT2::CommandLine::Sprite diff --git a/src/openrct2/libopenrct2.vcxproj b/src/openrct2/libopenrct2.vcxproj index d1815b1674..868b309ddf 100644 --- a/src/openrct2/libopenrct2.vcxproj +++ b/src/openrct2/libopenrct2.vcxproj @@ -173,7 +173,8 @@ - + + @@ -763,14 +764,22 @@ - + + + + + + + + + + - @@ -1187,4 +1196,4 @@ - \ No newline at end of file + diff --git a/test/tests/CLITests.cpp b/test/tests/CLITests.cpp index e305aaacd1..d51b9b141f 100644 --- a/test/tests/CLITests.cpp +++ b/test/tests/CLITests.cpp @@ -5,10 +5,11 @@ #include #include #include -#include +#include #include using namespace OpenRCT2; +using namespace OpenRCT2::CommandLine::Sprite; class CommandLineTests : public testing::Test { @@ -61,20 +62,20 @@ TEST_F(CommandLineTests, command_line_for_sprite_details) std::string exampleFilePath = ExampleSpriteFilePath(); const char* detailsCmd[3] = { "details", exampleFilePath.c_str() }; - int32_t result = CommandLineForSprite(detailsCmd, 2); + int32_t result = details(detailsCmd, 2); // need to come up with some way to extract stdout/stderr stream if we want to // fully test this module - ASSERT_EQ(result, 1); + ASSERT_EQ(result, 0); } TEST_F(CommandLineTests, command_line_for_sprite_build) { std::string manifestFilePath = ManifestFilePath(); std::string outputfilePath = BuildOutputfilePath(); - const char* detailsCmd[3] = { "build", outputfilePath.c_str(), manifestFilePath.c_str() }; + const char* buildCmd[3] = { "build", outputfilePath.c_str(), manifestFilePath.c_str() }; - int32_t result = CommandLineForSprite(detailsCmd, 3); - ASSERT_EQ(result, 1); + int32_t result = build(buildCmd, 3, ImportMode::Default); + ASSERT_EQ(result, 0); // compare the resulting output file and assert its identical to expected ASSERT_TRUE(CompareSpriteFiles(ExampleSpriteFilePath(), outputfilePath)); } @@ -84,15 +85,15 @@ TEST_F(CommandLineTests, command_line_for_sprite_failed_build) // run on correct manifest file std::string manifestFilePath = ManifestFilePath(); std::string outputfilePath = BuildOutputfilePath(); - const char* detailsCmd[3] = { "build", outputfilePath.c_str(), manifestFilePath.c_str() }; - int32_t result = CommandLineForSprite(detailsCmd, 3); - ASSERT_EQ(result, 1); + const char* buildCmd[3] = { "build", outputfilePath.c_str(), manifestFilePath.c_str() }; + int32_t result = build(buildCmd, 3, ImportMode::Default); + ASSERT_EQ(result, 0); ASSERT_TRUE(CompareSpriteFiles(ExampleSpriteFilePath(), outputfilePath)); // now use bad manifest and make sure output file is not edited std::string badManifestFilePath = BadManifestFilePath(); - detailsCmd[2] = badManifestFilePath.c_str(); - result = CommandLineForSprite(detailsCmd, 3); + buildCmd[2] = badManifestFilePath.c_str(); + result = build(buildCmd, 3, ImportMode::Default); // check the command failed ASSERT_EQ(result, -1); // validate the target file was unchanged