Format like smack-a-brother, and write comments as sentences

Four-space indents, braces on their own lines, and one-statement bodies without braces.
Semicolons in comments became full stops.
Designated initializers may leave fields out without a warning.
This commit is contained in:
shweet committed 2026-11-22 17:30:03 -05:00
1 parent 40f6b554b5
commit 7afdf709c3
176 files changed
+20500 -19048

No files matched your search

+91 -90
View File
@@ -10,127 +10,128 @@
TEST_CASE("Image png round trip and uid tracking")
{
const std::vector<uint8_t> pixels = {255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40};
Image image(pixels.data(), {2, 2});
REQUIRE(image.is_valid());
const std::vector<uint8_t> pixels = {255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40};
Image image(pixels.data(), {2, 2});
REQUIRE(image.is_valid());
auto path = std::filesystem::temp_directory_path() / "anm2ed_test_image.png";
REQUIRE(image.write_png(path));
Image loaded(path);
std::filesystem::remove(path);
CHECK(loaded.size == image.size);
CHECK(loaded.pixels == image.pixels);
CHECK(loaded.uid != image.uid);
auto path = std::filesystem::temp_directory_path() / "anm2ed_test_image.png";
REQUIRE(image.write_png(path));
Image loaded(path);
std::filesystem::remove(path);
CHECK(loaded.size == image.size);
CHECK(loaded.pixels == image.pixels);
CHECK(loaded.uid != image.uid);
auto copy = image;
CHECK(copy.uid == image.uid);
copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f});
CHECK(copy.uid != image.uid);
CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f));
auto copy = image;
CHECK(copy.uid == image.uid);
copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f});
CHECK(copy.uid != image.uid);
CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f));
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}));
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}));
}
TEST_CASE("AudioData holds file bytes")
{
const unsigned char bytes[] = {'R', 'I', 'F', 'F'};
AudioData audio(bytes, sizeof(bytes));
CHECK(audio.is_valid());
CHECK(audio.uid != 0);
CHECK_FALSE(AudioData(std::filesystem::path("missing.wav")).is_valid());
const unsigned char bytes[] = {'R', 'I', 'F', 'F'};
AudioData audio(bytes, sizeof(bytes));
CHECK(audio.is_valid());
CHECK(audio.uid != 0);
CHECK_FALSE(AudioData(std::filesystem::path("missing.wav")).is_valid());
}
TEST_CASE("AssetStore keys assets by content")
{
AssetStore store = {};
const std::vector<uint8_t> pixels = {1, 2, 3, 4};
auto key = store.image_add(Image(pixels.data(), {1, 1}));
CHECK(key != 0);
CHECK(store.image_add(Image(pixels.data(), {1, 1})) == key);
CHECK(store.image_add(Image(pixels.data(), {1, 1}, true)) != key);
REQUIRE(store.image_get(key));
CHECK(store.image_get(key)->pixels == pixels);
CHECK_FALSE(store.image_get(key + 1));
AssetStore store = {};
const std::vector<uint8_t> pixels = {1, 2, 3, 4};
auto key = store.image_add(Image(pixels.data(), {1, 1}));
CHECK(key != 0);
CHECK(store.image_add(Image(pixels.data(), {1, 1})) == key);
CHECK(store.image_add(Image(pixels.data(), {1, 1}, true)) != key);
REQUIRE(store.image_get(key));
CHECK(store.image_get(key)->pixels == pixels);
CHECK_FALSE(store.image_get(key + 1));
const unsigned char bytes[] = {'O', 'g', 'g', 'S'};
auto audioKey = store.audio_add(AudioData(bytes, sizeof(bytes)));
CHECK(store.audio_add(AudioData(bytes, sizeof(bytes))) == audioKey);
CHECK(store.audio_get(audioKey)->bytes.size() == sizeof(bytes));
const unsigned char bytes[] = {'O', 'g', 'g', 'S'};
auto audioKey = store.audio_add(AudioData(bytes, sizeof(bytes)));
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_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);
Image image(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);
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);
}
TEST_CASE("SVG spritesheets compose into SVGs that draw the same")
{
Image vector(TEST_DIR / "render" / "vector.svg");
REQUIRE(vector.is_vector());
Image vector(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());
// 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<uint8_t> 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}));
// A PNG part is embedded as an image, pixel for pixel. Composing the result again still works.
const std::vector<uint8_t> 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}));
}
TEST_CASE("an SVG's shapes meet without a seam")
{
// Two rectangles of one color meeting at x 10.5: the pixel they share is solid, while the outer edge at 20.5 keeps
// its anti-aliasing.
auto text = std::make_shared<std::string>(R"(<svg xmlns="http://www.w3.org/2000/svg" width="24" height="4">
// Two rectangles of one color meeting at x 10.5: the pixel they share is solid, while the outer edge at 20.5 keeps
// its anti-aliasing.
auto text = std::make_shared<std::string>(R"(<svg xmlns="http://www.w3.org/2000/svg" width="24" height="4">
<rect x="0" y="0" width="10.5" height="4" fill="#804020"/>
<rect x="10.5" y="0" width="10" height="4" fill="#804020"/></svg>)");
auto path = std::filesystem::temp_directory_path() / "anm2ed_seam.svg";
file_save(path, *text);
Image image(path);
std::filesystem::remove(path);
REQUIRE(image.is_vector());
auto seam = image.pixel_read({10.0f, 2.0f});
CHECK(seam.a == 1.0f);
CHECK(glm::distance(glm::vec3(seam), glm::vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f);
CHECK(image.pixel_read({20.0f, 2.0f}).a < 1.0f);
auto path = std::filesystem::temp_directory_path() / "anm2ed_seam.svg";
file_save(path, *text);
Image image(path);
std::filesystem::remove(path);
REQUIRE(image.is_vector());
auto seam = image.pixel_read({10.0f, 2.0f});
CHECK(seam.a == 1.0f);
CHECK(glm::distance(glm::vec3(seam), glm::vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f);
CHECK(image.pixel_read({20.0f, 2.0f}).a < 1.0f);
}
TEST_CASE("Embedded resources load")
{
for (auto& info : FRIENDS)
{
INFO("friend: ", info.name);
Model model = {};
std::string errorString;
CHECK(model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString));
CHECK(model.animations_count_get() > 0);
CHECK(Image(info.png->data, info.png->size).is_valid());
}
for (auto& icon : ICONS)
CHECK(std::string_view((const char*)icon.svg->data, icon.svg->size).starts_with("<svg"));
for (auto& font : FONTS)
CHECK(font->size > 0);
for (auto& info : FRIENDS)
{
INFO("friend: ", info.name);
Model model = {};
std::string errorString;
CHECK(model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString));
CHECK(model.animations_count_get() > 0);
CHECK(Image(info.png->data, info.png->size).is_valid());
}
for (auto& icon : ICONS)
CHECK(std::string_view((const char*)icon.svg->data, icon.svg->size).starts_with("<svg"));
for (auto& font : FONTS)
CHECK(font->size > 0);
}
+57 -53
View File
@@ -12,84 +12,88 @@
#include "model/json.h"
#include "model/xml.h"
inline const std::filesystem::path TEST_DIR = ANM2ED_TEST_DIR;
inline const std::filesystem::path CORPUS_DIR = TEST_DIR / "corpus";
inline const std::filesystem::path GOLDEN_DIR = TEST_DIR / "golden";
inline const std::filesystem::path TEST_DIR = ANM2ED_TEST_DIR;
inline const std::filesystem::path CORPUS_DIR = TEST_DIR / "corpus";
inline const std::filesystem::path GOLDEN_DIR = TEST_DIR / "golden";
inline constexpr std::pair<const char*, Flags> PRESETS[] = {{"default", SERIALIZE_DEFAULT},
{"editor", SERIALIZE_EDITOR_DEFAULT},
{"isaac", SERIALIZE_ISAAC_DEFAULT},
{"anm2ed", SERIALIZE_ANM2ED_DEFAULT}};
inline constexpr std::pair<const char*, Merge> MERGES[] = {{"merge_prepend", MERGE_PREPEND},
{"merge_append", MERGE_APPEND},
{"merge_replace", MERGE_REPLACE},
{"merge_ignore", MERGE_IGNORE}};
inline constexpr std::pair<const char*, Flags> PRESETS[] = {{"default", SERIALIZE_DEFAULT},
{"editor", SERIALIZE_EDITOR_DEFAULT},
{"isaac", SERIALIZE_ISAAC_DEFAULT},
{"anm2ed", SERIALIZE_ANM2ED_DEFAULT}};
inline constexpr std::pair<const char*, Merge> MERGES[] = {{"merge_prepend", MERGE_PREPEND},
{"merge_append", MERGE_APPEND},
{"merge_replace", MERGE_REPLACE},
{"merge_ignore", MERGE_IGNORE}};
using Variant = std::pair<std::string, std::string>;
using Variant = std::pair<std::string, std::string>;
inline std::string file_load(const std::filesystem::path& path)
{
inline std::string file_load(const std::filesystem::path& path)
{
std::ifstream file(path, std::ios::binary);
return {std::istreambuf_iterator<char>(file), {}};
}
}
inline void file_save(const std::filesystem::path& path, const std::string& text)
{
inline void file_save(const std::filesystem::path& path, const std::string& text)
{
std::filesystem::create_directories(path.parent_path());
std::ofstream(path, std::ios::binary) << text;
}
}
inline bool is_env_set(const char* name) { return std::getenv(name) != nullptr; }
inline bool is_env_set(const char* name)
{
return std::getenv(name) != nullptr;
}
inline std::vector<std::filesystem::path> fixtures_get()
{
inline std::vector<std::filesystem::path> fixtures_get()
{
std::vector<std::filesystem::path> fixtures;
for (auto& entry : std::filesystem::directory_iterator(CORPUS_DIR))
if (entry.path().extension() == ".anm2") fixtures.push_back(entry.path());
if (entry.path().extension() == ".anm2")
fixtures.push_back(entry.path());
std::ranges::sort(fixtures);
return fixtures;
}
}
inline Model model_load(const std::string& text)
{
inline Model model_load(const std::string& text)
{
Model model = {};
REQUIRE(model_load_string(model, text));
return model;
}
}
// Every serialization and merge the editor can produce for a document; goldens lock each one down.
inline std::vector<Variant> variants_get(const Model& model)
{
// Every serialization and merge the editor can produce for a document. Goldens lock each one down.
inline std::vector<Variant> variants_get(const Model& model)
{
std::vector<Variant> variants;
for (auto [name, flags] : PRESETS)
variants.emplace_back(name, model_serialize(model, flags));
variants.emplace_back(name, model_serialize(model, flags));
variants.emplace_back("save", model_to_string(model));
for (auto [name, type] : MERGES)
{
auto merged = model;
std::set<int> sources = {0, 1, 2};
animations_merge(merged, 0, sources, type, type == MERGE_PREPEND || type == MERGE_REPLACE,
{});
variants.emplace_back(name, model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT));
auto merged = model;
std::set<int> sources = {0, 1, 2};
animations_merge(merged, 0, sources, type, type == MERGE_PREPEND || type == MERGE_REPLACE, {});
variants.emplace_back(name, model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT));
}
return variants;
}
}
// The outer document of a save with its SourceDocument (the root's last child, on lines of its own) removed: what
// the game reads.
inline std::string game_document_get(std::string text)
{
// The outer document of a save with its SourceDocument (the root's last child, on lines of its own) removed: what
// the game reads.
inline std::string game_document_get(std::string text)
{
constexpr std::string_view END = "</SourceDocument>";
auto start = text.find("\n <SourceDocument");
if (start != std::string::npos) text.erase(start, text.find(END, start) + END.size() - start);
if (start != std::string::npos)
text.erase(start, text.find(END, start) + END.size() - start);
return text;
}
}
// Save/reload properties every document must hold.
inline void invariants_check(const Model& model)
{
// Save/reload properties every document must hold.
inline void invariants_check(const Model& model)
{
// The first save may repair invalid input (dangling ids, duplicates); after that, saves must be fixed points.
// The first save may repair invalid input (dangling ids, duplicates). After that, saves must be fixed points.
auto text = model_to_string(model);
auto reloaded = model_load(text);
auto resaved = model_to_string(reloaded);
@@ -99,17 +103,17 @@
// Loading only the game's view and re-saving it for the game must not change it.
auto game = game_document_get(model_to_string(model));
CHECK(model_serialize(model_load(game), SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS) == game);
}
}
// Compares against a stored golden; ANM2ED_UPDATE_GOLDEN (or a missing golden when isBootstrap) rewrites it.
inline void golden_check(const std::filesystem::path& path, const std::string& text, bool isBootstrap = false)
{
// Compares against a stored golden. ANM2ED_UPDATE_GOLDEN (or a missing golden when isBootstrap) rewrites it.
inline void golden_check(const std::filesystem::path& path, const std::string& text, bool isBootstrap = false)
{
if (is_env_set("ANM2ED_UPDATE_GOLDEN") || (isBootstrap && !std::filesystem::exists(path)))
{
file_save(path, text);
return;
file_save(path, text);
return;
}
INFO("golden: ", path.string());
REQUIRE(std::filesystem::exists(path));
CHECK(file_load(path) == text);
}
}
+20 -19
View File
@@ -4,25 +4,26 @@
// ANM2ED_CORPUS_BASELINE (default ~/.cache/anm2ed/corpus) and compared on every later run. Nothing here is committed.
TEST_CASE("local corpus matches baselines" * doctest::skip(!is_env_set("ANM2ED_CORPUS")))
{
auto baseline = is_env_set("ANM2ED_CORPUS_BASELINE")
? std::filesystem::path(std::getenv("ANM2ED_CORPUS_BASELINE"))
: std::filesystem::path(std::getenv("HOME")) / ".cache/anm2ed/corpus";
std::istringstream list(file_load(std::getenv("ANM2ED_CORPUS")));
std::string line;
while (std::getline(list, line))
{
if (line.empty()) continue;
INFO("file: ", line);
auto key = std::format("{:016x}", std::hash<std::string>{}(line));
Model anm2 = {};
std::string error;
if (!model_load(anm2, line, &error))
auto baseline = is_env_set("ANM2ED_CORPUS_BASELINE")
? std::filesystem::path(std::getenv("ANM2ED_CORPUS_BASELINE"))
: std::filesystem::path(std::getenv("HOME")) / ".cache/anm2ed/corpus";
std::istringstream list(file_load(std::getenv("ANM2ED_CORPUS")));
std::string line;
while (std::getline(list, line))
{
golden_check(baseline / (key + ".error.txt"), error, true);
continue;
if (line.empty())
continue;
INFO("file: ", line);
auto key = std::format("{:016x}", std::hash<std::string>{}(line));
Model anm2 = {};
std::string error;
if (!model_load(anm2, line, &error))
{
golden_check(baseline / (key + ".error.txt"), error, true);
continue;
}
for (auto& [name, text] : variants_get(anm2))
golden_check(baseline / std::format("{}.{}.xml", key, name), text, true);
invariants_check(anm2);
}
for (auto& [name, text] : variants_get(anm2))
golden_check(baseline / std::format("{}.{}.xml", key, name), text, true);
invariants_check(anm2);
}
}
+174 -174
View File
@@ -6,210 +6,212 @@
TEST_CASE("draw lists put the root first and each item's onion samples before it")
{
auto anm2 = model_load(file_load(CORPUS_DIR / "02_items.anm2"));
auto& animation = *anm2.animation_get(0);
auto draws = animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}});
REQUIRE(!draws.empty());
CHECK(draws.front().type == DrawType::ROOT);
auto anm2 = model_load(file_load(CORPUS_DIR / "02_items.anm2"));
auto& animation = *anm2.animation_get(0);
auto draws = animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}});
REQUIRE(!draws.empty());
CHECK(draws.front().type == DrawType::ROOT);
for (int i = 0; i + 1 < (int)draws.size(); ++i)
if (draws[i].sample != -1) CHECK((draws[i + 1].id == draws[i].id && draws[i + 1].type == draws[i].type));
for (int i = 0; i + 1 < (int)draws.size(); ++i)
if (draws[i].sample != -1)
CHECK((draws[i + 1].id == draws[i].id && draws[i + 1].type == draws[i].type));
auto layerDraws = std::ranges::count_if(draws, [](const Draw& draw)
{ return draw.type == DrawType::LAYER && draw.sample == -1; });
CHECK(layerDraws > 0);
CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f));
auto layerDraws = std::ranges::count_if(
draws, [](const Draw& draw) { return draw.type == DrawType::LAYER && draw.sample == -1; });
CHECK(layerDraws > 0);
CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f));
}
TEST_CASE("root transforms fold into layer draws")
{
auto anm2 = model_load(file_load(CORPUS_DIR / "04_group_root_transform.anm2"));
auto& animation = *anm2.animation_get(0);
auto plain = animation_draws_get(anm2, animation, {});
auto rooted = animation_draws_get(anm2, animation, {.isRootTransform = true});
REQUIRE(plain.size() == rooted.size());
bool isAnyMoved = false;
for (int i = 0; i < (int)plain.size(); ++i)
isAnyMoved |= plain[i].type == DrawType::LAYER && plain[i].parent != rooted[i].parent;
CHECK(isAnyMoved);
auto anm2 = model_load(file_load(CORPUS_DIR / "04_group_root_transform.anm2"));
auto& animation = *anm2.animation_get(0);
auto plain = animation_draws_get(anm2, animation, {});
auto rooted = animation_draws_get(anm2, animation, {.isRootTransform = true});
REQUIRE(plain.size() == rooted.size());
bool isAnyMoved = false;
for (int i = 0; i < (int)plain.size(); ++i)
isAnyMoved |= plain[i].type == DrawType::LAYER && plain[i].parent != rooted[i].parent;
CHECK(isAnyMoved);
}
TEST_CASE("a layer frame's depth moves it among the layers for that frame only")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
auto layer_ids_get = [&](float time)
{
std::vector<int> ids;
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {.time = time}))
if (draw.type == DrawType::LAYER) ids.push_back(draw.id);
return ids;
};
CHECK(layer_ids_get(0.0f) == std::vector{1, 0});
auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
auto layer_ids_get = [&](float time) {
std::vector<int> ids;
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {.time = time}))
if (draw.type == DrawType::LAYER)
ids.push_back(draw.id);
return ids;
};
CHECK(layer_ids_get(0.0f) == std::vector{1, 0});
anm2.frame_edit({0, LAYER, 0, 0})->depth = -1;
CHECK(layer_ids_get(0.0f) == std::vector{0, 1});
CHECK(layer_ids_get(5.0f) == std::vector{1, 0});
anm2.frame_edit({0, LAYER, 0, 0})->depth = -1;
CHECK(layer_ids_get(0.0f) == std::vector{0, 1});
CHECK(layer_ids_get(5.0f) == std::vector{1, 0});
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("Depth") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1);
CHECK(isaac_issues_get(anm2).depthFrames == 1);
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("Depth") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1);
CHECK(isaac_issues_get(anm2).depthFrames == 1);
}
TEST_CASE("a layer frame's blur reaches its child's draws and stays out of the game's copy")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f;
bool isAnyChild = false;
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {}))
if (draw.type == DrawType::LAYER && draw.id == 1)
{
isAnyChild = true;
CHECK(draw.frame.blur >= 6.0f);
}
CHECK(isAnyChild);
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f;
bool isAnyChild = false;
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {}))
if (draw.type == DrawType::LAYER && draw.id == 1)
{
isAnyChild = true;
CHECK(draw.frame.blur >= 6.0f);
}
CHECK(isAnyChild);
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("Blur") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f);
CHECK(isaac_issues_get(anm2).blurFrames == 1);
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("Blur") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f);
CHECK(isaac_issues_get(anm2).blurFrames == 1);
}
TEST_CASE("an animation layer draws its child animation, from this file or a library")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
DrawOptions options = {.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }};
auto red_position_get = [&](int layerId)
{
std::optional<glm::vec2> position{};
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), options))
if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2())
position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f));
return position;
};
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
DrawOptions options = {.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }};
auto red_position_get = [&](int layerId) {
std::optional<glm::vec2> position{};
for (auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), options))
if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2())
position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f));
return position;
};
// The library's red square, half size at (40, 0), starts on its fifth frame (at x 16).
CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f));
// This file's Inner holds its first frame however far the parent plays.
options.time = 1.0f;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
// An animation never draws inside itself.
CHECK_FALSE(red_position_get(3));
// The library's red square, half size at (40, 0), starts on its fifth frame (at x 16).
CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f));
// This file's Inner holds its first frame however far the parent plays.
options.time = 1.0f;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
// An animation never draws inside itself.
CHECK_FALSE(red_position_get(3));
// Once stops on the child's last frame; Loop wraps around it.
options.time = 6.0f;
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f));
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
// Once stops on the child's last frame. Loop wraps around it.
options.time = 6.0f;
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f));
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
// Without the library loaded, its layer draws nothing.
options.library_get = {};
CHECK_FALSE(red_position_get(0));
// Without the library loaded, its layer draws nothing.
options.library_get = {};
CHECK_FALSE(red_position_get(0));
auto text = model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT);
CHECK(model_hash(model_load(text)) == model_hash(anm2));
CHECK(isaac_issues_get(anm2).animationLayers == 3);
CHECK(game_document_get(model_to_string(anm2)).find(" Animation=\"") == std::string::npos);
auto text = model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT);
CHECK(model_hash(model_load(text)) == model_hash(anm2));
CHECK(isaac_issues_get(anm2).animationLayers == 3);
CHECK(game_document_get(model_to_string(anm2)).find(" Animation=\"") == std::string::npos);
}
TEST_CASE("an alpha offset is kept by the editor's copy only")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
anm2.frame_edit({0, LAYER, 0, 0})->colorOffset.a = -0.5f;
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("AlphaOffset") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->colorOffset.a == doctest::Approx(-127.0f / 255.0f));
CHECK(isaac_issues_get(anm2).alphaOffsetFrames == 1);
auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
anm2.frame_edit({0, LAYER, 0, 0})->colorOffset.a = -0.5f;
auto text = model_to_string(anm2);
CHECK(game_document_get(text).find("AlphaOffset") == std::string::npos);
CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->colorOffset.a == doctest::Approx(-127.0f / 255.0f));
CHECK(isaac_issues_get(anm2).alphaOffsetFrames == 1);
}
TEST_CASE("only SVG spritesheets that layers show count against Rebirth")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "vector.anm2"));
CHECK(spritesheets_vector_used_get(anm2) == std::set{0});
anm2.content.layers.clear();
CHECK(spritesheets_vector_used_get(anm2).empty());
auto anm2 = model_load(file_load(TEST_DIR / "render" / "vector.anm2"));
CHECK(spritesheets_vector_used_get(anm2) == std::set{0});
anm2.content.layers.clear();
CHECK(spritesheets_vector_used_get(anm2).empty());
}
TEST_CASE("child animations fire their triggers as they reach them")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
spin.content.events.push_back({.id = 0, .name = "spun"});
spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}});
anm2.content.events.push_back({.id = 0, .name = "inner"});
anm2.animation_edit(1)->triggers.frames.push_back({.atFrame = 0, .eventIds = {0}});
auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; };
auto sources_get = [&](int time)
{
std::vector<const Model*> sources;
for (auto& fire : animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get))
sources.push_back(fire.source);
return sources;
};
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
spin.content.events.push_back({.id = 0, .name = "spun"});
spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}});
anm2.content.events.push_back({.id = 0, .name = "inner"});
anm2.animation_edit(1)->triggers.frames.push_back({.atFrame = 0, .eventIds = {0}});
auto library_get = [&](const Model&, int id) {
return id == 0 ? &spin : nullptr;
};
auto sources_get = [&](int time) {
std::vector<const Model*> sources;
for (auto& fire : animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get))
sources.push_back(fire.source);
return sources;
};
// Inner (held on its first frame) fires once, when the parent starts; the library's Spin, started on its fifth
// frame, reaches its sixth (and its trigger) one frame later.
CHECK(sources_get(0) == std::vector<const Model*>{&anm2});
CHECK(sources_get(1) == std::vector<const Model*>{&spin});
CHECK(sources_get(2).empty());
// Inner (held on its first frame) fires once, when the parent starts. The library's Spin, started on its fifth
// frame, reaches its sixth (and its trigger) one frame later.
CHECK(sources_get(0) == std::vector<const Model*>{&anm2});
CHECK(sources_get(1) == std::vector<const Model*>{&spin});
CHECK(sources_get(2).empty());
}
TEST_CASE("flattening animation layers bakes their children into plain layers that draw the same")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; };
auto flat =
animation_layers_flatten(anm2, library_get, [](const Model&, const std::filesystem::path& path)
{ return std::filesystem::path("library") / path; });
CHECK(std::ranges::none_of(flat.content.layers, &Layer::is_animation));
CHECK(flat.content.spritesheets.back().path == std::filesystem::path("library") / "sheet.png");
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
auto library_get = [&](const Model&, int id) {
return id == 0 ? &spin : nullptr;
};
auto flat = animation_layers_flatten(anm2, library_get, [](const Model&, const std::filesystem::path& path) {
return std::filesystem::path("library") / path;
});
CHECK(std::ranges::none_of(flat.content.layers, &Layer::is_animation));
CHECK(flat.content.spritesheets.back().path == std::filesystem::path("library") / "sheet.png");
// Every frame, the plain layers draw where the animation layers' children did.
auto points_get = [&](const Model& model, const LibraryGet& get, float time)
{
std::vector<glm::vec2> points{};
for (auto& draw :
animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get}))
if (draw.type == DrawType::LAYER)
points.push_back(glm::round(glm::vec2(draw.parent * draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1))));
std::ranges::sort(points, [](glm::vec2 a, glm::vec2 b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); });
return points;
};
for (float time = 0.0f; time < 8.0f; time += 1.0f)
CHECK(points_get(flat, {}, time) == points_get(anm2, library_get, time));
// Every frame, the plain layers draw where the animation layers' children did.
auto points_get = [&](const Model& model, const LibraryGet& get, float time) {
std::vector<glm::vec2> points{};
for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get}))
if (draw.type == DrawType::LAYER)
points.push_back(
glm::round(glm::vec2(draw.parent * draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1))));
std::ranges::sort(points, [](glm::vec2 a, glm::vec2 b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); });
return points;
};
for (float time = 0.0f; time < 8.0f; time += 1.0f)
CHECK(points_get(flat, {}, time) == points_get(anm2, library_get, time));
auto text = model_to_string(anm2, {.gameModel = &flat});
auto game = game_document_get(text);
CHECK(game.find(" Animation=\"") == std::string::npos);
CHECK(game.find("spin/red") != std::string::npos);
CHECK(std::ranges::count_if(model_load(text).content.layers, &Layer::is_animation) == 3);
auto text = model_to_string(anm2, {.gameModel = &flat});
auto game = game_document_get(text);
CHECK(game.find(" Animation=\"") == std::string::npos);
CHECK(game.find("spin/red") != std::string::npos);
CHECK(std::ranges::count_if(model_load(text).content.layers, &Layer::is_animation) == 3);
// Children's triggers join the flattened animation's, their events found (or added) by name.
spin.content.events.push_back({.id = 0, .name = "spun"});
spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}});
flat = animation_layers_flatten(anm2, library_get,
[](const Model&, const std::filesystem::path& path) { return path; });
auto& triggers = flat.animation_get(0)->triggers.frames;
REQUIRE(triggers.size() == 1);
CHECK(triggers.front().atFrame == 1);
CHECK(item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun");
// Children's triggers join the flattened animation's, their events found (or added) by name.
spin.content.events.push_back({.id = 0, .name = "spun"});
spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}});
flat = animation_layers_flatten(anm2, library_get,
[](const Model&, const std::filesystem::path& path) { return path; });
auto& triggers = flat.animation_get(0)->triggers.frames;
REQUIRE(triggers.size() == 1);
CHECK(triggers.front().atFrame == 1);
CHECK(item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun");
}
TEST_CASE("an animation layer's child sits where the layer's frame puts it")
{
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto placement = layer_child_transform_get(*anm2.animation_get(0), 0, 0.0f, true);
REQUIRE(placement);
CHECK(glm::vec2(*placement * glm::vec4(16.0f, 0.0f, 0.0f, 1.0f)) == glm::vec2(48.0f, 0.0f));
CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true));
auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto placement = layer_child_transform_get(*anm2.animation_get(0), 0, 0.0f, true);
REQUIRE(placement);
CHECK(glm::vec2(*placement * glm::vec4(16.0f, 0.0f, 0.0f, 1.0f)) == glm::vec2(48.0f, 0.0f));
CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true));
}
TEST_CASE("the game's copy stands in for depth and alpha offsets")
{
auto anm2 = model_load(R"({ "sheets": [ { "path": "a.png" } ],
auto anm2 = model_load(R"({ "sheets": [ { "path": "a.png" } ],
"layers": [ { "name": "a" }, { "name": "b" }, { "name": "c" } ],
"animations": { "A": { "length": 6, "layers": [
{ "layer": 0, "frames": [ { "crop": [0, 0], "size": [1, 1], "delay": 2 },
@@ -217,30 +219,28 @@ TEST_CASE("the game's copy stands in for depth and alpha offsets")
{ "crop": [1, 0], "size": [1, 1], "pos": [8, 0], "delay": 2, "depth": -1 } ] },
{ "layer": 1, "frames": [ { "crop": [2, 0], "size": [1, 1], "delay": 6, "depth": -1 } ] },
{ "layer": 2, "frames": [ { "crop": [3, 0], "size": [1, 1], "delay": 6, "offset": [0, 0, 0, -64] } ] } ] } } })");
auto game = isaac_bridge(anm2);
auto game = isaac_bridge(anm2);
// Every frame, the same crops draw in the same order and places, with no depth left.
auto draws_get = [](const Model& model, float time)
{
std::vector<std::pair<glm::vec2, glm::vec2>> draws{};
for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time}))
if (draw.type == DrawType::LAYER && draw.frame.isVisible)
draws.emplace_back(draw.frame.crop, draw.frame.position);
return draws;
};
for (float time = 0.0f; time < 6.0f; time += 0.5f)
CHECK(draws_get(game, time) == draws_get(anm2, time));
CHECK(isaac_issues_get(game).depthFrames == 0);
CHECK(
std::ranges::any_of(game.content.layers, [](const Layer& layer) { return layer.name == "a (depth +2)"; }));
// Every frame, the same crops draw in the same order and places, with no depth left.
auto draws_get = [](const Model& model, float time) {
std::vector<std::pair<glm::vec2, glm::vec2>> draws{};
for (auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time}))
if (draw.type == DrawType::LAYER && draw.frame.isVisible)
draws.emplace_back(draw.frame.crop, draw.frame.position);
return draws;
};
for (float time = 0.0f; time < 6.0f; time += 0.5f)
CHECK(draws_get(game, time) == draws_get(anm2, time));
CHECK(isaac_issues_get(game).depthFrames == 0);
CHECK(std::ranges::any_of(game.content.layers, [](const Layer& layer) { return layer.name == "a (depth +2)"; }));
// The alpha offset joins the alpha tint.
auto& offsetFrame = *game.frame_get({0, LAYER, 2, 0});
CHECK(offsetFrame.colorOffset.a == 0.0f);
CHECK(float_to_uint8(offsetFrame.tint.a) == 255 - 64);
// The alpha offset joins the alpha tint.
auto& offsetFrame = *game.frame_get({0, LAYER, 2, 0});
CHECK(offsetFrame.colorOffset.a == 0.0f);
CHECK(float_to_uint8(offsetFrame.tint.a) == 255 - 64);
// A document saved with Ignore and Save remembers it, in either format.
anm2.info.isIsaacIgnored = true;
CHECK(model_load(model_to_string(anm2)).info.isIsaacIgnored);
CHECK(model_load(model_to_json(anm2)).info.isIsaacIgnored);
// A document saved with Ignore and Save remembers it, in either format.
anm2.info.isIsaacIgnored = true;
CHECK(model_load(model_to_string(anm2)).info.isIsaacIgnored);
CHECK(model_load(model_to_json(anm2)).info.isIsaacIgnored);
}
+93 -93
View File
@@ -2,137 +2,137 @@
TEST_CASE("per-fixture invariants")
{
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.filename().string());
invariants_check(model_load(file_load(fixture)));
}
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.filename().string());
invariants_check(model_load(file_load(fixture)));
}
}
TEST_CASE("saved text escapes what it holds, and reads back the same")
{
auto model = model_load(file_load(CORPUS_DIR / "11_unknown.anm2"));
model.extras.children.emplace_back(
0, XmlNode{.tag = "Note",
.attributes = {{"Quote", "it's \"x\" & <y>"}},
.text = "a & b > c 'd' \"e\"",
.children = {{.tag = "Inner", .children = {{.tag = "Leaf", .attributes = {{"A", "1"}}}}}}});
auto text = model_to_string(model);
CHECK(text.find("Quote=\"it&apos;s &quot;x&quot; &amp; &lt;y&gt;\"") != std::string::npos);
CHECK(text.find(">a &amp; b &gt; c 'd' \"e\"<") != std::string::npos);
auto reloaded = model_load(text).extras.children;
auto note = std::ranges::find(reloaded, std::string("Note"), [](const auto& child) { return child.second.tag; });
REQUIRE(note != reloaded.end());
CHECK(note->second == model.extras.children.back().second);
auto model = model_load(file_load(CORPUS_DIR / "11_unknown.anm2"));
model.extras.children.emplace_back(
0, XmlNode{.tag = "Note",
.attributes = {{"Quote", "it's \"x\" & <y>"}},
.text = "a & b > c 'd' \"e\"",
.children = {{.tag = "Inner", .children = {{.tag = "Leaf", .attributes = {{"A", "1"}}}}}}});
auto text = model_to_string(model);
CHECK(text.find("Quote=\"it&apos;s &quot;x&quot; &amp; &lt;y&gt;\"") != std::string::npos);
CHECK(text.find(">a &amp; b &gt; c 'd' \"e\"<") != std::string::npos);
auto reloaded = model_load(text).extras.children;
auto note = std::ranges::find(reloaded, std::string("Note"), [](const auto& child) { return child.second.tag; });
REQUIRE(note != reloaded.end());
CHECK(note->second == model.extras.children.back().second);
}
TEST_CASE("saves leave out default colors, which read back the same")
{
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.string());
auto model = model_load(file_load(fixture));
auto text = model_to_string(model);
CHECK(text.find("Tint=\"255\"") == std::string::npos);
CHECK(text.find("Offset=\"0\"") == std::string::npos);
CHECK(model_hash(model_load(text)) == model_hash(model));
}
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.string());
auto model = model_load(file_load(fixture));
auto text = model_to_string(model);
CHECK(text.find("Tint=\"255\"") == std::string::npos);
CHECK(text.find("Offset=\"0\"") == std::string::npos);
CHECK(model_hash(model_load(text)) == model_hash(model));
}
}
TEST_CASE("JSON documents read back as the editor's copy")
{
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.string());
auto model = model_load(file_load(fixture));
auto text = model_to_json(model);
auto reloaded = model_load(text);
CHECK(model_to_json(reloaded) == text);
// Unknown XML, element order, dangling references and repeated animation names are not kept.
auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2";
if (!isQuirky)
CHECK(model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) ==
model_serialize(model, SERIALIZE_ANM2ED_DEFAULT));
}
for (auto& fixture : fixtures_get())
{
INFO("fixture: ", fixture.string());
auto model = model_load(file_load(fixture));
auto text = model_to_json(model);
auto reloaded = model_load(text);
CHECK(model_to_json(reloaded) == text);
// Unknown XML, element order, dangling references and repeated animation names are not kept.
auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2";
if (!isQuirky)
CHECK(model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) ==
model_serialize(model, SERIALIZE_ANM2ED_DEFAULT));
}
}
TEST_CASE("JSON animations get unique names")
{
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
model.animations.entries.push_back(model.animations.entries.front());
auto reloaded = model_load(model_to_json(model));
REQUIRE(reloaded.animations_count_get() == 2);
CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2");
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
model.animations.entries.push_back(model.animations.entries.front());
auto reloaded = model_load(model_to_json(model));
REQUIRE(reloaded.animations_count_get() == 2);
CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2");
}
TEST_CASE("JSON groups don't renumber an animation sharing their name")
{
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
auto animation = std::get<std::shared_ptr<const Animation>>(model.animations.entries.front());
model.animations.entries = {AnimationGroup{.name = animation->name, .animations = {animation}}};
auto reloaded = model_load(model_to_json(model));
REQUIRE(reloaded.animations_count_get() == 1);
CHECK(reloaded.animation_get(0)->name == animation->name);
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
auto animation = std::get<std::shared_ptr<const Animation>>(model.animations.entries.front());
model.animations.entries = {AnimationGroup{.name = animation->name, .animations = {animation}}};
auto reloaded = model_load(model_to_json(model));
REQUIRE(reloaded.animations_count_get() == 1);
CHECK(reloaded.animation_get(0)->name == animation->name);
}
TEST_CASE("JSON markers are a pair, and a frame's child an object only when it has one")
{
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
auto text = model_to_json(model);
CHECK(text.find("\"child\"") == std::string::npos);
model.animation_edit(0)->startMarker = 2;
model.animation_edit(0)->endMarker = 5;
auto frame = model.frame_edit({0, (int)ItemType::LAYER, 0, 0});
REQUIRE(frame);
frame->childMode = ChildMode::HOLD;
frame->childStart = 3;
text = model_to_json(model);
CHECK(text.find("\"markers\": [2, 5]") != std::string::npos);
CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos);
auto reloaded = model_load(text);
CHECK(reloaded.animation_get(0)->endMarker == 5);
CHECK(model_to_json(reloaded) == text);
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
auto text = model_to_json(model);
CHECK(text.find("\"child\"") == std::string::npos);
model.animation_edit(0)->startMarker = 2;
model.animation_edit(0)->endMarker = 5;
auto frame = model.frame_edit({0, (int)ItemType::LAYER, 0, 0});
REQUIRE(frame);
frame->childMode = ChildMode::HOLD;
frame->childStart = 3;
text = model_to_json(model);
CHECK(text.find("\"markers\": [2, 5]") != std::string::npos);
CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos);
auto reloaded = model_load(text);
CHECK(reloaded.animation_get(0)->endMarker == 5);
CHECK(model_to_json(reloaded) == text);
}
TEST_CASE("JSON dates are ISO 8601")
{
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
for (auto [date, iso] : {std::pair{"01/01/2026 12:00:00 PM", "2026-01-01T12:00:00"},
{"03/04/2025 12:30:05 AM", "2025-03-04T00:30:05"},
{"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}})
{
model.info.createdOn = date;
auto text = model_to_json(model);
CHECK(text.find(iso) != std::string::npos);
CHECK(model_load(text).info.createdOn == date);
}
auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2"));
for (auto [date, iso] : {std::pair{"01/01/2026 12:00:00 PM", "2026-01-01T12:00:00"},
{"03/04/2025 12:30:05 AM", "2025-03-04T00:30:05"},
{"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}})
{
model.info.createdOn = date;
auto text = model_to_json(model);
CHECK(text.find(iso) != std::string::npos);
CHECK(model_load(text).info.createdOn == date);
}
}
TEST_CASE("JSON that can't be read is reported by where it is, and the rest still opens")
{
auto text = R"({ "colour": 1, "info": { "fps": "fast" },
auto text = R"({ "colour": 1, "info": { "fps": "fast" },
"layers": [ { "name": "a", "sheet": 4 } ],
"animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "ease": "bouncy", "delay": 3 } ] } } })";
Model model = {};
std::string issues;
REQUIRE(model_load_string(model, text, &issues));
CHECK(model.animation_get(0)->frameNum == 3);
CHECK(model.animation_get(0)->root.frames[0].duration == 3);
for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4",
"animations.Idle.root[0].pos: expected an array of 2 numbers",
"animations.Idle.root[0].ease: unknown value \"bouncy\""})
CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue);
Model model = {};
std::string issues;
REQUIRE(model_load_string(model, text, &issues));
CHECK(model.animation_get(0)->frameNum == 3);
CHECK(model.animation_get(0)->root.frames[0].duration == 3);
for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4",
"animations.Idle.root[0].pos: expected an array of 2 numbers",
"animations.Idle.root[0].ease: unknown value \"bouncy\""})
CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue);
CHECK_FALSE(model_load_string(model, "{ \"fps\": 30, ", &issues));
CHECK_FALSE(model_load_string(model, "{ \"fps\": 30, ", &issues));
}
TEST_CASE("JSON layers can name a library listed after them in the file")
{
auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ],
auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ],
"libraries": [ "shared/shadows.anm2" ] })";
Model model = {};
std::string issues;
REQUIRE(model_load_string(model, text, &issues));
CHECK(issues.empty());
CHECK(model.content.layers[0].libraryId == 0);
Model model = {};
std::string issues;
REQUIRE(model_load_string(model, text, &issues));
CHECK(issues.empty());
CHECK(model.content.layers[0].libraryId == 0);
}
+431 -439
View File
@@ -4,561 +4,553 @@
#include "playback.h"
#include "pack.h"
static Model fixture_load(const char* name) { return model_load(file_load(CORPUS_DIR / name)); }
static Model fixture_load(const char* name)
{
return model_load(file_load(CORPUS_DIR / name));
}
static void operation_check(const char* name, const Model& model)
{
golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name),
model_serialize(model, SERIALIZE_ANM2ED_DEFAULT));
golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), model_serialize(model, SERIALIZE_ANM2ED_DEFAULT));
}
static Track& layer_track_get(Model& model, int animationIndex, int layerId)
{
auto track = model.track_edit({animationIndex, LAYER, layerId});
REQUIRE(track);
return *track;
auto track = model.track_edit({animationIndex, LAYER, layerId});
REQUIRE(track);
return *track;
}
static int groups_named_count(const Animation& animation, std::string_view name)
{
int count = 0;
for (const auto* entries : {&animation.layers, &animation.nulls})
groups_each(*entries, [&](const TrackGroup& group) { count += group.name == name; });
return count;
int count = 0;
for (const auto* entries : {&animation.layers, &animation.nulls})
groups_each(*entries, [&](const TrackGroup& group) { count += group.name == name; });
return count;
}
TEST_CASE("animations_merge keeps one group per name")
{
for (auto [name, type] : MERGES)
{
INFO("merge: ", std::string(name));
auto model = fixture_load("03a_groups_nested.anm2");
animations_merge(model, 0, {0, 1}, type, false, {});
CHECK(groups_named_count(*model.animation_get(0), "Main") == 1);
}
for (auto [name, type] : MERGES)
{
INFO("merge: ", std::string(name));
auto model = fixture_load("03a_groups_nested.anm2");
animations_merge(model, 0, {0, 1}, type, false, {});
CHECK(groups_named_count(*model.animation_get(0), "Main") == 1);
}
}
TEST_CASE("file_merge presets")
{
constexpr std::pair<const char*, FileMergePreset> PRESETS_FILE_MERGE[] = {
{"file_merge_by_name", FILE_MERGE_PRESET_MERGE_BY_NAME},
{"file_merge_append", FILE_MERGE_PRESET_APPEND_AS_NEW},
{"file_merge_replace", FILE_MERGE_PRESET_REPLACE_MATCHING}};
for (auto [name, preset] : PRESETS_FILE_MERGE)
{
auto model = fixture_load("02_items.anm2");
CHECK(file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset));
operation_check(name, model);
}
constexpr std::pair<const char*, FileMergePreset> PRESETS_FILE_MERGE[] = {
{"file_merge_by_name", FILE_MERGE_PRESET_MERGE_BY_NAME},
{"file_merge_append", FILE_MERGE_PRESET_APPEND_AS_NEW},
{"file_merge_replace", FILE_MERGE_PRESET_REPLACE_MATCHING}};
for (auto [name, preset] : PRESETS_FILE_MERGE)
{
auto model = fixture_load("02_items.anm2");
CHECK(file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset));
operation_check(name, model);
}
}
TEST_CASE("item_add")
{
auto model = fixture_load("02_items.anm2");
CHECK(item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1,
DESTINATION_ALL) == 2);
CHECK(item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, DESTINATION_THIS) == 2);
operation_check("item_add", model);
auto model = fixture_load("02_items.anm2");
CHECK(item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1, DESTINATION_ALL) == 2);
CHECK(item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, DESTINATION_THIS) == 2);
operation_check("item_add", model);
}
TEST_CASE("regions_generate and regions_scan")
{
auto model = fixture_load("02_items.anm2");
regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET);
auto generated = model;
regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET);
CHECK(is_model_equal(model, generated));
operation_check("regions_generate", model);
auto model = fixture_load("02_items.anm2");
regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET);
auto generated = model;
regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET);
CHECK(is_model_equal(model, generated));
operation_check("regions_generate", model);
auto scanned = fixture_load("05_regions.anm2");
regions_scan(scanned);
operation_check("regions_scan", scanned);
auto scanned = fixture_load("05_regions.anm2");
regions_scan(scanned);
operation_check("regions_scan", scanned);
}
TEST_CASE("frames_change")
{
constexpr std::pair<const char*, ChangeType> CHANGES[] = {{"adjust", ChangeType::ADJUST},
{"add", ChangeType::ADD},
{"subtract", ChangeType::SUBTRACT},
{"multiply", ChangeType::MULTIPLY},
{"divide", ChangeType::DIVIDE}};
for (auto [name, type] : CHANGES)
{
auto model = fixture_load("02_items.anm2");
FrameChange change = {.cropX = 2.0f, .positionY = 4.0f, .scaleX = 50.0f, .rotation = 90.0f, .tintR = 0.5f};
change.duration = 3;
change.interpolation = Interpolation::EASE_IN;
change.isFlipX = true;
frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1});
operation_check(std::format("frames_change_{}", name).c_str(), model);
}
constexpr std::pair<const char*, ChangeType> CHANGES[] = {{"adjust", ChangeType::ADJUST},
{"add", ChangeType::ADD},
{"subtract", ChangeType::SUBTRACT},
{"multiply", ChangeType::MULTIPLY},
{"divide", ChangeType::DIVIDE}};
for (auto [name, type] : CHANGES)
{
auto model = fixture_load("02_items.anm2");
FrameChange change = {.cropX = 2.0f, .positionY = 4.0f, .scaleX = 50.0f, .rotation = 90.0f, .tintR = 0.5f};
change.duration = 3;
change.interpolation = Interpolation::EASE_IN;
change.isFlipX = true;
frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1});
operation_check(std::format("frames_change_{}", name).c_str(), model);
}
}
TEST_CASE("frame_bake and frame_mix")
{
auto model = fixture_load("07_special_interpolation.anm2");
frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false);
frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true);
operation_check("frame_bake", model);
auto model = fixture_load("07_special_interpolation.anm2");
frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false);
frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true);
operation_check("frame_bake", model);
Frame from = {};
Frame to = {};
to.position = {10.0f, -20.0f};
to.skew = {30.0f, 0.0f};
to.rotation = 90.0f;
to.tint = {0.0f, 1.0f, 1.0f, 0.5f};
frame_mix(from, to, 0.5f);
CHECK(from.position == glm::vec2(5.0f, -10.0f));
CHECK(from.skew == glm::vec2(15.0f, 0.0f));
CHECK(from.rotation == doctest::Approx(45.0f));
CHECK(from.tint.a == doctest::Approx(0.75f));
Frame from = {};
Frame to = {};
to.position = {10.0f, -20.0f};
to.skew = {30.0f, 0.0f};
to.rotation = 90.0f;
to.tint = {0.0f, 1.0f, 1.0f, 0.5f};
frame_mix(from, to, 0.5f);
CHECK(from.position == glm::vec2(5.0f, -10.0f));
CHECK(from.skew == glm::vec2(15.0f, 0.0f));
CHECK(from.rotation == doctest::Approx(45.0f));
CHECK(from.tint.a == doctest::Approx(0.75f));
}
TEST_CASE("rects_pack fits every rect without overlap")
{
std::vector<glm::ivec2> sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}};
glm::ivec2 size{};
std::vector<glm::ivec2> positions{};
REQUIRE(rects_pack(sizes, size, positions));
REQUIRE(positions.size() == sizes.size());
for (std::size_t i = 0; i < sizes.size(); ++i)
{
CHECK(glm::all(glm::greaterThanEqual(positions[i], glm::ivec2(0))));
CHECK(glm::all(glm::lessThanEqual(positions[i] + sizes[i], size)));
for (std::size_t j = i + 1; j < sizes.size(); ++j)
std::vector<glm::ivec2> sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}};
glm::ivec2 size{};
std::vector<glm::ivec2> positions{};
REQUIRE(rects_pack(sizes, size, positions));
REQUIRE(positions.size() == sizes.size());
for (std::size_t i = 0; i < sizes.size(); ++i)
{
auto isSeparate = glm::any(glm::lessThanEqual(positions[i] + sizes[i], positions[j])) ||
glm::any(glm::lessThanEqual(positions[j] + sizes[j], positions[i]));
CHECK(isSeparate);
CHECK(glm::all(glm::greaterThanEqual(positions[i], glm::ivec2(0))));
CHECK(glm::all(glm::lessThanEqual(positions[i] + sizes[i], size)));
for (std::size_t j = i + 1; j < sizes.size(); ++j)
{
auto isSeparate = glm::any(glm::lessThanEqual(positions[i] + sizes[i], positions[j])) ||
glm::any(glm::lessThanEqual(positions[j] + sizes[j], positions[i]));
CHECK(isSeparate);
}
}
}
}
// Each edit runs on a fixture; its result document is a golden, and every returned uid must resolve.
// Each edit runs on a fixture. Its result document is a golden, and every returned uid must resolve.
TEST_CASE("edit layer operations")
{
struct Case
{
const char* name;
const char* fixture;
std::function<Uids(Model&)> operation;
std::size_t uidCount;
};
struct Case
{
const char* name;
const char* fixture;
std::function<Uids(Model&)> operation;
std::size_t uidCount;
};
const Reference head = {0, LAYER, 0};
const Case CASES[] = {
{"frame_insert", "02_items.anm2",
[&](Model& anm2) { return frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1},
{"trigger_insert", "02_items.anm2",
[&](Model& anm2) { return frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1},
{"frames_delete", "02_items.anm2",
[&](Model& anm2) { return frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0},
{"frames_duplicate", "02_items.anm2", [&](Model& anm2)
{ return frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2},
{"frames_reverse", "07_special_interpolation.anm2",
[&](Model& anm2) { return frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0},
{"frames_bake", "07_special_interpolation.anm2", [&](Model& anm2)
{ return frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5},
{"frame_split", "02_items.anm2", [&](Model& anm2) { return frame_split(anm2, {0, LAYER, 1, 0}, 2); },
1},
{"frames_move", "02_items.anm2",
[&](Model& anm2) { return frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2},
{"frames_paste", "02_items.anm2",
[&](Model& anm2)
{
auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0});
auto text = frame_to_string(*frame, ItemType::LAYER) + frame_to_string(*frame, ItemType::LAYER);
return frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr);
},
2},
{"root_bake_into", "04_group_root_transform.anm2",
[&](Model& anm2)
{
return root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}},
{.isRoundScale = true, .isMatchRootInterpolation = true});
},
1},
{"items_group", "03b_groups_legacy_flat.anm2",
[&](Model& anm2) { return items_group(anm2, 0, LAYER, {2}, "New"); }, 1},
{"items_move", "03b_groups_legacy_flat.anm2", [&](Model& anm2)
{ return items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0},
{"items_remove", "03b_groups_legacy_flat.anm2",
[&](Model& anm2) { return items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0},
{"animation_add", "03a_groups_nested.anm2",
[&](Model& anm2) { return animation_add(anm2, 1, 0, 0, "Added"); }, 1},
{"animations_remove", "03a_groups_nested.anm2",
[&](Model& anm2) { return animations_remove(anm2, {1}, {0}); }, 0},
{"animations_move", "02_items.anm2", [&](Model& anm2)
{ return animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1},
{"animations_group", "02_items.anm2",
[&](Model& anm2) { return animations_group(anm2, {0, 1}, "Group"); }, 0},
{"animations_paste", "02_items.anm2",
[&](Model& anm2)
{
std::set<int> groupIds;
auto text = animation_to_string(*anm2.animation_get(1));
return animations_paste(anm2, text, 0, -1, groupIds, nullptr);
},
1},
{"regions_paste", "05_regions.anm2",
[&](Model& anm2)
{
auto region = item_get(item_get(anm2.content.spritesheets, 0)->regions, 1);
return regions_paste(anm2, 0, item_to_string(*region), 1, nullptr);
},
0},
{"animation_grid_generate", "05_regions.anm2",
[&](Model& anm2)
{
return animation_grid_generate(anm2, {{0, LAYER, 0}},
{{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"});
},
3},
{"frames_change_apply", "02_items.anm2",
[&](Model& anm2)
{
FrameChange change = {.positionX = 3.0f, .rotation = 10.0f};
return frames_change_apply(
anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change,
ChangeType::ADD);
},
0},
{"animations_merge", "03a_groups_nested.anm2",
[&](Model& anm2) { return animations_merge(anm2, 0, {1}, MERGE_APPEND, true, {0}); }, 1},
};
const Reference head = {0, LAYER, 0};
const Case CASES[] = {
{"frame_insert", "02_items.anm2", [&](Model& anm2) { return frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1},
{"trigger_insert", "02_items.anm2", [&](Model& anm2) { return frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1},
{"frames_delete", "02_items.anm2",
[&](Model& anm2) { return frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0},
{"frames_duplicate", "02_items.anm2",
[&](Model& anm2) { return frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); },
2},
{"frames_reverse", "07_special_interpolation.anm2",
[&](Model& anm2) { return frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0},
{"frames_bake", "07_special_interpolation.anm2",
[&](Model& anm2) { return frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5},
{"frame_split", "02_items.anm2", [&](Model& anm2) { return frame_split(anm2, {0, LAYER, 1, 0}, 2); }, 1},
{"frames_move", "02_items.anm2",
[&](Model& anm2) { return frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2},
{"frames_paste", "02_items.anm2",
[&](Model& anm2) {
auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0});
auto text = frame_to_string(*frame, ItemType::LAYER) + frame_to_string(*frame, ItemType::LAYER);
return frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr);
},
2},
{"root_bake_into", "04_group_root_transform.anm2",
[&](Model& anm2) {
return root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}},
{.isRoundScale = true, .isMatchRootInterpolation = true});
},
1},
{"items_group", "03b_groups_legacy_flat.anm2",
[&](Model& anm2) { return items_group(anm2, 0, LAYER, {2}, "New"); }, 1},
{"items_move", "03b_groups_legacy_flat.anm2",
[&](Model& anm2) { return items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0},
{"items_remove", "03b_groups_legacy_flat.anm2",
[&](Model& anm2) { return items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0},
{"animation_add", "03a_groups_nested.anm2", [&](Model& anm2) { return animation_add(anm2, 1, 0, 0, "Added"); },
1},
{"animations_remove", "03a_groups_nested.anm2", [&](Model& anm2) { return animations_remove(anm2, {1}, {0}); },
0},
{"animations_move", "02_items.anm2",
[&](Model& anm2) { return animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1},
{"animations_group", "02_items.anm2", [&](Model& anm2) { return animations_group(anm2, {0, 1}, "Group"); }, 0},
{"animations_paste", "02_items.anm2",
[&](Model& anm2) {
std::set<int> groupIds;
auto text = animation_to_string(*anm2.animation_get(1));
return animations_paste(anm2, text, 0, -1, groupIds, nullptr);
},
1},
{"regions_paste", "05_regions.anm2",
[&](Model& anm2) {
auto region = item_get(item_get(anm2.content.spritesheets, 0)->regions, 1);
return regions_paste(anm2, 0, item_to_string(*region), 1, nullptr);
},
0},
{"animation_grid_generate", "05_regions.anm2",
[&](Model& anm2) {
return animation_grid_generate(anm2, {{0, LAYER, 0}}, {{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"});
},
3},
{"frames_change_apply", "02_items.anm2",
[&](Model& anm2) {
FrameChange change = {.positionX = 3.0f, .rotation = 10.0f};
return frames_change_apply(
anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change,
ChangeType::ADD);
},
0},
{"animations_merge", "03a_groups_nested.anm2",
[&](Model& anm2) { return animations_merge(anm2, 0, {1}, MERGE_APPEND, true, {0}); }, 1},
};
for (auto& entry : CASES)
{
INFO("operation: ", std::string(entry.name));
auto anm2 = fixture_load(entry.fixture);
auto uids = entry.operation(anm2);
CHECK(uids.size() == entry.uidCount);
anm2.uids_repair();
UidIndex index(anm2);
for (auto uid : uids)
CHECK(index.reference_get(uid));
operation_check(entry.name, anm2);
}
for (auto& entry : CASES)
{
INFO("operation: ", std::string(entry.name));
auto anm2 = fixture_load(entry.fixture);
auto uids = entry.operation(anm2);
CHECK(uids.size() == entry.uidCount);
anm2.uids_repair();
UidIndex index(anm2);
for (auto uid : uids)
CHECK(index.reference_get(uid));
operation_check(entry.name, anm2);
}
}
TEST_CASE("spritesheet pixel edits")
{
auto image_make = [](glm::ivec2 size, std::vector<glm::ivec2> opaque = {})
{
std::vector<uint8_t> pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0);
for (auto point : opaque)
std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * IMAGE_CHANNELS,
IMAGE_CHANNELS, 255);
return Image(pixels.data(), size);
};
auto sheet = image_make({64, 64}, {{4, 6}});
auto other = image_make({16, 16});
auto image_make = [](glm::ivec2 size, std::vector<glm::ivec2> opaque = {}) {
std::vector<uint8_t> pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0);
for (auto point : opaque)
std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * IMAGE_CHANNELS, IMAGE_CHANNELS,
255);
return Image(pixels.data(), size);
};
auto sheet = image_make({64, 64}, {{4, 6}});
auto other = image_make({16, 16});
SUBCASE("regions_trim shrinks to content and keeps the custom pivot in place")
{
auto model = fixture_load("05_regions.anm2");
CHECK(regions_trim(model, 0, {0, 1}, sheet));
auto region = item_get(model.content.spritesheets[0].regions, 0);
CHECK(region->crop == glm::vec2(4, 6));
CHECK(region->size == glm::vec2(1, 1));
CHECK(region->pivot == glm::vec2(-1, -1));
}
SUBCASE("regions_trim shrinks to content and keeps the custom pivot in place")
{
auto model = fixture_load("05_regions.anm2");
CHECK(regions_trim(model, 0, {0, 1}, sheet));
auto region = item_get(model.content.spritesheets[0].regions, 0);
CHECK(region->crop == glm::vec2(4, 6));
CHECK(region->size == glm::vec2(1, 1));
CHECK(region->pivot == glm::vec2(-1, -1));
}
SUBCASE("spritesheet_pack returns an image holding every region")
{
auto model = fixture_load("05_regions.anm2");
auto packed = spritesheet_pack(model, 0, sheet, 1);
REQUIRE(packed);
CHECK(packed->is_valid());
for (auto& region : model.content.spritesheets[0].regions)
CHECK(glm::all(glm::lessThanEqual(glm::ivec2(region.crop + region.size), packed->size)));
}
SUBCASE("spritesheet_pack returns an image holding every region")
{
auto model = fixture_load("05_regions.anm2");
auto packed = spritesheet_pack(model, 0, sheet, 1);
REQUIRE(packed);
CHECK(packed->is_valid());
for (auto& region : model.content.spritesheets[0].regions)
CHECK(glm::all(glm::lessThanEqual(glm::ivec2(region.crop + region.size), packed->size)));
}
SUBCASE("spritesheets_merge appends images and moves layers onto the base sheet")
{
auto model = fixture_load("05_regions.anm2");
auto image_get = [&](int id) { return id == 0 ? &sheet : &other; };
auto merged = spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT);
REQUIRE(merged);
CHECK(merged->size == glm::ivec2(80, 64));
CHECK(model.content.spritesheets.size() == 1);
CHECK(item_get(model.content.layers, 1)->spritesheetId == 0);
operation_check("spritesheets_merge", model);
}
SUBCASE("spritesheets_merge appends images and moves layers onto the base sheet")
{
auto model = fixture_load("05_regions.anm2");
auto image_get = [&](int id) {
return id == 0 ? &sheet : &other;
};
auto merged = spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT);
REQUIRE(merged);
CHECK(merged->size == glm::ivec2(80, 64));
CHECK(model.content.spritesheets.size() == 1);
CHECK(item_get(model.content.layers, 1)->spritesheetId == 0);
operation_check("spritesheets_merge", model);
}
}
TEST_CASE("markers stay in the editor's copy and bound playback")
{
auto model = fixture_load("01_minimal.anm2");
auto animation = model.animation_edit(0);
REQUIRE(animation);
animation->frameNum = 10;
animation->startMarker = 2;
animation->endMarker = 5;
CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6));
auto model = fixture_load("01_minimal.anm2");
auto animation = model.animation_edit(0);
REQUIRE(animation);
animation->frameNum = 10;
animation->startMarker = 2;
animation->endMarker = 5;
CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6));
auto text = model_to_string(model);
CHECK(game_document_get(text).find("Marker") == std::string::npos);
auto reloaded = model_load(text);
CHECK(reloaded.animation_get(0)->startMarker == 2);
CHECK(reloaded.animation_get(0)->endMarker == 5);
auto text = model_to_string(model);
CHECK(game_document_get(text).find("Marker") == std::string::npos);
auto reloaded = model_load(text);
CHECK(reloaded.animation_get(0)->startMarker == 2);
CHECK(reloaded.animation_get(0)->endMarker == 5);
Playback playback = {};
playback.isPlaying = true;
playback.tick(10, 2, 6, true, 0.1f);
CHECK(playback.time == doctest::Approx(3.0f));
playback.tick(10, 2, 6, true, 0.5f);
CHECK(playback.time == doctest::Approx(4.0f));
Playback playback = {};
playback.isPlaying = true;
playback.tick(10, 2, 6, true, 0.1f);
CHECK(playback.time == doctest::Approx(3.0f));
playback.tick(10, 2, 6, true, 0.5f);
CHECK(playback.time == doctest::Approx(4.0f));
}
TEST_CASE("isaac_issues_get counts what the game's copy changes")
{
CHECK(isaac_issues_get(fixture_load("01_minimal.anm2")) == IsaacIssues{});
CHECK(isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5);
CHECK(isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0);
auto shaders = isaac_issues_get(fixture_load("06_shaders.anm2"));
CHECK(shaders.shaderFrames > 0);
CHECK(shaders.skewFrames > 0);
CHECK(isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0);
CHECK(isaac_issues_get(fixture_load("01_minimal.anm2")) == IsaacIssues{});
CHECK(isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5);
CHECK(isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0);
auto shaders = isaac_issues_get(fixture_load("06_shaders.anm2"));
CHECK(shaders.shaderFrames > 0);
CHECK(shaders.skewFrames > 0);
CHECK(isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0);
}
TEST_CASE("frames_property_set copies one property to the frames that have it")
{
auto model = fixture_load("02_items.anm2");
Frame source = {.crop = {7, 8}, .position = {3, 4}};
Reference layer = {0, LAYER, 0, 0};
Reference null = {0, NULL_, 0, 0};
REQUIRE(model.frame_get(layer));
REQUIRE(model.frame_get(null));
auto nullCrop = model.frame_get(null)->crop;
auto model = fixture_load("02_items.anm2");
Frame source = {.crop = {7, 8}, .position = {3, 4}};
Reference layer = {0, LAYER, 0, 0};
Reference null = {0, NULL_, 0, 0};
REQUIRE(model.frame_get(layer));
REQUIRE(model.frame_get(null));
auto nullCrop = model.frame_get(null)->crop;
frames_property_set(model, {layer, null}, FrameProperty::POSITION, source);
CHECK(model.frame_get(layer)->position == glm::vec2(3, 4));
CHECK(model.frame_get(null)->position == glm::vec2(3, 4));
frames_property_set(model, {layer, null}, FrameProperty::POSITION, source);
CHECK(model.frame_get(layer)->position == glm::vec2(3, 4));
CHECK(model.frame_get(null)->position == glm::vec2(3, 4));
frames_property_set(model, {layer, null}, FrameProperty::CROP, source);
CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8));
CHECK(model.frame_get(null)->crop == nullCrop);
frames_property_set(model, {layer, null}, FrameProperty::CROP, source);
CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8));
CHECK(model.frame_get(null)->crop == nullCrop);
CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER));
CHECK(is_frame_property_valid(FrameProperty::SOUNDS, ItemType::TRIGGER));
CHECK_FALSE(is_frame_property_valid(FrameProperty::POSITION, ItemType::TRIGGER));
CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER));
CHECK(is_frame_property_valid(FrameProperty::SOUNDS, ItemType::TRIGGER));
CHECK_FALSE(is_frame_property_valid(FrameProperty::POSITION, ItemType::TRIGGER));
}
TEST_CASE("frames_split splits every selected frame that spans the time")
{
auto model = fixture_load("02_items.anm2");
auto layerTrack = model.track_get({0, LAYER, 0});
auto nullTrack = model.track_get({0, NULL_, 0});
REQUIRE(layerTrack);
REQUIRE(nullTrack);
auto layerCount = layerTrack->frames.size();
auto nullCount = nullTrack->frames.size();
REQUIRE(layerTrack->frames[0].duration > 1);
REQUIRE(nullTrack->frames[0].duration > 1);
auto model = fixture_load("02_items.anm2");
auto layerTrack = model.track_get({0, LAYER, 0});
auto nullTrack = model.track_get({0, NULL_, 0});
REQUIRE(layerTrack);
REQUIRE(nullTrack);
auto layerCount = layerTrack->frames.size();
auto nullCount = nullTrack->frames.size();
REQUIRE(layerTrack->frames[0].duration > 1);
REQUIRE(nullTrack->frames[0].duration > 1);
auto uids = frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0);
CHECK(uids.size() == 2);
CHECK(model.track_get({0, LAYER, 0})->frames.size() == layerCount + 1);
CHECK(model.track_get({0, NULL_, 0})->frames.size() == nullCount + 1);
CHECK(model.track_get({0, LAYER, 0})->frames[0].duration == 1);
auto uids = frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0);
CHECK(uids.size() == 2);
CHECK(model.track_get({0, LAYER, 0})->frames.size() == layerCount + 1);
CHECK(model.track_get({0, NULL_, 0})->frames.size() == nullCount + 1);
CHECK(model.track_get({0, LAYER, 0})->frames[0].duration == 1);
}
TEST_CASE("change all frame properties changes layer depth only")
{
auto model = fixture_load("02_items.anm2");
Reference layer = {0, LAYER, 0, 0};
Reference null = {0, NULL_, 0, 0};
frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD);
frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT);
CHECK(model.frame_get(layer)->depth == 1);
CHECK(model.frame_get(null)->depth == 0);
auto model = fixture_load("02_items.anm2");
Reference layer = {0, LAYER, 0, 0};
Reference null = {0, NULL_, 0, 0};
frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD);
frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT);
CHECK(model.frame_get(layer)->depth == 1);
CHECK(model.frame_get(null)->depth == 0);
}
TEST_CASE("change all frame properties blurs layers and changes only animation layers' children")
{
auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
Reference animationLayer = {0, LAYER, 1, 0};
Reference spritesheetLayer = {1, LAYER, 2, 0};
REQUIRE(model.frame_get(spritesheetLayer));
frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}},
{.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3},
ChangeType::ADJUST);
auto child = *model.frame_get(animationLayer);
CHECK(child.blur == 8.0f);
CHECK(child.childAnimation == "Spin");
CHECK(child.childMode == ChildMode::ONCE);
CHECK(child.childStart == 3);
auto sprite = *model.frame_get(spritesheetLayer);
CHECK(sprite.blur == 8.0f);
CHECK(sprite.childAnimation.empty());
CHECK(sprite.childMode == ChildMode::LOOP);
CHECK(sprite.childStart == 0);
auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
Reference animationLayer = {0, LAYER, 1, 0};
Reference spritesheetLayer = {1, LAYER, 2, 0};
REQUIRE(model.frame_get(spritesheetLayer));
frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}},
{.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3},
ChangeType::ADJUST);
auto child = *model.frame_get(animationLayer);
CHECK(child.blur == 8.0f);
CHECK(child.childAnimation == "Spin");
CHECK(child.childMode == ChildMode::ONCE);
CHECK(child.childStart == 3);
auto sprite = *model.frame_get(spritesheetLayer);
CHECK(sprite.blur == 8.0f);
CHECK(sprite.childAnimation.empty());
CHECK(sprite.childMode == ChildMode::LOOP);
CHECK(sprite.childStart == 0);
frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD);
CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX);
frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD);
CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX);
}
TEST_CASE("animations_merge moves triggers past the animation placed before them")
{
auto model_make = []()
{
auto model = fixture_load("01_minimal.anm2");
auto first = *model.animation_get(0);
first.frameNum = 10;
auto second = first;
second.uid = uid_next();
second.triggers.frames = {Frame{.atFrame = 5}};
model.animations.entries = {std::make_shared<const Animation>(first),
std::make_shared<const Animation>(second)};
return model;
};
auto model_make = []() {
auto model = fixture_load("01_minimal.anm2");
auto first = *model.animation_get(0);
first.frameNum = 10;
auto second = first;
second.uid = uid_next();
second.triggers.frames = {Frame{.atFrame = 5}};
model.animations.entries = {std::make_shared<const Animation>(first),
std::make_shared<const Animation>(second)};
return model;
};
auto appended = model_make();
animations_merge(appended, 0, {0, 1}, MERGE_APPEND, false, {});
CHECK(appended.animation_get(0)->triggers.frames.at(0).atFrame == 15);
auto appended = model_make();
animations_merge(appended, 0, {0, 1}, MERGE_APPEND, false, {});
CHECK(appended.animation_get(0)->triggers.frames.at(0).atFrame == 15);
auto prepended = model_make();
animations_merge(prepended, 1, {0, 1}, MERGE_PREPEND, false, {});
CHECK(prepended.animation_get(1)->triggers.frames.at(0).atFrame == 15);
auto prepended = model_make();
animations_merge(prepended, 1, {0, 1}, MERGE_PREPEND, false, {});
CHECK(prepended.animation_get(1)->triggers.frames.at(0).atFrame == 15);
}
TEST_CASE("skew reads from the old Shear attributes too")
{
auto frames =
frames_from_string(R"(<Frame ShearX="5" ShearY="6"/><Frame SkewX="7" ShearX="9"/>)", ItemType::NULL_);
REQUIRE(frames.size() == 2);
CHECK(frames[0].skew == glm::vec2(5, 6));
CHECK(frames[1].skew.x == 7);
CHECK(frames[0].extras.attributes.empty());
auto frames = frames_from_string(R"(<Frame ShearX="5" ShearY="6"/><Frame SkewX="7" ShearX="9"/>)", ItemType::NULL_);
REQUIRE(frames.size() == 2);
CHECK(frames[0].skew == glm::vec2(5, 6));
CHECK(frames[1].skew.x == 7);
CHECK(frames[0].extras.attributes.empty());
}
TEST_CASE("a trigger fires several events; the game's copy keeps the first")
{
auto model = fixture_load("02_items.anm2");
model.frame_edit({0, TRIGGER, -1, 0})->eventIds = {1, 0};
auto text = model_to_string(model);
CHECK(model_load(text).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1, 0});
CHECK(model_load(game_document_get(text)).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1});
CHECK(isaac_issues_get(model).extraEvents == 1);
auto model = fixture_load("02_items.anm2");
model.frame_edit({0, TRIGGER, -1, 0})->eventIds = {1, 0};
auto text = model_to_string(model);
CHECK(model_load(text).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1, 0});
CHECK(model_load(game_document_get(text)).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1});
CHECK(isaac_issues_get(model).extraEvents == 1);
}
TEST_CASE("SVG spritesheets pack and merge into SVGs")
{
auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2"));
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}});
auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2"));
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 = 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 = item_get(model.content.spritesheets.front().regions, id);
CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original));
}
// Packing keeps the drawing: each region shows the same pixels where it now sits.
auto packed = 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 = 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<uint8_t> pixels(4 * 4 * IMAGE_CHANNELS, 255);
Image raster(pixels.data(), {4, 4});
model.content.spritesheets.push_back({.id = 1, .path = "white.png"});
auto images = std::map<int, const Image*>{{0, &vector}, {1, &raster}};
auto image_get = [&](int id) { return images.at(id); };
auto mixed = model;
auto merged = 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");
// 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<uint8_t> pixels(4 * 4 * IMAGE_CHANNELS, 255);
Image raster(pixels.data(), {4, 4});
model.content.spritesheets.push_back({.id = 1, .path = "white.png"});
auto images = std::map<int, const Image*>{{0, &vector}, {1, &raster}};
auto image_get = [&](int id) {
return images.at(id);
};
auto mixed = model;
auto merged = 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(spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT));
CHECK(item_get(model.content.spritesheets, 0)->path == "white.svg");
std::swap(model.content.spritesheets.front().id, model.content.spritesheets.back().id);
images = {{1, &vector}, {0, &raster}};
REQUIRE(spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT));
CHECK(item_get(model.content.spritesheets, 0)->path == "white.svg");
}
TEST_CASE("content_remove takes what refers to an item with it")
{
auto path_keep = [](const Model&, const std::filesystem::path& path) { return path; };
auto remove = [&](Model& model, ElementType type, std::set<int> ids, int spritesheetId = -1,
const LibraryGet& library_get = {})
{ content_remove(model, type, ids, spritesheetId, library_get, path_keep); };
auto tracks_count = [](const Model& model, int layerId)
{
int count = 0;
for (auto [index, animation] : model.animations_get())
tracks_each(animation->layers, [&](const Track& track, auto*) { count += track.id == layerId; });
return count;
};
auto path_keep = [](const Model&, const std::filesystem::path& path) {
return path;
};
auto remove = [&](Model& model, ElementType type, std::set<int> ids, int spritesheetId = -1,
const LibraryGet& library_get = {}) {
content_remove(model, type, ids, spritesheetId, library_get, path_keep);
};
auto tracks_count = [](const Model& model, int layerId) {
int count = 0;
for (auto [index, animation] : model.animations_get())
tracks_each(animation->layers, [&](const Track& track, auto*) { count += track.id == layerId; });
return count;
};
SUBCASE("a layer's tracks, and a spritesheet's plain layers")
{
auto model = fixture_load("02_items.anm2");
CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0));
remove(model, ElementType::LAYER_ELEMENT, {0});
CHECK_FALSE(item_get(model.content.layers, 0));
CHECK(tracks_count(model, 0) == 0);
CHECK(tracks_count(model, 1) > 0);
SUBCASE("a layer's tracks, and a spritesheet's plain layers")
{
auto model = fixture_load("02_items.anm2");
CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0));
remove(model, ElementType::LAYER_ELEMENT, {0});
CHECK_FALSE(item_get(model.content.layers, 0));
CHECK(tracks_count(model, 0) == 0);
CHECK(tracks_count(model, 1) > 0);
CHECK(model.uses_count(ElementType::SPRITESHEET, {1}) == 1);
remove(model, ElementType::SPRITESHEET, {1});
CHECK(model.content.layers.empty());
CHECK(tracks_count(model, 1) == 0);
CHECK(model.content.spritesheets.size() == 1);
}
CHECK(model.uses_count(ElementType::SPRITESHEET, {1}) == 1);
remove(model, ElementType::SPRITESHEET, {1});
CHECK(model.content.layers.empty());
CHECK(tracks_count(model, 1) == 0);
CHECK(model.content.spritesheets.size() == 1);
}
SUBCASE("an event or sound from its triggers, and triggers left with neither")
{
auto model = fixture_load("02_items.anm2");
auto& triggers = model.animation_get(0)->triggers.frames;
REQUIRE(triggers.size() == 3);
CHECK(model.uses_count(ElementType::SOUND_ELEMENT, {1}) == 2);
remove(model, ElementType::SOUND_ELEMENT, {1});
REQUIRE(triggers.size() == 2);
CHECK(triggers[1].soundIds == std::vector{0});
remove(model, ElementType::EVENT_ELEMENT, {0});
REQUIRE(triggers.size() == 2);
CHECK(triggers[0].eventIds.empty());
CHECK(triggers[0].soundIds == std::vector{0});
}
SUBCASE("an event or sound from its triggers, and triggers left with neither")
{
auto model = fixture_load("02_items.anm2");
auto& triggers = model.animation_get(0)->triggers.frames;
REQUIRE(triggers.size() == 3);
CHECK(model.uses_count(ElementType::SOUND_ELEMENT, {1}) == 2);
remove(model, ElementType::SOUND_ELEMENT, {1});
REQUIRE(triggers.size() == 2);
CHECK(triggers[1].soundIds == std::vector{0});
remove(model, ElementType::EVENT_ELEMENT, {0});
REQUIRE(triggers.size() == 2);
CHECK(triggers[0].eventIds.empty());
CHECK(triggers[0].soundIds == std::vector{0});
}
SUBCASE("a shader, and a region, from their frames")
{
auto shaders = fixture_load("06_shaders.anm2");
remove(shaders, ElementType::SHADER, {0});
CHECK(shaders.frame_get({0, LAYER, 0, 0})->shaderId == -1);
CHECK(shaders.frame_get({0, LAYER, 0, 1})->shaderId == 4);
SUBCASE("a shader, and a region, from their frames")
{
auto shaders = fixture_load("06_shaders.anm2");
remove(shaders, ElementType::SHADER, {0});
CHECK(shaders.frame_get({0, LAYER, 0, 0})->shaderId == -1);
CHECK(shaders.frame_get({0, LAYER, 0, 1})->shaderId == 4);
auto regions = fixture_load("05_regions.anm2");
auto before = *regions.frame_get({0, LAYER, 0, 0});
REQUIRE(before.regionId == 0);
CHECK(regions.uses_count(ElementType::REGION, {0}, 0) == 1);
remove(regions, ElementType::REGION, {0}, 0);
auto after = *regions.frame_get({0, LAYER, 0, 0});
CHECK(after.regionId == -1);
CHECK(after.crop == before.crop);
CHECK(after.size == before.size);
CHECK(after.pivot == before.pivot);
CHECK_FALSE(item_get(regions.content.spritesheets.front().regions, 0));
}
auto regions = fixture_load("05_regions.anm2");
auto before = *regions.frame_get({0, LAYER, 0, 0});
REQUIRE(before.regionId == 0);
CHECK(regions.uses_count(ElementType::REGION, {0}, 0) == 1);
remove(regions, ElementType::REGION, {0}, 0);
auto after = *regions.frame_get({0, LAYER, 0, 0});
CHECK(after.regionId == -1);
CHECK(after.crop == before.crop);
CHECK(after.size == before.size);
CHECK(after.pivot == before.pivot);
CHECK_FALSE(item_get(regions.content.spritesheets.front().regions, 0));
}
SUBCASE("a library's layers, flattened")
{
auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1);
remove(model, ElementType::LIBRARY, {0}, -1,
[&](const Model&, int id) { return id == 0 ? &spin : nullptr; });
CHECK(model.content.libraries.empty());
CHECK_FALSE(item_get(model.content.layers, 0));
CHECK(
std::ranges::any_of(model.content.layers, [](const Layer& layer) { return layer.name == "spin/red"; }));
// Layers playing this file's animations stay as they are.
CHECK(item_get(model.content.layers, 1)->is_animation());
CHECK(item_get(model.content.layers, 3)->is_animation());
}
SUBCASE("a library's layers, flattened")
{
auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2"));
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1);
remove(model, ElementType::LIBRARY, {0}, -1, [&](const Model&, int id) { return id == 0 ? &spin : nullptr; });
CHECK(model.content.libraries.empty());
CHECK_FALSE(item_get(model.content.layers, 0));
CHECK(std::ranges::any_of(model.content.layers, [](const Layer& layer) { return layer.name == "spin/red"; }));
// Layers playing this file's animations stay as they are.
CHECK(item_get(model.content.layers, 1)->is_animation());
CHECK(item_get(model.content.layers, 3)->is_animation());
}
}
+244 -240
View File
@@ -13,255 +13,258 @@
#include "image.h"
#include "render.h"
const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render";
const std::filesystem::path GOLDEN_DIR = RENDER_TEST_DIR / "golden";
const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR;
constexpr int CHANNEL_TOLERANCE = 8;
constexpr double MISMATCH_RATIO_MAX = 0.01;
constexpr float SCALE = 3.0f;
constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f};
const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render";
const std::filesystem::path GOLDEN_DIR = RENDER_TEST_DIR / "golden";
const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR;
constexpr int CHANNEL_TOLERANCE = 8;
constexpr double MISMATCH_RATIO_MAX = 0.01;
constexpr float SCALE = 3.0f;
constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f};
// Different OpenGL implementations round a little differently: a few pixels may differ, each only slightly.
static void golden_image_check(const std::string& name)
{
auto actualPath = OUTPUT_DIR / name;
auto goldenPath = GOLDEN_DIR / name;
INFO("render: ", actualPath.string());
if (std::getenv("ANM2ED_UPDATE_GOLDEN"))
{
std::filesystem::copy_file(actualPath, goldenPath, std::filesystem::copy_options::overwrite_existing);
return;
}
Image actual(actualPath);
Image golden(goldenPath);
REQUIRE(golden.is_valid());
REQUIRE(actual.size == golden.size);
int mismatches = 0;
for (std::size_t i = 0; i < actual.pixels.size(); ++i)
mismatches += std::abs((int)actual.pixels[i] - (int)golden.pixels[i]) > CHANNEL_TOLERANCE;
CHECK((double)mismatches / (double)actual.pixels.size() <= MISMATCH_RATIO_MAX);
auto actualPath = OUTPUT_DIR / name;
auto goldenPath = GOLDEN_DIR / name;
INFO("render: ", actualPath.string());
if (std::getenv("ANM2ED_UPDATE_GOLDEN"))
{
std::filesystem::copy_file(actualPath, goldenPath, std::filesystem::copy_options::overwrite_existing);
return;
}
Image actual(actualPath);
Image golden(goldenPath);
REQUIRE(golden.is_valid());
REQUIRE(actual.size == golden.size);
int mismatches = 0;
for (std::size_t i = 0; i < actual.pixels.size(); ++i)
mismatches += std::abs((int)actual.pixels[i] - (int)golden.pixels[i]) > CHANNEL_TOLERANCE;
CHECK((double)mismatches / (double)actual.pixels.size() <= MISMATCH_RATIO_MAX);
}
struct RenderFixture
{
HeadlessGL gl = {};
std::optional<Document> document;
std::optional<ShaderProgram> shader;
std::optional<Canvas> canvas;
const Animation* animation = nullptr;
glm::vec4 bounds{};
HeadlessGL gl = {};
std::optional<Document> document;
std::optional<ShaderProgram> shader;
std::optional<Canvas> canvas;
const Animation* animation = nullptr;
glm::vec4 bounds{};
explicit RenderFixture(const char* file)
{
if (!gl.is_valid()) return;
std::filesystem::create_directories(OUTPUT_DIR);
document.emplace(RENDER_TEST_DIR / file, false);
auto& info = SHADERS[SHADER_TEXTURE];
shader.emplace(info.vertex, info.fragment);
canvas.emplace(glm::vec2(1.0f));
animation = document->model.animation_get(0);
bounds = animation_bounds_get(*document, *animation, true);
}
explicit RenderFixture(const char* file)
{
if (!gl.is_valid())
return;
std::filesystem::create_directories(OUTPUT_DIR);
document.emplace(RENDER_TEST_DIR / file, false);
auto& info = SHADERS[SHADER_TEXTURE];
shader.emplace(info.vertex, info.fragment);
canvas.emplace(glm::vec2(1.0f));
animation = document->model.animation_get(0);
bounds = animation_bounds_get(*document, *animation, true);
}
std::vector<uint8_t> frame_get(float time)
{
auto pixels =
animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true);
pixels_unpremultiply(pixels);
return pixels;
}
std::vector<uint8_t> frame_get(float time)
{
auto pixels =
animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true);
pixels_unpremultiply(pixels);
return pixels;
}
glm::u8vec4 pixel_get(const std::vector<uint8_t>& pixels, glm::vec2 point)
{
auto position = glm::ivec2((point - glm::vec2(bounds.x, bounds.y)) * SCALE);
auto index = ((std::size_t)position.y * (std::size_t)canvas->size.x + (std::size_t)position.x) * 4;
return {pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]};
}
glm::u8vec4 pixel_get(const std::vector<uint8_t>& pixels, glm::vec2 point)
{
auto position = glm::ivec2((point - glm::vec2(bounds.x, bounds.y)) * SCALE);
auto index = ((std::size_t)position.y * (std::size_t)canvas->size.x + (std::size_t)position.x) * 4;
return {pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]};
}
};
TEST_CASE("frames draw where the animation puts them")
{
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
// At time 0 the red square is centered at (-16, 0) with its white dot up and left; the half-transparent blue
// square (32 x 32, at the origin) covers the middle.
auto pixels = fixture.frame_get(0.0f);
auto red = fixture.pixel_get(pixels, {-20.0f, 4.0f});
CHECK(red.r > 200);
CHECK(red.g < 80);
auto dot = fixture.pixel_get(pixels, {-18.5f, -2.5f});
CHECK(dot.g > 200);
auto blue = fixture.pixel_get(pixels, {12.0f, 12.0f});
CHECK(blue.b > blue.r + 40);
// At time 0 the red square is centered at (-16, 0) with its white dot up and left. The half-transparent blue
// square (32 x 32, at the origin) covers the middle.
auto pixels = fixture.frame_get(0.0f);
auto red = fixture.pixel_get(pixels, {-20.0f, 4.0f});
CHECK(red.r > 200);
CHECK(red.g < 80);
auto dot = fixture.pixel_get(pixels, {-18.5f, -2.5f});
CHECK(dot.g > 200);
auto blue = fixture.pixel_get(pixels, {12.0f, 12.0f});
CHECK(blue.b > blue.r + 40);
auto framePath = OUTPUT_DIR / "spin_frame_0.png";
REQUIRE(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data()));
golden_image_check("spin_frame_0.png");
auto framePath = OUTPUT_DIR / "spin_frame_0.png";
REQUIRE(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data()));
golden_image_check("spin_frame_0.png");
}
TEST_CASE("a recorded spritesheet holds every frame")
{
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
RecorderOptions options{.type = RENDER_SPRITESHEET,
.path = OUTPUT_DIR / "spin_sheet.png",
.start = 0,
.end = fixture.animation->frameNum - 1,
.animationFps = fixture.document->model.info.fps,
.fps = fixture.document->model.info.fps};
REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation,
fixture.bounds, SCALE, BACKGROUND, true));
Image sheet(options.path);
auto layout = spritesheet_layout_get(0, 0, fixture.animation->frameNum);
CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows));
golden_image_check("spin_sheet.png");
RecorderOptions options{.type = RENDER_SPRITESHEET,
.path = OUTPUT_DIR / "spin_sheet.png",
.start = 0,
.end = fixture.animation->frameNum - 1,
.animationFps = fixture.document->model.info.fps,
.fps = fixture.document->model.info.fps};
REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation,
fixture.bounds, SCALE, BACKGROUND, true));
Image sheet(options.path);
auto layout = spritesheet_layout_get(0, 0, fixture.animation->frameNum);
CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows));
golden_image_check("spin_sheet.png");
}
TEST_CASE("animation layers draw their child animations")
{
RenderFixture fixture("nested.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
RenderFixture fixture("nested.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
// The library's red square at half size starts on its fifth frame, centered at (48, 0); this file's Inner holds its
// red square at (-40, 0).
auto pixels = fixture.frame_get(0.0f);
for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)})
{
auto red = fixture.pixel_get(pixels, point);
CHECK(red.r > 200);
CHECK(red.g < 80);
}
// The library's red square at half size starts on its fifth frame, centered at (48, 0). This file's Inner holds its
// red square at (-40, 0).
auto pixels = fixture.frame_get(0.0f);
for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)})
{
auto red = fixture.pixel_get(pixels, point);
CHECK(red.r > 200);
CHECK(red.g < 80);
}
REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size),
pixels.data()));
golden_image_check("nested_frame_0.png");
REQUIRE(
Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data()));
golden_image_check("nested_frame_0.png");
}
TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter")
{
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
REQUIRE(fixture.document->is_valid());
// The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it; an
// 8 pixel box spreads a third of it out and takes as much from inside.
constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f};
auto sharp = fixture.frame_get(0.0f);
fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f;
fixture.animation = fixture.document->model.animation_get(0);
auto blurred = fixture.frame_get(0.0f);
CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40);
CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r);
// The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it. An
// 8 pixel box spreads a third of it out and takes as much from inside.
constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f};
auto sharp = fixture.frame_get(0.0f);
fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f;
fixture.animation = fixture.document->model.animation_get(0);
auto blurred = fixture.frame_get(0.0f);
CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40);
CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r);
REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size),
blurred.data()));
REQUIRE(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());
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);
// 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(Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size),
pixels.data()));
golden_image_check("vector_frame_0.png");
REQUIRE(
Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data()));
golden_image_check("vector_frame_0.png");
}
TEST_CASE("converting SVG spritesheets writes PNGs beside them")
{
auto directory = std::filesystem::temp_directory_path() / "anm2ed_vector_convert";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
for (auto name : {"vector.anm2", "vector.svg"})
std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / name);
auto directory = std::filesystem::temp_directory_path() / "anm2ed_vector_convert";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
for (auto name : {"vector.anm2", "vector.svg"})
std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / name);
Document document(directory / "vector.anm2", false);
REQUIRE(document.is_valid());
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));
CHECK_FALSE(document.texture_get(0)->is_vector());
CHECK(spritesheets_vector_used_get(document.model).empty());
Document document(directory / "vector.anm2", false);
REQUIRE(document.is_valid());
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));
CHECK_FALSE(document.texture_get(0)->is_vector());
CHECK(spritesheets_vector_used_get(document.model).empty());
document.undo();
CHECK(document.model.content.spritesheets.front().path == "vector.svg");
CHECK(document.texture_get(0)->is_vector());
std::filesystem::remove_all(directory);
document.undo();
CHECK(document.model.content.spritesheets.front().path == "vector.svg");
CHECK(document.texture_get(0)->is_vector());
std::filesystem::remove_all(directory);
}
TEST_CASE("a Rebirth save flattens animation layers for the game")
{
auto directory = std::filesystem::temp_directory_path() / "anm2ed_flatten";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory / "library");
std::filesystem::copy_file(RENDER_TEST_DIR / "nested.anm2", directory / "nested.anm2");
for (auto name : {"spin.anm2", "sheet.png"})
std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / "library" / name);
auto text = std::string{};
{
std::ifstream file(directory / "nested.anm2");
text.assign(std::istreambuf_iterator<char>(file), {});
}
text.replace(text.find("Path=\"spin.anm2\""), std::string("Path=\"spin.anm2\"").size(), "Path=\"library/spin.anm2\"");
std::ofstream(directory / "nested.anm2") << text;
auto directory = std::filesystem::temp_directory_path() / "anm2ed_flatten";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory / "library");
std::filesystem::copy_file(RENDER_TEST_DIR / "nested.anm2", directory / "nested.anm2");
for (auto name : {"spin.anm2", "sheet.png"})
std::filesystem::copy_file(RENDER_TEST_DIR / name, directory / "library" / name);
auto text = std::string{};
{
std::ifstream file(directory / "nested.anm2");
text.assign(std::istreambuf_iterator<char>(file), {});
}
text.replace(text.find("Path=\"spin.anm2\""), std::string("Path=\"spin.anm2\"").size(),
"Path=\"library/spin.anm2\"");
std::ofstream(directory / "nested.anm2") << text;
Document document(directory / "nested.anm2", false);
REQUIRE(document.is_valid());
REQUIRE(document.save(directory / "rebirth.anm2"));
std::ifstream file(directory / "rebirth.anm2");
std::string saved(std::istreambuf_iterator<char>(file), {});
auto game = saved.substr(0, saved.find("<SourceDocument"));
CHECK(game.find("Name=\"spin/red\"") != std::string::npos);
CHECK(game.find("Path=\"library/sheet.png\"") != std::string::npos);
CHECK(game.find(" Animation=\"") == std::string::npos);
CHECK(saved.find(" Animation=\"Spin\"") != std::string::npos);
std::filesystem::remove_all(directory);
Document document(directory / "nested.anm2", false);
REQUIRE(document.is_valid());
REQUIRE(document.save(directory / "rebirth.anm2"));
std::ifstream file(directory / "rebirth.anm2");
std::string saved(std::istreambuf_iterator<char>(file), {});
auto game = saved.substr(0, saved.find("<SourceDocument"));
CHECK(game.find("Name=\"spin/red\"") != std::string::npos);
CHECK(game.find("Path=\"library/sheet.png\"") != std::string::npos);
CHECK(game.find(" Animation=\"") == std::string::npos);
CHECK(saved.find(" Animation=\"Spin\"") != std::string::npos);
std::filesystem::remove_all(directory);
}
// The game's copy draws what the editor does: skew, blur and a skewed root baked into a spritesheet beside the save.
TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the same")
{
HeadlessGL gl = {};
if (!gl.is_valid()) return;
auto directory = std::filesystem::temp_directory_path() / "anm2ed_bake";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
std::filesystem::copy_file(RENDER_TEST_DIR / "sheet.png", directory / "sheet.png");
std::ofstream(directory / "bake.anm2") << R"({ "sheets": [ { "path": "sheet.png" } ],
HeadlessGL gl = {};
if (!gl.is_valid())
return;
auto directory = std::filesystem::temp_directory_path() / "anm2ed_bake";
std::filesystem::remove_all(directory);
std::filesystem::create_directories(directory);
std::filesystem::copy_file(RENDER_TEST_DIR / "sheet.png", directory / "sheet.png");
std::ofstream(directory / "bake.anm2") << R"({ "sheets": [ { "path": "sheet.png" } ],
"layers": [ { "name": "skewed" }, { "name": "blurred" } ],
"animations": {
"Layers": { "length": 6, "layers": [
@@ -274,54 +277,55 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the
"root": [ { "pos": [2, 3], "skew": [25, 10], "scale": [150, 100], "delay": 2 } ],
"layers": [ { "layer": 1, "frames": [ { "crop": [16, 0], "size": [16, 16], "pivot": [8, 8], "delay": 2 } ] } ] } } })";
Document document(directory / "bake.anm2", false);
REQUIRE(document.is_valid());
REQUIRE(document.save(directory / "saved.anm2"));
CHECK(std::filesystem::exists(directory / "saved.baked.png"));
std::string saved;
{
std::ifstream file(directory / "saved.anm2");
saved.assign(std::istreambuf_iterator<char>(file), {});
}
auto game = saved.substr(0, saved.find(" <SourceDocument")) + "</AnimatedActor>\n";
CHECK(game.find("SkewX") == std::string::npos);
CHECK(game.find("Blur") == std::string::npos);
std::ofstream(directory / "game.anm2") << game;
Document gameDocument(directory / "game.anm2", false);
REQUIRE(gameDocument.is_valid());
auto& info = SHADERS[SHADER_TEXTURE];
ShaderProgram shader(info.vertex, info.fragment);
Canvas canvas(glm::vec2(1.0f));
for (int index = 0; index < document.model.animations_count_get(); ++index)
{
auto& animation = *document.model.animation_get(index);
auto& gameAnimation = *gameDocument.model.animation_get(index);
INFO("animation: ", animation.name);
// On whole pixels, so the baked images land on the pixels they were drawn on.
auto bounds = animation_bounds_get(document, animation, true);
bounds = glm::vec4(glm::floor(glm::vec2(bounds)) - 8.0f, glm::ceil(glm::vec2(bounds.z, bounds.w)) + 16.0f);
for (int time = 0; time < animation.frameNum; ++time)
Document document(directory / "bake.anm2", false);
REQUIRE(document.is_valid());
REQUIRE(document.save(directory / "saved.anm2"));
CHECK(std::filesystem::exists(directory / "saved.baked.png"));
std::string saved;
{
INFO("time: ", time);
auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f,
glm::vec4(0.0f), true);
auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds,
1.0f, glm::vec4(0.0f), true);
REQUIRE(actual.size() == expected.size());
CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; }));
int mismatches = 0;
for (std::size_t i = 0; i < actual.size(); ++i)
mismatches += std::abs((int)actual[i] - (int)expected[i]) > CHANNEL_TOLERANCE;
CHECK((double)mismatches / (double)actual.size() <= MISMATCH_RATIO_MAX);
std::ifstream file(directory / "saved.anm2");
saved.assign(std::istreambuf_iterator<char>(file), {});
}
}
auto game = saved.substr(0, saved.find(" <SourceDocument")) + "</AnimatedActor>\n";
CHECK(game.find("SkewX") == std::string::npos);
CHECK(game.find("Blur") == std::string::npos);
std::ofstream(directory / "game.anm2") << game;
Document gameDocument(directory / "game.anm2", false);
REQUIRE(gameDocument.is_valid());
// Ignore and Save leaves them out: no baked layers or spritesheet.
document.model.info.isIsaacIgnored = true;
REQUIRE(document.save(directory / "ignored.anm2"));
CHECK_FALSE(std::filesystem::exists(directory / "ignored.baked.png"));
std::ifstream ignored(directory / "ignored.anm2");
CHECK(std::string(std::istreambuf_iterator<char>(ignored), {}).find("(baked)") == std::string::npos);
if (!std::getenv("ANM2ED_KEEP")) std::filesystem::remove_all(directory);
auto& info = SHADERS[SHADER_TEXTURE];
ShaderProgram shader(info.vertex, info.fragment);
Canvas canvas(glm::vec2(1.0f));
for (int index = 0; index < document.model.animations_count_get(); ++index)
{
auto& animation = *document.model.animation_get(index);
auto& gameAnimation = *gameDocument.model.animation_get(index);
INFO("animation: ", animation.name);
// On whole pixels, so the baked images land on the pixels they were drawn on.
auto bounds = animation_bounds_get(document, animation, true);
bounds = glm::vec4(glm::floor(glm::vec2(bounds)) - 8.0f, glm::ceil(glm::vec2(bounds.z, bounds.w)) + 16.0f);
for (int time = 0; time < animation.frameNum; ++time)
{
INFO("time: ", time);
auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f,
glm::vec4(0.0f), true);
auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, 1.0f,
glm::vec4(0.0f), true);
REQUIRE(actual.size() == expected.size());
CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; }));
int mismatches = 0;
for (std::size_t i = 0; i < actual.size(); ++i)
mismatches += std::abs((int)actual[i] - (int)expected[i]) > CHANNEL_TOLERANCE;
CHECK((double)mismatches / (double)actual.size() <= MISMATCH_RATIO_MAX);
}
}
// Ignore and Save leaves them out: no baked layers or spritesheet.
document.model.info.isIsaacIgnored = true;
REQUIRE(document.save(directory / "ignored.anm2"));
CHECK_FALSE(std::filesystem::exists(directory / "ignored.baked.png"));
std::ifstream ignored(directory / "ignored.anm2");
CHECK(std::string(std::istreambuf_iterator<char>(ignored), {}).find("(baked)") == std::string::npos);
if (!std::getenv("ANM2ED_KEEP"))
std::filesystem::remove_all(directory);
}
+8 -8
View File
@@ -2,12 +2,12 @@
TEST_CASE("fixtures match goldens")
{
auto fixtures = fixtures_get();
REQUIRE(!fixtures.empty());
for (auto& fixture : fixtures)
{
auto anm2 = model_load(file_load(fixture));
for (auto& [name, text] : variants_get(anm2))
golden_check(GOLDEN_DIR / std::format("{}.{}.xml", fixture.stem().string(), name), text);
}
auto fixtures = fixtures_get();
REQUIRE(!fixtures.empty());
for (auto& fixture : fixtures)
{
auto anm2 = model_load(file_load(fixture));
for (auto& [name, text] : variants_get(anm2))
golden_check(GOLDEN_DIR / std::format("{}.{}.xml", fixture.stem().string(), name), text);
}
}
+73 -72
View File
@@ -3,110 +3,111 @@
#include "edit/edit.h"
#include "selection.h"
static Model fixture_load_with_uids(const char* name) { return model_load(file_load(CORPUS_DIR / name)); }
static Model fixture_load_with_uids(const char* name)
{
return model_load(file_load(CORPUS_DIR / name));
}
// Applies an edit and follows the selection through it, the way a commit does.
void selection_edit(Model& anm2, Selection& selection, auto&& edit)
{
auto before = selection_focus_get(selection, UidIndex(anm2));
edit();
anm2.uids_repair();
selection_follow(selection, anm2, UidIndex(anm2), before);
auto before = selection_focus_get(selection, UidIndex(anm2));
edit();
anm2.uids_repair();
selection_follow(selection, anm2, UidIndex(anm2), before);
}
TEST_CASE("uids are unique and non-zero after load")
{
for (auto& fixture : fixtures_get())
{
auto anm2 = model_load(file_load(fixture));
std::set<std::uint64_t> uids;
bool isUnique = true;
for (auto [index, animation] : anm2.animations_get())
animation_tracks_each(*animation,
[&](const Track& track)
{
isUnique &= uids.insert(track.uid).second;
for (auto& frame : track.frames)
isUnique &= uids.insert(frame.uid).second;
});
INFO("fixture: ", fixture.filename().string());
CHECK(isUnique);
}
for (auto& fixture : fixtures_get())
{
auto anm2 = model_load(file_load(fixture));
std::set<std::uint64_t> uids;
bool isUnique = true;
for (auto [index, animation] : anm2.animations_get())
animation_tracks_each(*animation, [&](const Track& track) {
isUnique &= uids.insert(track.uid).second;
for (auto& frame : track.frames)
isUnique &= uids.insert(frame.uid).second;
});
INFO("fixture: ", fixture.filename().string());
CHECK(isUnique);
}
}
TEST_CASE("selected frames and focus follow inserts and moves")
{
auto anm2 = fixture_load_with_uids("02_items.anm2");
Selection selection = {};
selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}, {0, LAYER, 1, 0}});
selection_focus_set(selection, anm2, {0, LAYER, 0, 1});
auto anm2 = fixture_load_with_uids("02_items.anm2");
Selection selection = {};
selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}, {0, LAYER, 1, 0}});
selection_focus_set(selection, anm2, {0, LAYER, 0, 1});
selection_edit(anm2, selection, [&] { frame_insert(anm2, {0, LAYER, 0, -1}, 0); });
selection_edit(anm2, selection, [&] { frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); });
selection_edit(anm2, selection, [&] { frame_insert(anm2, {0, LAYER, 0, -1}, 0); });
selection_edit(anm2, selection, [&] { frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); });
UidIndex index(anm2);
CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0});
CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) ==
std::set<Reference>{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}});
UidIndex index(anm2);
CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0});
CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) ==
std::set<Reference>{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}});
}
TEST_CASE("a removed focus falls back to its nearest survivor")
{
auto anm2 = fixture_load_with_uids("02_items.anm2");
Selection selection = {};
selection_focus_set(selection, anm2, {0, LAYER, 0, 1});
selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}});
auto anm2 = fixture_load_with_uids("02_items.anm2");
Selection selection = {};
selection_focus_set(selection, anm2, {0, LAYER, 0, 1});
selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}});
selection_edit(anm2, selection, [&] { frames_delete(anm2, {{0, LAYER, 0, 1}}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0});
CHECK(selection.uids[SelectionKind::FRAMES].empty());
selection_edit(anm2, selection, [&] { frames_delete(anm2, {{0, LAYER, 0, 1}}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0});
CHECK(selection.uids[SelectionKind::FRAMES].empty());
selection_edit(anm2, selection, [&] { items_remove(anm2, 0, {{LAYER, {0}}}, {}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT});
selection_edit(anm2, selection, [&] { items_remove(anm2, 0, {{LAYER, {0}}}, {}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT});
selection_focus_set(selection, anm2, {1, ROOT, -1, 0});
selection_edit(anm2, selection, [&] { animations_remove(anm2, {1}, {}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT});
selection_focus_set(selection, anm2, {1, ROOT, -1, 0});
selection_edit(anm2, selection, [&] { animations_remove(anm2, {1}, {}); });
CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT});
}
TEST_CASE("track and group selection follow regrouping")
{
auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2");
const TrackGroup* group = nullptr;
groups_each(anm2.animation_get(0)->layers, [&](const TrackGroup& candidate) { group = &candidate; });
REQUIRE(group);
auto groupId = group->id;
Selection selection = {};
selection_references_set(selection, anm2, SelectionKind::TRACKS, {{0, LAYER, 0, -1, LAYER, groupId}});
selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, groupId}});
auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2");
const TrackGroup* group = nullptr;
groups_each(anm2.animation_get(0)->layers, [&](const TrackGroup& candidate) { group = &candidate; });
REQUIRE(group);
auto groupId = group->id;
Selection selection = {};
selection_references_set(selection, anm2, SelectionKind::TRACKS, {{0, LAYER, 0, -1, LAYER, groupId}});
selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, groupId}});
selection_edit(anm2, selection,
[&] { items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); });
selection_edit(anm2, selection, [&] { items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); });
UidIndex index(anm2);
CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set<Reference>{{0, LAYER, 0}});
CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == std::set<Reference>{{0, LAYER, groupId}});
UidIndex index(anm2);
CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set<Reference>{{0, LAYER, 0}});
CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) ==
std::set<Reference>{{0, LAYER, groupId}});
}
TEST_CASE("content selection follows items, and regions follow the focused spritesheet")
{
auto anm2 = fixture_load_with_uids("05_regions.anm2");
Selection selection = {};
auto& regions = item_get(anm2.content.spritesheets, 0)->regions;
REQUIRE(regions.size() > 1);
auto regionId = regions[1].id;
auto anm2 = fixture_load_with_uids("05_regions.anm2");
Selection selection = {};
auto& regions = item_get(anm2.content.spritesheets, 0)->regions;
REQUIRE(regions.size() > 1);
auto regionId = regions[1].id;
selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId});
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty());
selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId});
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty());
selection_focus_id_set(selection, anm2, SelectionKind::SPRITESHEETS, 0);
selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId});
selection_focus_id_set(selection, anm2, SelectionKind::REGIONS, regionId);
regions.erase(regions.begin());
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set<int>{regionId});
CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId);
selection_focus_id_set(selection, anm2, SelectionKind::SPRITESHEETS, 0);
selection_ids_set(selection, anm2, SelectionKind::REGIONS, {regionId});
selection_focus_id_set(selection, anm2, SelectionKind::REGIONS, regionId);
regions.erase(regions.begin());
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set<int>{regionId});
CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId);
std::erase_if(regions, [&](const Region& region) { return region.id == regionId; });
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty());
CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1);
std::erase_if(regions, [&](const Region& region) { return region.id == regionId; });
CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty());
CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1);
}
+106 -101
View File
@@ -11,124 +11,129 @@ constexpr int UNDO_LIMIT = 1000;
static std::vector<Reference> references_all_get(const Model& anm2, bool isFrames)
{
UidIndex index(anm2);
std::vector<Reference> result;
auto add = [&](std::uint64_t uid)
{
auto reference = index.reference_get(uid);
if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER) return;
if (isFrames == (reference->frameIndex >= 0)) result.push_back(*reference);
};
for (auto [i, animation] : anm2.animations_get())
animation_tracks_each(*animation,
[&](const Track& track)
{
add(track.uid);
for (auto& frame : track.frames)
add(frame.uid);
});
return result;
UidIndex index(anm2);
std::vector<Reference> result;
auto add = [&](std::uint64_t uid) {
auto reference = index.reference_get(uid);
if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER)
return;
if (isFrames == (reference->frameIndex >= 0))
result.push_back(*reference);
};
for (auto [i, animation] : anm2.animations_get())
animation_tracks_each(*animation, [&](const Track& track) {
add(track.uid);
for (auto& frame : track.frames)
add(frame.uid);
});
return result;
}
// One random edit on randomly chosen live elements; returns false when nothing applicable exists.
// One random edit on randomly chosen live elements. Returns false when nothing applicable exists.
static bool edit_random_apply(Model& anm2, std::mt19937& random)
{
auto frames = references_all_get(anm2, true);
auto tracks = references_all_get(anm2, false);
if (frames.empty() || tracks.empty()) return false;
auto pick = [&](const auto& items)
{ return items[std::uniform_int_distribution<int>(0, (int)items.size() - 1)(random)]; };
auto frame = pick(frames);
auto other = pick(frames);
auto frames = references_all_get(anm2, true);
auto tracks = references_all_get(anm2, false);
if (frames.empty() || tracks.empty())
return false;
auto pick = [&](const auto& items) {
return items[std::uniform_int_distribution<int>(0, (int)items.size() - 1)(random)];
};
auto frame = pick(frames);
auto other = pick(frames);
switch (std::uniform_int_distribution<int>(0, 8)(random))
{
case 0:
frame_insert(anm2, frame, 0);
break;
case 1:
if (frames.size() > 4) frames_delete(anm2, {frame, other});
break;
case 2:
frames_duplicate(anm2, {frame, other}, frame);
break;
case 3:
frames_reverse(anm2, {frame, other});
break;
case 4:
frames_bake(anm2, {frame}, 1, false, false);
break;
case 5:
frame_split(anm2, frame, 1);
break;
case 6:
if (frame.itemType != ROOT) frames_move(anm2, {frame}, pick(tracks), 0);
break;
case 7:
animation_add(anm2, 0, -1, frame.animationIndex, "Walk");
break;
default:
animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0});
break;
}
return true;
switch (std::uniform_int_distribution<int>(0, 8)(random))
{
case 0:
frame_insert(anm2, frame, 0);
break;
case 1:
if (frames.size() > 4)
frames_delete(anm2, {frame, other});
break;
case 2:
frames_duplicate(anm2, {frame, other}, frame);
break;
case 3:
frames_reverse(anm2, {frame, other});
break;
case 4:
frames_bake(anm2, {frame}, 1, false, false);
break;
case 5:
frame_split(anm2, frame, 1);
break;
case 6:
if (frame.itemType != ROOT)
frames_move(anm2, {frame}, pick(tracks), 0);
break;
case 7:
animation_add(anm2, 0, -1, frame.animationIndex, "Walk");
break;
default:
animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0});
break;
}
return true;
}
TEST_CASE("undo and redo restore every state of a random edit walk")
{
SnapshotStack::max_size_set(UNDO_LIMIT);
for (auto name :
{"02_items.anm2", "03a_groups_nested.anm2", "04_group_root_transform.anm2", "07_special_interpolation.anm2"})
{
INFO("fixture: ", name);
Snapshots snapshots = {};
snapshots.current.model = model_load(file_load(CORPUS_DIR / name));
std::mt19937 random(WALK_SEED);
std::vector<std::uint64_t> hashes{model_hash(snapshots.current.model)};
for (int step = 0; step < WALK_STEPS; ++step)
SnapshotStack::max_size_set(UNDO_LIMIT);
for (auto name :
{"02_items.anm2", "03a_groups_nested.anm2", "04_group_root_transform.anm2", "07_special_interpolation.anm2"})
{
snapshots.push("Edit");
if (!edit_random_apply(snapshots.current.model, random)) break;
auto count = snapshots.undoStack.size();
snapshots.commit();
if (snapshots.undoStack.size() != count) hashes.push_back(model_hash(snapshots.current.model));
}
REQUIRE(hashes.size() > 1);
INFO("fixture: ", name);
Snapshots snapshots = {};
snapshots.current.model = model_load(file_load(CORPUS_DIR / name));
std::mt19937 random(WALK_SEED);
for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it)
{
REQUIRE(snapshots.undo());
CHECK(model_hash(snapshots.current.model) == *it);
}
CHECK_FALSE(snapshots.undo());
std::vector<std::uint64_t> hashes{model_hash(snapshots.current.model)};
for (int step = 0; step < WALK_STEPS; ++step)
{
snapshots.push("Edit");
if (!edit_random_apply(snapshots.current.model, random))
break;
auto count = snapshots.undoStack.size();
snapshots.commit();
if (snapshots.undoStack.size() != count)
hashes.push_back(model_hash(snapshots.current.model));
}
REQUIRE(hashes.size() > 1);
for (auto it = hashes.begin() + 1; it != hashes.end(); ++it)
{
REQUIRE(snapshots.redo());
CHECK(model_hash(snapshots.current.model) == *it);
for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it)
{
REQUIRE(snapshots.undo());
CHECK(model_hash(snapshots.current.model) == *it);
}
CHECK_FALSE(snapshots.undo());
for (auto it = hashes.begin() + 1; it != hashes.end(); ++it)
{
REQUIRE(snapshots.redo());
CHECK(model_hash(snapshots.current.model) == *it);
}
}
}
}
TEST_CASE("selection follows its frame through an edit and its undo")
{
Snapshots snapshots = {};
auto& current = snapshots.current;
current.model = model_load(file_load(CORPUS_DIR / "02_items.anm2"));
selection_focus_set(current.selection, current.model, {0, LAYER, 0, 1});
selection_references_set(current.selection, current.model, SelectionKind::FRAMES, {{0, LAYER, 0, 1}});
Snapshots snapshots = {};
auto& current = snapshots.current;
current.model = model_load(file_load(CORPUS_DIR / "02_items.anm2"));
selection_focus_set(current.selection, current.model, {0, LAYER, 0, 1});
selection_references_set(current.selection, current.model, SelectionKind::FRAMES, {{0, LAYER, 0, 1}});
snapshots.push("Insert");
frame_insert(current.model, {0, LAYER, 0, -1}, 0);
auto& track = *current.model.track_edit(Reference{0, LAYER, 0});
std::rotate(track.frames.begin(), track.frames.end() - 1, track.frames.end());
snapshots.commit();
UidIndex index(current.model);
CHECK(selection_focus_get(current.selection, index) == Reference{0, LAYER, 0, 2});
CHECK(selection_references_get(current.selection, index, SelectionKind::FRAMES) ==
std::set<Reference>{{0, LAYER, 0, 2}});
snapshots.push("Insert");
frame_insert(current.model, {0, LAYER, 0, -1}, 0);
auto& track = *current.model.track_edit(Reference{0, LAYER, 0});
std::rotate(track.frames.begin(), track.frames.end() - 1, track.frames.end());
snapshots.commit();
UidIndex index(current.model);
CHECK(selection_focus_get(current.selection, index) == Reference{0, LAYER, 0, 2});
CHECK(selection_references_get(current.selection, index, SelectionKind::FRAMES) ==
std::set<Reference>{{0, LAYER, 0, 2}});
REQUIRE(snapshots.undo());
CHECK(selection_focus_get(current.selection, UidIndex(current.model)) == Reference{0, LAYER, 0, 1});
REQUIRE(snapshots.undo());
CHECK(selection_focus_get(current.selection, UidIndex(current.model)) == Reference{0, LAYER, 0, 1});
}