From 5f01e8065da58e4ad7ebad8f97d2e45bb6f99285 Mon Sep 17 00:00:00 2001 From: shweet Date: Wed, 21 Oct 2026 00:15:56 -0400 Subject: [PATCH] SVG spritesheets: pack, merge, rasterize Packing an SVG sheet makes a new SVG holding its drawing once (as a symbol), each region a clipped view of it at its new place; merging makes an SVG whenever any sheet is one, with PNG sheets embedded as images (the merged sheet's file name takes the matching extension). Both go through Image::compose, which also does the pixel versions, so merge_append is gone. Vector sheets save as their SVG (autosaves too, and images load as PNG or SVG by content), and their asset key includes the SVG. Rasterize in the Spritesheets menu turns selected SVG sheets into PNGs beside them, with a toast for each. Co-Authored-By: Claude Opus 5.5 --- src/document.cpp | 16 +-- src/document.hpp | 2 +- src/edit/spritesheets.cpp | 45 +++--- src/imgui/actions.hpp | 1 + src/imgui/documents.cpp | 2 +- src/imgui/taskbar.cpp | 2 +- src/imgui/window/spritesheets.cpp | 23 +++- src/resource/asset_store.cpp | 4 +- src/resource/image.cpp | 221 +++++++++++++++++++++++++----- src/resource/image.hpp | 14 +- src/resource/strings.hpp | 2 + tests/assets.cpp | 26 +++- tests/operations.cpp | 38 +++++ tests/render/render.cpp | 2 +- 14 files changed, 316 insertions(+), 82 deletions(-) diff --git a/src/document.cpp b/src/document.cpp index 3339989..68ae592 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -272,7 +272,7 @@ namespace anm2ed { auto spritesheet = model::item_get(model.content.spritesheets, id); auto texture = texture_get(id); - if (texture && texture->write_png(spritesheet_autosave_path_get(*spritesheet))) + if (texture && texture->write(spritesheet_autosave_path_get(*spritesheet))) spritesheetAutosaveHashes[id] = spritesheetHashes.at(id); } autosaveHash = hash; @@ -602,8 +602,7 @@ namespace anm2ed bool Document::spritesheet_pack(int id, int padding) { auto texture = texture_get(id); - auto packed = - texture && !texture->is_vector() ? edit::spritesheet_pack(model, id, *texture, padding) : std::nullopt; + auto packed = texture ? edit::spritesheet_pack(model, id, *texture, padding) : std::nullopt; if (!packed) return false; texture_set(id, std::move(*packed)); assets_sync(); @@ -613,12 +612,13 @@ namespace anm2ed bool Document::spritesheets_merge(const std::set& ids, bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, Origin origin) { - if (std::ranges::any_of(ids, [&](int id) { return texture_get(id) && texture_get(id)->is_vector(); })) return false; auto merged = edit::spritesheets_merge( model, ids, [this](int id) { return texture_get(id); }, isAppendRight, isMakeRegions, isMakePrimaryRegion, origin); if (!merged) return false; texture_set(*ids.begin(), std::move(*merged)); + // The merged sheet may now be an SVG (or a PNG) under a new name; it is written when saved. + texturePaths[*ids.begin()] = model::item_get(model.content.spritesheets, *ids.begin())->path; for (auto id : ids) if (id != *ids.begin()) textures.erase(id); assets_sync(); @@ -786,10 +786,9 @@ namespace anm2ed } } - // Writes each SVG spritesheet a layer shows as a PNG beside it, and points the spritesheet at the PNG. - void Document::spritesheets_vector_convert() + // Rasterizes SVG spritesheets: each is written as a PNG beside it (as drawn now), and points at the PNG. + void Document::spritesheets_vector_convert(const std::set& ids) { - auto ids = model::spritesheets_vector_used_get(model); std::set converted{}; edit_apply(EDIT_CONVERT_SVG_SPRITESHEETS, [&](model::Model& model) @@ -798,10 +797,11 @@ namespace anm2ed { auto spritesheet = model::item_get(model.content.spritesheets, id); auto texture = texture_get(id); + if (!spritesheet || !texture || !texture->is_vector()) continue; auto pngPath = std::filesystem::path(spritesheet->path).replace_extension(resource::image::PNG_EXTENSION); auto pathString = path::to_utf8(pngPath); - if (!texture || !texture->write_png(std::filesystem::absolute(directory_get()) / pngPath)) + if (!texture->write_png(std::filesystem::absolute(directory_get()) / pngPath)) { toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); continue; diff --git a/src/document.hpp b/src/document.hpp index fb42465..2716c17 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -193,7 +193,7 @@ namespace anm2ed void spritesheet_hashes_sync(); std::set spritesheets_changed_get(); void spritesheets_reload(const std::set&); - void spritesheets_vector_convert(); + void spritesheets_vector_convert(const std::set&); std::filesystem::path spritesheet_autosave_path_get(const model::Spritesheet&); std::set spritesheets_autosave_dirty_get(); void spritesheets_autosave_restore(); diff --git a/src/edit/spritesheets.cpp b/src/edit/spritesheets.cpp index 57a53db..0401e5a 100644 --- a/src/edit/spritesheets.cpp +++ b/src/edit/spritesheets.cpp @@ -102,32 +102,17 @@ namespace anm2ed::edit std::vector positions{}; if (!util::pack::rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return {}; - std::vector packedPixels((std::size_t)packedSize.x * packedSize.y * image::CHANNELS, 0); - std::unordered_map crops{}; + std::vector parts{}; for (int i = 0; i < (int)items.size(); ++i) - { - auto& item = items[i]; - auto destination = positions[i] + padding; - crops[item.regionId] = destination; - for (int y = 0; y < item.size.y; ++y) - for (int x = 0; x < item.size.x; ++x) - { - auto source = item.source + glm::ivec2(x, y); - auto target = destination + glm::ivec2(x, y); - if (glm::any(glm::lessThan(source, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(source, sheet.size)) || - glm::any(glm::greaterThanEqual(target, packedSize))) - continue; - std::copy_n(sheet.pixels.data() + ((std::size_t)source.y * sheet.size.x + source.x) * image::CHANNELS, - image::CHANNELS, - packedPixels.data() + ((std::size_t)target.y * packedSize.x + target.x) * image::CHANNELS); - } - } - + parts.push_back({&sheet, items[i].source, items[i].size, positions[i] + padding}); for (auto& region : spritesheet->regions) - if (crops.contains(region.id)) region.crop = crops.at(region.id); - return Image(packedPixels.data(), packedSize); + for (int i = 0; i < (int)items.size(); ++i) + if (items[i].regionId == region.id) region.crop = parts[i].destination; + return Image::compose(parts, packedSize, sheet.is_vector()); } + // Appends sheets to the first, right or below. The result is an SVG (holding any PNG sheets as images) when any of + // them is one; the first sheet's path takes the result's extension. std::optional spritesheets_merge(Model& model, const std::set& ids, const ImageGet& image_get, bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, Origin origin) @@ -138,7 +123,8 @@ namespace anm2ed::edit auto baseId = *ids.begin(); auto base = item_get(model.content.spritesheets, baseId); - auto mergedTexture = *image_get(baseId); + auto mergedSize = image_get(baseId)->size; + std::vector parts{{image_get(baseId), {}, mergedSize, {}}}; std::unordered_map> regionIdMap{}; auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) @@ -155,13 +141,15 @@ namespace anm2ed::edit base->regions.push_back(region); }; - if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedTexture.size); + if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedSize); for (auto id : ids) { if (id == baseId) continue; auto texture = image_get(id); - auto offset = isAppendRight ? glm::ivec2(mergedTexture.size.x, 0) : glm::ivec2(0, mergedTexture.size.y); - mergedTexture = Image::merge_append(mergedTexture, *texture, isAppendRight); + auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y); + mergedSize = isAppendRight ? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y)) + : glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y); + parts.push_back({texture, {}, texture->size, offset}); if (!isMakeRegions) continue; location_region_add(id, offset, texture->size); @@ -196,8 +184,11 @@ namespace anm2ed::edit frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; }); + auto isVector = std::ranges::any_of(parts, [](const ImagePart& part) { return part.image->is_vector(); }); + if (isVector != path::is_extension(base->path, image::SVG_EXTENSION)) + base->path.replace_extension(isVector ? image::SVG_EXTENSION : image::PNG_EXTENSION); std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet) { return spritesheet.id != baseId && ids.contains(spritesheet.id); }); - return mergedTexture; + return Image::compose(parts, mergedSize, isVector); } } diff --git a/src/imgui/actions.hpp b/src/imgui/actions.hpp index 6334075..6910a7b 100644 --- a/src/imgui/actions.hpp +++ b/src/imgui/actions.hpp @@ -34,6 +34,7 @@ namespace anm2ed::imgui X(ACTION_OPEN_DIRECTORY, BASIC_OPEN_DIRECTORY, -1) \ X(ACTION_SET_FILE_PATH, BASIC_SET_FILE_PATH, -1) \ X(ACTION_PACK, BASIC_PACK, -1) \ + X(ACTION_RASTERIZE, LABEL_RASTERIZE, -1) \ X(ACTION_TRIM, BASIC_TRIM, -1) \ X(ACTION_PLAY, LABEL_PLAY, SHORTCUT_PLAY_PAUSE) \ X(ACTION_CENTER_VIEW, LABEL_CENTER_VIEW, SHORTCUT_CENTER_VIEW) \ diff --git a/src/imgui/documents.cpp b/src/imgui/documents.cpp index f2799ee..5218314 100644 --- a/src/imgui/documents.cpp +++ b/src/imgui/documents.cpp @@ -313,7 +313,7 @@ namespace anm2ed::imgui auto pathString = path::to_utf8(spritesheet.path); auto savePath = closeDocument.directory_get() / spritesheet.path; path::ensure_directory(savePath.parent_path()); - if (texture->write_png(savePath)) + if (texture->write(savePath)) { closeDocument.spritesheet_hash_set_saved(id); toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index b3867d6..b51a9b3 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -395,7 +395,7 @@ namespace anm2ed::imgui shortcut(manager.chords[isConverted ? SHORTCUT_CONFIRM : SHORTCUT_CANCEL]); if (!ImGui::Button(localize.get(label), widgetSize) || !document) continue; if (isConverted) - document->spritesheets_vector_convert(); + document->spritesheets_vector_convert(model::spritesheets_vector_used_get(document->model)); else document->isVectorKept = true; vectorPopup.close(); diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index 435761f..4848507 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -38,11 +38,11 @@ namespace anm2ed::imgui { auto spritesheet = spritesheet_get(document, id); auto texture = document.texture_get(id); - if (!spritesheet || !texture || texture->is_vector()) continue; + if (!spritesheet || !texture) continue; auto pathString = path::to_utf8(spritesheet->path); WorkingDirectory workingDirectory(document.directory_get()); path::ensure_directory(spritesheet->path.parent_path()); - auto isSaved = texture->write_png(spritesheet->path); + auto isSaved = texture->write(spritesheet->path); if (isSaved) document.spritesheet_hash_set_saved(id); toast_log(isSaved ? Level::INFO : Level::ERROR, isSaved ? TOAST_SAVE_SPRITESHEET : TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); @@ -65,7 +65,7 @@ namespace anm2ed::imgui { WorkingDirectory workingDirectory(document.directory_get()); path::ensure_directory(newPath.parent_path()); - if (!texture->write_png(newPath)) + if (!texture->write(newPath)) return toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); } spritesheet->path = newPath; @@ -287,6 +287,23 @@ namespace anm2ed::imgui spritesheets.packPopup.open(); }, TOOLTIP_PACK_SPRITESHEET); + // SVG sheets become PNGs beside them; greyed when none of the selection is an SVG. + actions.add( + ACTION_RASTERIZE, + [&]() + { + return std::ranges::any_of(selection, + [&](int id) + { + auto texture = document.texture_get(id); + return texture && texture->is_vector(); + }); + }, + [&]() + { + command_push(panel, [selection](Document& document) { document.spritesheets_vector_convert(selection); }); + }, + TOOLTIP_RASTERIZE_SPRITESHEETS); actions.add( ACTION_SAVE, isAny, [&]() diff --git a/src/resource/asset_store.cpp b/src/resource/asset_store.cpp index 57874ca..1e88f43 100644 --- a/src/resource/asset_store.cpp +++ b/src/resource/asset_store.cpp @@ -26,7 +26,9 @@ namespace anm2ed::resource { auto hash = bytes_hash(value_bytes_get(image.size)); hash = bytes_hash(value_bytes_get(image.isLinear), hash); - hash = hash_finish(bytes_hash(image.pixels, hash)); + hash = bytes_hash(image.pixels, hash); + if (image.svg) hash = bytes_hash({(const std::uint8_t*)image.svg->data(), image.svg->size()}, hash); + hash = hash_finish(hash); images.try_emplace(hash, std::move(image)); return hash; } diff --git a/src/resource/image.cpp b/src/resource/image.cpp index 97d9ab8..5aff4b3 100644 --- a/src/resource/image.cpp +++ b/src/resource/image.cpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #if defined(__clang__) || defined(__GNUC__) @@ -24,6 +26,7 @@ #endif #include +#include #include "file.hpp" #include "math.hpp" @@ -37,6 +40,19 @@ using namespace glm; namespace anm2ed::resource { + constexpr std::size_t BASE64_GROUP_BYTES = 3; + constexpr int BASE64_DIGIT_BITS = 6; + constexpr std::uint32_t BASE64_DIGIT_MASK = 0x3F; + constexpr int BYTE_BITS = 8; + constexpr std::string_view BASE64_DIGITS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + constexpr char BASE64_PADDING = '='; + constexpr auto SVG_NAMESPACE = "http://www.w3.org/2000/svg"; + constexpr auto XLINK_NAMESPACE = "http://www.w3.org/1999/xlink"; + constexpr auto SVG_ID_PREFIX = "anm2ed-source-"; + constexpr std::string_view SVG_URL_START = "url(#"; + // A drawing's root attributes that place it, rather than style it. + constexpr std::string_view SVG_ROOT_ONLY_ATTRIBUTES[] = {"width", "height", "viewBox", "preserveAspectRatio", + "x", "y", "version", "id"}; bool Image::is_valid() const { return !pixels.empty(); } @@ -85,23 +101,13 @@ namespace anm2ed::resource } } - Image::Image(const std::filesystem::path& pngPath) + // A PNG, or else an SVG (whatever the file is named, so autosaved copies load too). + Image::Image(const std::filesystem::path& path) { - if (path::is_extension(pngPath, SVG_EXTENSION)) - { - auto text = std::make_shared(); - if (file::read_to_string(pngPath, text.get())) *this = svg_render(std::move(text), 1.0f); - return; - } - File file(pngPath, "rb"); - if (auto handle = file.get()) - { - if (auto data = stbi_load_from_file(handle, &size.x, &size.y, nullptr, CHANNELS); data) - { - *this = Image(data, size); - stbi_image_free((void*)data); - } - } + auto text = std::make_shared(); + if (!file::read_to_string(path, text.get())) return; + *this = Image((const unsigned char*)text->data(), text->size()); + if (!is_valid()) *this = svg_render(std::move(text), 1.0f); } bool Image::write_png(const std::filesystem::path& path) const @@ -152,32 +158,173 @@ namespace anm2ed::resource return region; } - Image Image::merge_append(const Image& base, const Image& append, bool isAppendRight) + // Base64 of bytes, for an image embedded in an SVG. + std::string base64_get(const std::vector& bytes) { - if (base.size.x <= 0 || base.size.y <= 0) return append; - if (append.size.x <= 0 || append.size.y <= 0) return base; - if (base.pixels.empty()) return append; - if (append.pixels.empty()) return base; - - auto resultSize = isAppendRight ? ivec2(base.size.x + append.size.x, std::max(base.size.y, append.size.y)) - : ivec2(std::max(base.size.x, append.size.x), base.size.y + append.size.y); - auto resultPixelsSize = (size_t)resultSize.x * (size_t)resultSize.y * CHANNELS; - std::vector resultPixels(resultPixelsSize, 0); - - auto blit = [&](const Image& texture, ivec2 offset) + std::string text{}; + for (std::size_t i = 0; i < bytes.size(); i += BASE64_GROUP_BYTES) { - for (int y = 0; y < texture.size.y; y++) - { - auto src = (size_t)y * (size_t)texture.size.x * CHANNELS; - auto dst = ((size_t)(offset.y + y) * (size_t)resultSize.x + (size_t)offset.x) * CHANNELS; - std::memcpy(resultPixels.data() + dst, texture.pixels.data() + src, (size_t)texture.size.x * CHANNELS); - } + auto count = std::min(BASE64_GROUP_BYTES, bytes.size() - i); + std::uint32_t value{}; + for (std::size_t j = 0; j < BASE64_GROUP_BYTES; ++j) + value = value << BYTE_BITS | (j < count ? bytes[i + j] : 0u); + for (std::size_t j = 0; j <= BASE64_GROUP_BYTES; ++j) + text += j <= count + ? BASE64_DIGITS[(value >> ((BASE64_GROUP_BYTES - j) * BASE64_DIGIT_BITS)) & BASE64_DIGIT_MASK] + : BASE64_PADDING; + } + return text; + } + + // An image as one SVG definition: a vector one as a symbol of its drawing (its ids prefixed with `id`, so + // several drawings can share a document), a raster one as an embedded PNG. Either draws at the image's size in + // SVG units. + void svg_definition_add(tinyxml2::XMLDocument& document, tinyxml2::XMLElement* root, tinyxml2::XMLElement* defs, + const Image& image, const std::string& id) + { + if (!image.is_vector()) + { + std::vector png{}; + stbi_write_png_to_func( + [](void* context, void* data, int count) + { + static_cast*>(context)->insert(static_cast*>(context)->end(), + (uint8_t*)data, (uint8_t*)data + count); + }, + &png, image.size.x, image.size.y, CHANNELS, image.pixels.data(), image.size.x * CHANNELS); + auto element = defs->InsertNewChildElement("image"); + element->SetAttribute("id", id.c_str()); + element->SetAttribute("width", image.size.x); + element->SetAttribute("height", image.size.y); + element->SetAttribute("xlink:href", ("data:image/png;base64," + base64_get(png)).c_str()); + return; + } + + tinyxml2::XMLDocument source{}; + source.Parse(image.svg->c_str()); + auto sourceRoot = source.RootElement(); + if (!sourceRoot) return; + + // Every id in the drawing gets the prefix, and so does every reference to one (href="#id", url(#id)). + std::set ids{}; + auto elements_each = [](tinyxml2::XMLElement* element, auto&& callback, auto&& self) -> void + { + callback(element); + for (auto child = element->FirstChildElement(); child; child = child->NextSiblingElement()) + self(child, callback, self); }; + elements_each( + sourceRoot, + [&](tinyxml2::XMLElement* element) + { + if (auto elementId = element->Attribute("id")) ids.insert(elementId); + }, + elements_each); + auto renamed_get = [&](std::string_view sourceId) { return id + "-" + std::string(sourceId); }; + elements_each( + sourceRoot, + [&](tinyxml2::XMLElement* element) + { + std::vector> attributes{}; + for (auto attribute = element->FirstAttribute(); attribute; attribute = attribute->Next()) + attributes.emplace_back(attribute->Name(), attribute->Value()); + for (auto& [name, value] : attributes) + { + if (name == "id") + value = renamed_get(value); + else if ((name == "href" || name == "xlink:href") && value.starts_with('#') && + ids.contains(value.substr(1))) + value = "#" + renamed_get(value.substr(1)); + else + for (auto at = value.find(SVG_URL_START); at != std::string::npos; at = value.find(SVG_URL_START, at + 1)) + { + auto start = at + SVG_URL_START.size(); + auto end = value.find(')', start); + if (end == std::string::npos) break; + if (auto reference = value.substr(start, end - start); ids.contains(reference)) + value.replace(start, end - start, renamed_get(reference)); + } + element->SetAttribute(name.c_str(), value.c_str()); + } + }, + elements_each); - blit(base, {0, 0}); - blit(append, isAppendRight ? ivec2(base.size.x, 0) : ivec2(0, base.size.y)); + auto unitSize = image.unit_size_get(); + auto symbol = defs->InsertNewChildElement("symbol"); + symbol->SetAttribute("id", id.c_str()); + auto viewBox = sourceRoot->Attribute("viewBox"); + symbol->SetAttribute("viewBox", viewBox ? viewBox : std::format("0 0 {} {}", unitSize.x, unitSize.y).c_str()); + if (auto aspect = sourceRoot->Attribute("preserveAspectRatio")) symbol->SetAttribute("preserveAspectRatio", aspect); + // The drawing's root styles carry over through a group; its namespaces go on the new root. + auto group = symbol->InsertNewChildElement("g"); + for (auto attribute = sourceRoot->FirstAttribute(); attribute; attribute = attribute->Next()) + { + std::string_view name = attribute->Name(); + if (name.starts_with("xmlns")) + root->SetAttribute(attribute->Name(), attribute->Value()); + else if (!std::ranges::contains(SVG_ROOT_ONLY_ATTRIBUTES, name)) + group->SetAttribute(attribute->Name(), attribute->Value()); + } + for (auto child = sourceRoot->FirstChild(); child; child = child->NextSibling()) + group->InsertEndChild(child->DeepClone(&document)); + } - return Image(resultPixels.data(), resultSize); + // Parts of images placed into one image of `size`: an SVG when `isVector` (each part a clipped view of its image's + // drawing, or of an embedded PNG), otherwise pixels. + Image Image::compose(const std::vector& parts, glm::ivec2 size, bool isVector) + { + if (!isVector) + { + std::vector pixels((std::size_t)size.x * size.y * CHANNELS, 0); + Image composed(pixels.data(), size); + for (const auto& part : parts) + composed.paste(part.image->region_get(part.source, part.size), part.destination); + return composed; + } + + tinyxml2::XMLDocument document{}; + auto root = document.NewElement("svg"); + document.InsertEndChild(root); + root->SetAttribute("xmlns", SVG_NAMESPACE); + root->SetAttribute("xmlns:xlink", XLINK_NAMESPACE); + root->SetAttribute("width", size.x); + root->SetAttribute("height", size.y); + root->SetAttribute("viewBox", std::format("0 0 {} {}", size.x, size.y).c_str()); + auto defs = root->InsertNewChildElement("defs"); + + std::vector sources{}; + for (const auto& part : parts) + { + auto source = std::ranges::find(sources, part.image); + if (source == sources.end()) + { + source = sources.insert(sources.end(), part.image); + svg_definition_add(document, root, defs, *part.image, std::format("{}{}", SVG_ID_PREFIX, sources.size() - 1)); + } + auto view = root->InsertNewChildElement("svg"); + view->SetAttribute("x", part.destination.x); + view->SetAttribute("y", part.destination.y); + view->SetAttribute("width", part.size.x); + view->SetAttribute("height", part.size.y); + view->SetAttribute("viewBox", + std::format("{} {} {} {}", part.source.x, part.source.y, part.size.x, part.size.y).c_str()); + auto use = view->InsertNewChildElement("use"); + auto unitSize = part.image->unit_size_get(); + use->SetAttribute("xlink:href", std::format("#{}{}", SVG_ID_PREFIX, source - sources.begin()).c_str()); + use->SetAttribute("width", unitSize.x); + use->SetAttribute("height", unitSize.y); + } + + tinyxml2::XMLPrinter printer{}; + document.Print(&printer); + return svg_render(std::make_shared(printer.CStr()), 1.0f); + } + + // Writes a vector image as its SVG (unless the path asks for a PNG), and any other as a PNG. + bool Image::write(const std::filesystem::path& path) const + { + if (is_vector() && !path::is_extension(path, PNG_EXTENSION)) return file::write_string(path, *svg); + return write_png(path); } vec4 Image::pixel_read(vec2 position) const diff --git a/src/resource/image.hpp b/src/resource/image.hpp index fb13ce8..1c04578 100644 --- a/src/resource/image.hpp +++ b/src/resource/image.hpp @@ -18,6 +18,17 @@ namespace anm2ed::resource::image namespace anm2ed::resource { + class Image; + + // A block of an image placed at `destination`, for composing images. + struct ImagePart + { + const Image* image{}; + glm::ivec2 source{}; + glm::ivec2 size{}; + glm::ivec2 destination{}; + }; + // CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. A vector image keeps // its SVG and is drawn at `scale` pixels per SVG unit; it can be drawn again at any scale, and isn't edited. class Image @@ -42,7 +53,8 @@ namespace anm2ed::resource size_t pixel_size_get() const; bool write_png(const std::filesystem::path&) const; static bool write_pixels_png(const std::filesystem::path&, glm::ivec2, const uint8_t*); - static Image merge_append(const Image&, const Image&, bool); + bool write(const std::filesystem::path&) const; + static Image compose(const std::vector&, glm::ivec2, bool); void paste(const Image&, glm::ivec2); Image region_get(glm::ivec2, glm::ivec2) const; glm::vec4 pixel_read(glm::vec2) const; diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index d456fdc..58276fb 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -307,6 +307,7 @@ namespace anm2ed X(LABEL_PROPERTY, "Property", "Propiedad", "Свойство", "属性", "속성") \ X(LABEL_PURGE_DEFAULT_COLORS, "Purge Default Color Values", "Omitir Valores de Color por Defecto", "Убирать цвета по умолчанию", "清除默认颜色值", "기본 색상 값 제거") \ X(LABEL_RANDOM, "Random", "Aleatorio", "Случайно", "随机", "무작위") \ + X(LABEL_RASTERIZE, "Rasterize", "Rasterizar", "Растеризовать", "栅格化", "래스터화") \ X(LABEL_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удалить маркеры", "移除标记", "마커 제거") \ X(LABEL_RESTART, "Restart", "Reiniciar", "Перезапуск", "重新开始", "다시 시작") \ X(LABEL_SAVE_ANYWAY, "Save Anyway", "Guardar de Todos Modos", "Всё равно сохранить", "仍然保存", "그래도 저장") \ @@ -708,6 +709,7 @@ namespace anm2ed X(TOOLTIP_ONLY_SELECTED_ITEM, "Only the selected item (root, layer or null) is onionskinned and shows its pivot path.", "Solo el elemento seleccionado (raíz, capa o null) usa papel cebolla y muestra la trayectoria de su pivote.", "Оньонскин и путь опорной точки показываются только для выбранного элемента (корень, слой или null).", "仅对选中的项目(根、图层或空节点)显示洋葱皮和枢轴路径。", "선택한 항목(루트, 레이어 또는 널)에만 전후 비교와 피벗 경로를 표시합니다.") \ X(TOOLTIP_PIVOT_PATH, "Show the path each item's pivot travels through the animation, with a dot on every frame.", "Muestra la trayectoria que recorre el pivote de cada elemento durante la animación, con un punto en cada Frame.", "Показать путь опорной точки каждого элемента в анимации, с точкой на каждом кадре.", "显示每个项目的枢轴在动画中移动的路径,每帧一个点。", "애니메이션 동안 각 항목의 피벗이 지나는 경로를 프레임마다 점으로 표시합니다.") \ X(TOOLTIP_PURGE_DEFAULT_COLORS, "Leave tints of 255 and color offsets of 0 out of saved frames; the game and the editor read missing ones as those defaults, so files get much smaller.", "Omite de los Frames guardados los tintes de 255 y los desplazamientos de color de 0; el juego y el editor leen los que faltan como esos valores, así que los archivos son mucho más pequeños.", "Не записывать в кадры оттенки 255 и смещения цвета 0; игра и редактор считают отсутствующие значения такими же, поэтому файлы становятся намного меньше.", "保存帧时省略为 255 的色调和为 0 的颜色偏移;游戏和编辑器会将缺失值读作这些默认值,因此文件会小得多。", "저장되는 프레임에서 255인 틴트와 0인 색상 오프셋을 생략합니다. 게임과 에디터는 빠진 값을 기본값으로 읽으므로 파일이 훨씬 작아집니다.") \ + X(TOOLTIP_RASTERIZE_SPRITESHEETS, "Turn the selected SVG spritesheets into PNGs beside them (same name), drawn at 100%.", "Convierte los spritesheets SVG seleccionados en PNG junto a ellos (mismo nombre), dibujados al 100%.", "Превратить выбранные SVG спрайт-листы в PNG рядом с ними (с тем же именем), отрисованные в масштабе 100%.", "将所选 SVG 图集转换为旁边的同名 PNG,按 100% 绘制。", "선택한 SVG 스프라이트 시트를 옆에 같은 이름의 PNG로 바꿉니다(100%로 그림).") \ X(TOOLTIP_REGION, "Set the spritesheet region the frame will use.", "Establece la región del spritesheet que usará el frame.", "Установить регион спрайт-листа, который будет использовать кадр.", "设置帧将使用的图集区域.", "프레임이 사용할 스프라이트 시트 영역을 설정합니다.") \ X(TOOLTIP_FRAME_SHADER, "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.") \ X(TOOLTIP_REGION_PROPERTIES_ORIGIN, "Use a preset origin for the region.", "Usa un origen predefinido para la región.", "Использовать предустановленную точку отсчета для региона.", "为区域使用预设原点。", "영역에 사전 설정된 원점을 사용합니다.") \ diff --git a/tests/assets.cpp b/tests/assets.cpp index ee83043..a11147d 100644 --- a/tests/assets.cpp +++ b/tests/assets.cpp @@ -27,7 +27,8 @@ TEST_CASE("Image png round trip and uid tracking") CHECK(copy.uid != image.uid); CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f)); - auto merged = Image::merge_append(image, loaded, true); + auto merged = Image::compose({{&image, {}, image.size, {}}, {&loaded, {}, loaded.size, {image.size.x, 0}}}, + {image.size.x * 2, image.size.y}, false); CHECK(merged.size == glm::ivec2(4, 2)); CHECK(merged.pixel_read({2, 0}) == image.pixel_read({0, 0})); } @@ -74,3 +75,26 @@ TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale") CHECK(large.unit_size_get() == image.unit_size_get()); CHECK(large.uid != image.uid); } + +TEST_CASE("SVG spritesheets compose into SVGs that draw the same") +{ + Image vector(test::TEST_DIR / "render" / "vector.svg"); + REQUIRE(vector.is_vector()); + + // The circle (left half) and the square (right half) swapped: each part is a clipped view of the drawing. + auto swapped = + Image::compose({{&vector, {16, 0}, {16, 16}, {0, 0}}, {&vector, {0, 0}, {16, 16}, {16, 0}}}, vector.size, true); + REQUIRE(swapped.is_vector()); + CHECK(swapped.size == vector.size); + CHECK(swapped.pixel_read({24.0f, 8.0f}) == vector.pixel_read({8.0f, 8.0f})); + CHECK(swapped.pixel_read({1.0f, 1.0f}) == glm::vec4()); + + // A PNG part is embedded as an image, pixel for pixel; composing the result again still works. + const std::vector pixels{255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255}; + Image raster(pixels.data(), {2, 2}); + auto mixed = Image::compose({{&swapped, {}, swapped.size, {}}, {&raster, {}, raster.size, {32, 0}}}, {34, 16}, true); + REQUIRE(mixed.is_vector()); + CHECK(mixed.pixel_read({33.0f, 1.0f}) == raster.pixel_read({1.0f, 1.0f})); + CHECK(Image::compose({{&mixed, {}, mixed.size, {}}}, mixed.size, true).pixel_read({24.0f, 8.0f}) == + vector.pixel_read({8.0f, 8.0f})); +} diff --git a/tests/operations.cpp b/tests/operations.cpp index ef1f9f5..6701f83 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -458,3 +458,41 @@ TEST_CASE("a trigger fires several events; built-in events join a file when firs std::vector{1}); CHECK(model::isaac_issues_get(model).extraEvents == 0); } + +TEST_CASE("SVG spritesheets pack and merge into SVGs") +{ + auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); + resource::Image vector(TEST_DIR / "render" / "vector.svg"); + auto& regions = model.content.spritesheets.front().regions; + regions.push_back({.id = 0, .name = "circle", .crop = {0, 0}, .size = {16, 16}}); + regions.push_back({.id = 1, .name = "square", .crop = {16, 0}, .size = {16, 16}}); + + // Packing keeps the drawing: each region shows the same pixels where it now sits. + auto packed = edit::spritesheet_pack(model, 0, vector, 1); + REQUIRE(packed); + CHECK(packed->is_vector()); + for (auto [id, original] : {std::pair{0, glm::vec2(8, 8)}, std::pair{1, glm::vec2(24, 8)}}) + { + auto region = model::item_get(model.content.spritesheets.front().regions, id); + CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original)); + } + + // A PNG sheet merged after an SVG one: the result is an SVG holding the PNG; a PNG first takes the .svg name. + const std::vector pixels(4 * 4 * resource::image::CHANNELS, 255); + resource::Image raster(pixels.data(), {4, 4}); + model.content.spritesheets.push_back({.id = 1, .path = "white.png"}); + auto images = std::map{{0, &vector}, {1, &raster}}; + auto image_get = [&](int id) { return images.at(id); }; + auto mixed = model; + auto merged = edit::spritesheets_merge(mixed, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT); + REQUIRE(merged); + CHECK(merged->is_vector()); + CHECK(merged->size == glm::ivec2(36, 16)); + CHECK(merged->pixel_read({33, 1}) == raster.pixel_read({1, 1})); + CHECK(mixed.content.spritesheets.front().path == "vector.svg"); + + std::swap(model.content.spritesheets.front().id, model.content.spritesheets.back().id); + images = {{1, &vector}, {0, &raster}}; + REQUIRE(edit::spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT)); + CHECK(model::item_get(model.content.spritesheets, 0)->path == "white.svg"); +} diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 655bdc4..1b0dbd6 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -216,7 +216,7 @@ TEST_CASE("converting SVG spritesheets writes PNGs beside them") Document document(directory / "vector.anm2", false); REQUIRE(document.is_valid()); - document.spritesheets_vector_convert(); + document.spritesheets_vector_convert({0}); CHECK(document.model.content.spritesheets.front().path == "vector.png"); CHECK(std::filesystem::exists(directory / "vector.png")); REQUIRE(document.texture_get(0));