diff --git a/CMakeLists.txt b/CMakeLists.txt index 4843994..0baac0c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -119,6 +119,7 @@ set(CORE_INCLUDE_DIRS external/imgui external/glm external/tinyxml2 + external/lunasvg/include external/SDL/include src src/imgui @@ -127,6 +128,7 @@ set(CORE_INCLUDE_DIRS add_library(anm2ed_core STATIC ${CORE_SRC} ${TINYXML2_SRC} ${IMGUI_CORE_SRC}) target_include_directories(anm2ed_core PUBLIC ${CORE_INCLUDE_DIRS}) +target_link_libraries(anm2ed_core PUBLIC lunasvg) target_compile_definitions(anm2ed_core PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS IMGUI_DEBUG_PARANOID IMGUI_ENABLE_DOCKING) # windows.h otherwise defines min/max macros that break std::min/std::max. if(WIN32) diff --git a/src/canvas.cpp b/src/canvas.cpp index 109cc67..6d0c245 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -311,8 +311,8 @@ namespace anm2ed auto image = image_get(draw); if (!image || !image->is_valid() || frame.size == vec2()) continue; auto customShader = shader_get ? shader_get(frame.shaderId) : nullptr; - layer_render(customShader ? *customShader : shader, texture::id_get(*image), vec2(image->size), transform, draw, - frame.tint, frame.colorOffset); + layer_render(customShader ? *customShader : shader, texture::id_get(*image), image->unit_size_get(), transform, + draw, frame.tint, frame.colorOffset); } } diff --git a/src/cli.cpp b/src/cli.cpp index 4865b64..fa03af6 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -180,10 +180,10 @@ options: auto issues = model::isaac_issues_get(model); std::println("isaac issues: {} eased frames, {} group transforms, {} skewed frames, {} shader frames, {} depth " "frames, {} alpha offset frames, {} blurred frames, {} extra trigger events, {} trigger sounds, " - "{} animation layers", + "{} animation layers, {} vector spritesheets", issues.easedFrames, issues.groupTransforms, issues.skewFrames, issues.shaderFrames, issues.depthFrames, issues.alphaOffsetFrames, issues.blurFrames, issues.extraEvents, issues.triggerSounds, - issues.animationLayers); + issues.animationLayers, issues.vectorSpritesheets); return 0; } diff --git a/src/document.cpp b/src/document.cpp index 35c772e..9c18f1b 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -1,6 +1,7 @@ #include "document.hpp" #include +#include #include #include #include @@ -31,6 +32,8 @@ using namespace glm; namespace anm2ed::document { constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; + constexpr int VECTOR_LEVEL_MAX = 3; + constexpr int VECTOR_SIZE_MAX = 8192; constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; // A path written in a document in `directory`, as an absolute path. @@ -364,6 +367,15 @@ namespace anm2ed std::erase_if(shaders, is_invalid); std::erase_if(shaderVertexPaths, is_invalid); std::erase_if(shaderFragmentPaths, is_invalid); + + // Vector images drawn from spritesheet images no longer in use are dropped. + std::set imageUids{}; + for (const auto& spritesheet : model.content.spritesheets) + if (auto image = texture_get(spritesheet.id)) imageUids.insert(image->uid); + for (const auto& [path, library] : libraries) + for (const auto& [id, image] : library.images) + imageUids.insert(image.uid); + std::erase_if(vectorImages, [&](const auto& pair) { return !imageUids.contains(pair.first.first); }); } std::filesystem::path Document::library_path_get(int id) const @@ -400,16 +412,23 @@ namespace anm2ed return names; } - const resource::Image* Document::draw_image_get(const model::Draw& draw) const + // A layer draw's spritesheet image; a vector one is drawn again (cached) when `scale` canvas pixels show each pixel. + const resource::Image* Document::draw_image_get(const model::Draw& draw, float scale) const { - if (!draw.source || draw.source == &model) return texture_get(draw.spritesheetId); + const resource::Image* image{}; + if (!draw.source || draw.source == &model) image = texture_get(draw.spritesheetId); for (const auto& [path, library] : libraries) if (&library.model == draw.source) - { - auto image = library.images.find(draw.spritesheetId); - return image == library.images.end() ? nullptr : &image->second; - } - return nullptr; + if (auto found = library.images.find(draw.spritesheetId); found != library.images.end()) image = &found->second; + if (!image || !image->is_vector() || scale <= 1.0f) return image; + + auto level = std::min((int)std::ceil(std::log2(scale)), document::VECTOR_LEVEL_MAX); + while (level > 0 && std::max(image->size.x, image->size.y) << level > document::VECTOR_SIZE_MAX) + --level; + if (level == 0) return image; + auto [it, isNew] = vectorImages.try_emplace({image->uid, level}); + if (isNew) it->second = image->vector_render(image->scale * (float)(1 << level)); + return &it->second; } // Loads every library this document reaches (libraries' own libraries too) and forgets the ones it no longer does. @@ -447,7 +466,7 @@ namespace anm2ed document::library_load(path, library); isReloaded = true; } - if (isReloaded) libraries_sync(); + if (isReloaded) assets_sync(); return isReloaded; } @@ -468,7 +487,7 @@ namespace anm2ed resource::Image* Document::texture_edit(int id) { auto texture = texture_get(id); - if (!texture) return nullptr; + if (!texture || texture->is_vector()) return nullptr; return &textureDrafts.try_emplace(id, *texture).first->second; } @@ -501,7 +520,8 @@ namespace anm2ed bool Document::spritesheet_pack(int id, int padding) { auto texture = texture_get(id); - auto packed = texture ? edit::spritesheet_pack(model, id, *texture, padding) : std::nullopt; + auto packed = + texture && !texture->is_vector() ? edit::spritesheet_pack(model, id, *texture, padding) : std::nullopt; if (!packed) return false; texture_set(id, std::move(*packed)); assets_sync(); @@ -511,6 +531,7 @@ 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); diff --git a/src/document.hpp b/src/document.hpp index 12ee512..4a4ea28 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -76,6 +76,8 @@ namespace anm2ed // Libraries by absolute path, and what each (document, library id) points at (nullptr is this document). std::map libraries{}; std::map, const LibraryData*> libraryLinks{}; + // Vector spritesheets drawn again for zooms past 100%, by (image uid, power-of-two level). + mutable std::map, resource::Image> vectorImages{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; }; @@ -126,7 +128,7 @@ namespace anm2ed const LibraryData* library_get(const model::Model&, int) const; model::LibraryGet library_resolver_get() const; std::vector animation_names_get(int) const; - const resource::Image* draw_image_get(const model::Draw&) const; + const resource::Image* draw_image_get(const model::Draw&, float = 1.0f) const; void libraries_sync(); bool libraries_reload(); void library_reload(int); diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 6a3a2ad..1e5317f 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -391,7 +391,8 @@ namespace anm2ed::imgui {issues.blurFrames, FORMAT_ISAAC_BLUR_FRAMES}, {issues.extraEvents, FORMAT_ISAAC_EXTRA_EVENTS}, {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}, - {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}}) + {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}, + {issues.vectorSpritesheets, FORMAT_ISAAC_VECTOR_SPRITESHEETS}}) if (count > 0) ImGui::BulletText("%s", localize_format(format, count).c_str()); } ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_EDITOR_COPY)); diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 297f77c..e2356e8 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -715,10 +715,11 @@ namespace anm2ed::imgui } else if (draw.type == model::DrawType::LAYER) { - auto layerTexture = sampleDocument.draw_image_get(draw); + auto layerTexture = + sampleDocument.draw_image_get(draw, math::percent_to_unit(viewZoom) * model::draw_scale_get(draw)); if (!layerTexture || !layerTexture->is_valid() || layerTexture->size.x <= 0 || layerTexture->size.y <= 0) continue; - auto textureSize = vec2(layerTexture->size); + auto textureSize = layerTexture->unit_size_get(); auto layerModel = model::draw_quad_model_get(draw); auto layerTransform = transform * layerModel; auto tint = frame.tint; diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index 19b7f5c..435761f 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -38,7 +38,7 @@ namespace anm2ed::imgui { auto spritesheet = spritesheet_get(document, id); auto texture = document.texture_get(id); - if (!spritesheet || !texture) continue; + if (!spritesheet || !texture || texture->is_vector()) continue; auto pathString = path::to_utf8(spritesheet->path); WorkingDirectory workingDirectory(document.directory_get()); path::ensure_directory(spritesheet->path.parent_path()); diff --git a/src/model/draw.cpp b/src/model/draw.cpp index e0a5b21..334cb05 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -20,6 +20,14 @@ namespace anm2ed::model frame.rotation, math::percent_to_unit(frame.skew)); } + // How many canvas pixels one spritesheet pixel of a layer draw covers (along its longer axis). + float draw_scale_get(const Draw& draw) + { + auto model = draw.parent * draw_quad_model_get(draw); + auto size = glm::max(draw.frame.size, glm::vec2(1.0f)); + return std::max(glm::length(glm::vec2(model[0])) / size.x, glm::length(glm::vec2(model[1])) / size.y); + } + // When an item is drawn: now, and for each sample its time if the track has a frame there. std::vector> draw_times_get(const Animation& animation, const Track& track, const DrawOptions& options) diff --git a/src/model/draw.hpp b/src/model/draw.hpp index f514cae..68512cc 100644 --- a/src/model/draw.hpp +++ b/src/model/draw.hpp @@ -53,5 +53,6 @@ namespace anm2ed::model }; glm::mat4 draw_quad_model_get(const Draw&); + float draw_scale_get(const Draw&); std::vector animation_draws_get(const Model&, const Animation&, const DrawOptions&); } diff --git a/src/model/xml.cpp b/src/model/xml.cpp index 77c524d..b513bf0 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -13,6 +13,7 @@ #include "file.hpp" #include "frames.hpp" +#include "image.hpp" #include "math.hpp" #include "path.hpp" #include "time.hpp" @@ -1373,6 +1374,9 @@ namespace anm2ed::model { IsaacIssues issues{}; issues.animationLayers = (int)std::ranges::count_if(model.content.layers, &Layer::is_animation); + issues.vectorSpritesheets = + (int)std::ranges::count_if(model.content.spritesheets, [](const Spritesheet& spritesheet) + { return path::is_extension(spritesheet.path, resource::image::SVG_EXTENSION); }); for (auto [index, animation] : model.animations_get()) { for (const auto* entries : {&animation->layers, &animation->nulls}) diff --git a/src/model/xml.hpp b/src/model/xml.hpp index 9deb0fa..2cca0cb 100644 --- a/src/model/xml.hpp +++ b/src/model/xml.hpp @@ -21,6 +21,7 @@ namespace anm2ed::model int triggerSounds{}; int extraEvents{}; int animationLayers{}; + int vectorSpritesheets{}; bool operator==(const IsaacIssues&) const = default; }; diff --git a/src/render.cpp b/src/render.cpp index 18c3689..472d2bb 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -327,7 +327,8 @@ namespace anm2ed::render canvas.layers_render( shader, document.model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = document.library_resolver_get()}, - canvas.transform_get(zoom, pan), [&](const model::Draw& draw) { return document.draw_image_get(draw); }, + canvas.transform_get(zoom, pan), + [&](const model::Draw& draw) { return document.draw_image_get(draw, scale * model::draw_scale_get(draw)); }, [&](int id) { return document.shader_get(id); }); auto pixels = canvas.pixels_get(); canvas.unbind(); diff --git a/src/resource/image.cpp b/src/resource/image.cpp index 38204fe..97d9ab8 100644 --- a/src/resource/image.cpp +++ b/src/resource/image.cpp @@ -23,8 +23,11 @@ #pragma GCC diagnostic pop #endif +#include + #include "file.hpp" #include "math.hpp" +#include "path.hpp" #include "uid.hpp" using namespace anm2ed::resource::image; @@ -34,8 +37,30 @@ using namespace glm; namespace anm2ed::resource { + bool Image::is_valid() const { return !pixels.empty(); } + bool Image::is_vector() const { return svg != nullptr; } + + glm::vec2 Image::unit_size_get() const { return glm::vec2(size) / scale; } + + // An SVG drawn at about `scale` pixels per unit (exactly, after rounding to whole pixels); nothing if it won't parse. + Image svg_render(std::shared_ptr svg, float scale) + { + auto document = svg ? lunasvg::Document::loadFromData(*svg) : nullptr; + if (!document || document->width() <= 0.0f) return {}; + auto size = glm::max(ivec2(glm::ceil(vec2(document->width(), document->height()) * scale)), ivec2(1)); + auto bitmap = document->renderToBitmap(size.x, size.y); + if (bitmap.isNull()) return {}; + bitmap.convertToRGBA(); + Image image(bitmap.data(), size, true); + image.svg = std::move(svg); + image.scale = (float)size.x / document->width(); + return image; + } + + Image Image::vector_render(float scale) const { return svg_render(svg, scale); } + size_t Image::pixel_size_get() const { return size.x * size.y * CHANNELS; } Image::Image(const uint8_t* data, ivec2 size, bool isLinear) : isLinear(isLinear) @@ -62,6 +87,12 @@ namespace anm2ed::resource Image::Image(const std::filesystem::path& pngPath) { + 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()) { diff --git a/src/resource/image.hpp b/src/resource/image.hpp index 0f392d1..6cb095a 100644 --- a/src/resource/image.hpp +++ b/src/resource/image.hpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include @@ -10,11 +12,13 @@ namespace anm2ed::resource::image { constexpr auto CHANNELS = 4; + constexpr auto SVG_EXTENSION = "svg"; } namespace anm2ed::resource { - // CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. + // 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 { public: @@ -22,6 +26,8 @@ namespace anm2ed::resource std::vector pixels{}; bool isLinear{}; std::uint64_t uid{}; + std::shared_ptr svg{}; + float scale{1.0f}; Image() = default; Image(const uint8_t*, glm::ivec2, bool = false); @@ -29,6 +35,9 @@ namespace anm2ed::resource Image(const std::filesystem::path&); bool is_valid() const; + bool is_vector() const; + glm::vec2 unit_size_get() const; + Image vector_render(float) const; 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*); diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 5fbc1b7..7bccd66 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -242,6 +242,7 @@ namespace anm2ed X(FORMAT_ISAAC_SHADER_FRAMES, "{} frame(s) use shaders, which the game doesn't support; they will be dropped.", "{} Frame(s) usan shaders, que el juego no soporta; se descartarán.", "{} кадр(ов) используют шейдеры, которые игра не поддерживает; они будут отброшены.", "{} 个帧使用了着色器,游戏不支持,将被舍弃。", "프레임 {}개가 게임이 지원하지 않는 셰이더를 사용합니다. 셰이더는 제거됩니다.") \ X(FORMAT_ISAAC_SKEW_FRAMES, "{} frame(s) use skew, which the game doesn't support; it will be dropped.", "{} Frame(s) usan inclinación, que el juego no soporta; se descartará.", "{} кадр(ов) используют наклон, который игра не поддерживает; он будет отброшен.", "{} 个帧使用了斜切,游戏不支持,将被舍弃。", "프레임 {}개가 게임이 지원하지 않는 기울이기를 사용합니다. 기울이기는 제거됩니다.") \ X(FORMAT_ISAAC_TRIGGER_SOUNDS, "{} trigger(s) have sounds, which the game doesn't read from animations; they will be dropped.", "{} disparador(es) tienen sonidos, que el juego no lee de las animaciones; se descartarán.", "{} триггер(ов) имеют звуки, которые игра не читает из анимаций; они будут отброшены.", "{} 个触发器带有声音,游戏不会从动画中读取,将被舍弃。", "트리거 {}개에 게임이 애니메이션에서 읽지 않는 사운드가 있습니다. 사운드는 제거됩니다.") \ + X(FORMAT_ISAAC_VECTOR_SPRITESHEETS, "{} spritesheet(s) are SVGs, which the game can't load; export them as PNGs for it.", "{} spritesheet(s) son SVG, que el juego no puede cargar; expórtalos como PNG para él.", "{} спрайт-лист(ов) в формате SVG, который игра не может загрузить; экспортируйте их в PNG.", "{} 个图集是 SVG,游戏无法加载;请将其导出为 PNG。", "{}개의 스프라이트 시트가 SVG라서 게임에서 불러올 수 없습니다. PNG로 내보내세요.") \ X(FORMAT_LAYER_ANIMATION, "#{0} {1} (Animation: {2})", "#{0} {1} (Animación: {2})", "#{0} {1} (Анимация: {2})", "#{0} {1} (动画: {2})", "#{0} {1} (애니메이션: {2})") \ X(FORMAT_LIBRARY_ANIMATIONS, "Animations ({0})", "Animaciones ({0})", "Анимации ({0})", "动画 ({0})", "애니메이션 ({0})") \ X(FORMAT_ORIGIN, "Origin: {0}", "Origen: {0}", "Точка отсчета: {0}", "原点: {0}", "원점: {0}") \ diff --git a/tests/assets.cpp b/tests/assets.cpp index 9aec2a6..ee83043 100644 --- a/tests/assets.cpp +++ b/tests/assets.cpp @@ -58,3 +58,19 @@ TEST_CASE("AssetStore keys assets by content") CHECK(store.audio_add(AudioData(bytes, sizeof(bytes))) == audioKey); CHECK(store.audio_get(audioKey)->bytes.size() == sizeof(bytes)); } + +TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale") +{ + Image image(test::TEST_DIR / "render" / "vector.svg"); + REQUIRE(image.is_valid()); + CHECK(image.is_vector()); + CHECK(image.size == glm::ivec2(32, 16)); + auto red = image.pixel_read({8.0f, 8.0f}); + CHECK(red.r > 0.8f); + CHECK(red.b < 0.2f); + + auto large = image.vector_render(4.0f); + CHECK(large.size == glm::ivec2(128, 64)); + CHECK(large.unit_size_get() == image.unit_size_get()); + CHECK(large.uid != image.uid); +} diff --git a/tests/render/golden/vector_frame_0.png b/tests/render/golden/vector_frame_0.png new file mode 100644 index 0000000..a161792 Binary files /dev/null and b/tests/render/golden/vector_frame_0.png differ diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 910c93b..d5b4c1d 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -181,3 +181,26 @@ TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter") REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), blurred.data())); } + +TEST_CASE("SVG spritesheets draw sharp at any scale") +{ + RenderFixture fixture("vector.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); + + // Drawn at 600% (200% frames at a 3x render), the circle's edge stays within a pixel or two: just inside it is + // solid red, just outside it clear. + auto pixels = fixture.frame_get(0.0f); + auto inside = fixture.pixel_get(pixels, {-20.0f + 13.0f, 0.0f}); + auto outside = fixture.pixel_get(pixels, {-20.0f + 14.6f, 0.0f}); + CHECK(inside.r > 200); + CHECK(outside.r < 80); + + REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), + pixels.data())); + golden_image_check("vector_frame_0.png"); +} diff --git a/tests/render/vector.anm2 b/tests/render/vector.anm2 new file mode 100644 index 0000000..e9a38b9 --- /dev/null +++ b/tests/render/vector.anm2 @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/render/vector.svg b/tests/render/vector.svg new file mode 100644 index 0000000..ad1294b --- /dev/null +++ b/tests/render/vector.svg @@ -0,0 +1,4 @@ + + + +