SVG spritesheets

An .svg spritesheet loads through lunasvg (now part of the core library) at
one pixel per SVG unit, so regions, crops and picking work as for PNGs. The
preview, renders and CLI draw it again, cached per power-of-two zoom level up
to 8x, so it stays sharp when zoomed or scaled. Its pixels aren't edited
(pencil, eraser, pack and merge leave it alone, and Save skips it), and the
Isaac warning counts SVG sheets since the game can't load them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-08 17:41:57 -04:00
1 parent b31a28ebe9
commit a917d8ae97
21 files changed
+178 -21

No files matched your search

+2
View File
@@ -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)
+2 -2
View File
@@ -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);
}
}
+2 -2
View File
@@ -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;
}
+31 -10
View File
@@ -1,6 +1,7 @@
#include "document.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <format>
#include <limits>
@@ -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<std::uint64_t> 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<int>& 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);
+3 -1
View File
@@ -76,6 +76,8 @@ namespace anm2ed
// Libraries by absolute path, and what each (document, library id) points at (nullptr is this document).
std::map<std::filesystem::path, LibraryData> libraries{};
std::map<std::pair<const model::Model*, int>, const LibraryData*> libraryLinks{};
// Vector spritesheets drawn again for zooms past 100%, by (image uid, power-of-two level).
mutable std::map<std::pair<std::uint64_t, int>, 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<std::string> 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);
+2 -1
View File
@@ -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));
+3 -2
View File
@@ -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;
+1 -1
View File
@@ -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());
+8
View File
@@ -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<std::pair<int, float>> draw_times_get(const Animation& animation, const Track& track,
const DrawOptions& options)
+1
View File
@@ -53,5 +53,6 @@ namespace anm2ed::model
};
glm::mat4 draw_quad_model_get(const Draw&);
float draw_scale_get(const Draw&);
std::vector<Draw> animation_draws_get(const Model&, const Animation&, const DrawOptions&);
}
+4
View File
@@ -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})
+1
View File
@@ -21,6 +21,7 @@ namespace anm2ed::model
int triggerSounds{};
int extraEvents{};
int animationLayers{};
int vectorSpritesheets{};
bool operator==(const IsaacIssues&) const = default;
};
+2 -1
View File
@@ -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();
+31
View File
@@ -23,8 +23,11 @@
#pragma GCC diagnostic pop
#endif
#include <lunasvg.h>
#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<const std::string> 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<std::string>();
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())
{
+10 -1
View File
@@ -3,6 +3,8 @@
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <string>
#include <vector>
#include <glm/glm.hpp>
@@ -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<uint8_t> pixels{};
bool isLinear{};
std::uint64_t uid{};
std::shared_ptr<const std::string> 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*);
+1
View File
@@ -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}") \
+16
View File
@@ -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);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

+23
View File
@@ -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");
}
+31
View File
@@ -0,0 +1,31 @@
<AnimatedActor>
<Info CreatedBy="fixture" CreatedOn="01/01/2026 12:00:00 PM" Fps="30" Version="2" ExtendedVersion="1"/>
<Content>
<Spritesheets>
<Spritesheet Id="0" Path="vector.svg"/>
</Spritesheets>
<Layers>
<Layer Id="0" Name="circle" SpritesheetId="0"/>
<Layer Id="1" Name="square" SpritesheetId="0"/>
</Layers>
<Nulls/>
<Events/>
</Content>
<Animations DefaultAnimation="Big">
<Animation Name="Big" FrameNum="1" Loop="true">
<RootAnimation>
<Frame XPosition="0" YPosition="0" Delay="1" Visible="true" XScale="100" YScale="100" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</RootAnimation>
<LayerAnimations>
<LayerAnimation LayerId="0" Visible="true">
<Frame XPivot="8" YPivot="8" XCrop="0" YCrop="0" Width="16" Height="16" XPosition="-20" YPosition="0" Delay="1" Visible="true" XScale="200" YScale="200" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</LayerAnimation>
<LayerAnimation LayerId="1" Visible="true">
<Frame XPivot="8" YPivot="8" XCrop="16" YCrop="0" Width="16" Height="16" XPosition="20" YPosition="0" Delay="1" Visible="true" XScale="200" YScale="200" RedTint="255" GreenTint="255" BlueTint="255" AlphaTint="255" RedOffset="0" GreenOffset="0" BlueOffset="0" Rotation="0" Interpolated="false"/>
</LayerAnimation>
</LayerAnimations>
<NullAnimations/>
<Triggers/>
</Animation>
</Animations>
</AnimatedActor>
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="16" viewBox="0 0 32 16">
<circle cx="8" cy="8" r="7" fill="#e02020"/>
<rect x="17" y="1" width="14" height="14" fill="#2040e0" transform="rotate(20 24 8)"/>
</svg>

After

Width:  |  Height:  |  Size: 227 B