diff --git a/src/document.cpp b/src/document.cpp index 39f8694..c585a22 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -214,7 +214,7 @@ namespace anm2ed { auto absolutePath = !path.empty() ? path : this->path; auto absolutePathUtf8 = path::to_utf8(absolutePath); - if (model::model_save(model, absolutePath, errorString, {.isExtendedFormat = model.isExtendedFormat})) + if (file_write(absolutePath, errorString)) { this->path = absolutePath; toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); @@ -225,6 +225,26 @@ namespace anm2ed return false; } + // Writes the document; a Rebirth document's game copy has its animation layers flattened into plain layers. + bool Document::file_write(const std::filesystem::path& path, std::string* errorString) + { + std::optional game{}; + if (!model.isExtendedFormat && std::ranges::any_of(model.content.layers, &model::Layer::is_animation)) + game = edit::animation_layers_flatten( + model, library_resolver_get(), + [&](const model::Model& source, const std::filesystem::path& spritesheetPath) + { + for (const auto& [libraryPath, library] : libraries) + if (&library.model == &source) + return path::backslash_replace( + path::make_relative(document::absolute_path_get(libraryPath.parent_path(), spritesheetPath), + std::filesystem::absolute(directory_get()))); + return spritesheetPath; + }); + return model::model_save(model, path, errorString, + {.isExtendedFormat = model.isExtendedFormat, .gameModel = game ? &*game : nullptr}); + } + std::filesystem::path Document::autosave_path_get() { return directory_get() / @@ -244,7 +264,7 @@ namespace anm2ed { auto autosavePath = autosave_path_get(); auto autosavePathUtf8 = path::to_utf8(autosavePath); - if (model::model_save(model, autosavePath, errorString, {.isExtendedFormat = model.isExtendedFormat})) + if (file_write(autosavePath, errorString)) { for (auto id : spritesheets_autosave_dirty_get()) { @@ -388,9 +408,11 @@ namespace anm2ed : std::filesystem::path{}; } + // A library of this document (or of a copy of it) or of one of its libraries. const LibraryData* Document::library_get(const model::Model& from, int id) const { - auto link = libraryLinks.find({&from == &model ? nullptr : &from, id}); + auto isLibrary = std::ranges::any_of(libraries, [&](const auto& pair) { return &pair.second.model == &from; }); + auto link = libraryLinks.find({isLibrary ? &from : nullptr, id}); return link == libraryLinks.end() ? nullptr : link->second; } @@ -403,6 +425,15 @@ namespace anm2ed }; } + // An animation layer whose animation isn't there; a library that didn't load leaves the question open (false). + bool Document::is_layer_animation_missing(const model::Layer& layer) const + { + if (!layer.is_animation()) return false; + auto library = layer.libraryId == -1 ? nullptr : library_get(model, layer.libraryId); + auto source = layer.libraryId == -1 ? &model : library && library->model.isValid ? &library->model : nullptr; + return source && !source->animation_named_get(layer.animation); + } + // The animation names of library `libraryId`, or of this document at -1. std::vector Document::animation_names_get(int libraryId) const { @@ -455,7 +486,11 @@ namespace anm2ed { auto path = document::absolute_path_get(directory, library.path); auto [it, isNew] = libraries.try_emplace(path); - if (isNew) document::library_load(path, it->second); + if (isNew) + { + document::library_load(path, it->second); + ++librariesRevision; + } libraryLinks[{from == &model ? nullptr : from, library.id}] = &it->second; if (reached.insert(path).second) pending.emplace_back(&it->second.model, path.parent_path()); } @@ -473,6 +508,7 @@ namespace anm2ed auto time = std::filesystem::last_write_time(path, ec); if (ec || time == library.writeTime) continue; document::library_load(path, library); + ++librariesRevision; isReloaded = true; } if (isReloaded) assets_sync(); diff --git a/src/document.hpp b/src/document.hpp index 97030d0..3ccb1f1 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -78,6 +78,7 @@ namespace anm2ed // Libraries by absolute path, and what each (document, library id) points at (nullptr is this document). std::map libraries{}; std::map, const LibraryData*> libraryLinks{}; + std::uint64_t librariesRevision{}; // counts library loads, for anything drawn from them // Vector spritesheets drawn again for zooms past 100%, by (image uid, power-of-two level). mutable std::map, resource::Image> vectorImages{}; bool isAnimationPreviewSet{false}; @@ -115,6 +116,7 @@ namespace anm2ed Document(Document&&) noexcept; Document& operator=(Document&&) noexcept; bool save(const std::filesystem::path& = {}, std::string* = nullptr); + bool file_write(const std::filesystem::path&, std::string* = nullptr); void assets_sync(); void texture_change(int); bool texture_reload(int); @@ -163,6 +165,7 @@ namespace anm2ed } std::vector references_get(const edit::Uids&) const; bool is_dirty() const; + bool is_layer_animation_missing(const model::Layer&) const; bool is_autosave_dirty(); std::filesystem::path directory_get() const; std::filesystem::path filename_get() const; diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp index 0d922b7..1a7517c 100644 --- a/src/edit/edit.hpp +++ b/src/edit/edit.hpp @@ -9,6 +9,7 @@ #include #include "image.hpp" +#include "model/draw.hpp" #include "model/model.hpp" // Document edits as plain functions of the model. Each returns the uids of the elements it created or changed that @@ -137,5 +138,9 @@ namespace anm2ed::edit std::optional spritesheets_merge(model::Model&, const std::set&, const ImageGet&, bool, bool, bool, Origin); int event_id_resolve(model::Model&, int); + + // Where a spritesheet path of a document (this one, or a library) points, from this document. + using SpritesheetPathGet = std::function; + model::Model animation_layers_flatten(model::Model, const model::LibraryGet&, const SpritesheetPathGet&); bool file_merge(model::Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); } diff --git a/src/edit/flatten.cpp b/src/edit/flatten.cpp new file mode 100644 index 0000000..fcc4b84 --- /dev/null +++ b/src/edit/flatten.cpp @@ -0,0 +1,130 @@ +#include "edit.hpp" + +#include +#include +#include + +#include "math.hpp" + +using namespace anm2ed::model; +using namespace anm2ed::util; + +namespace anm2ed::edit +{ + // A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and + // rotation. Skew has no place in a plain frame, and is dropped. + Frame draw_frame_bake(const Draw& draw) + { + auto frame = draw.frame; + auto size = glm::max(frame.size, glm::vec2(1.0f)); + auto model = draw.parent * draw_quad_model_get(draw); + auto column0 = glm::vec2(model[0]) / size.x; + auto column1 = glm::vec2(model[1]) / size.y; + auto scaleX = glm::length(column0); + auto determinant = column0.x * column1.y - column0.y * column1.x; + frame.position = glm::vec2(model * glm::vec4(frame.pivot / size, 0.0f, 1.0f)); + frame.scale = math::unit_to_percent(glm::vec2(scaleX, scaleX > 0.0f ? determinant / scaleX : 0.0f)); + frame.rotation = glm::degrees(std::atan2(column0.y, column0.x)); + frame.skew = {}; + frame.depth = 0; + frame.regionId = -1; + frame.duration = FRAME_DURATION_MIN; + frame.interpolation = Interpolation::NONE; + frame.isVisible = true; + return frame; + } + + bool is_frame_baked_equal(Frame a, const Frame& b) + { + a.uid = b.uid; + a.duration = b.duration; + return a == b; + } + + // The game's copy of a document: each animation layer's track becomes plain layer tracks (one per layer its child + // animation draws), baked a frame at a time. A library's spritesheets join the copy, at paths from `path_get`. + Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get) + { + auto& content = model.content; + if (std::ranges::none_of(content.layers, &Layer::is_animation)) return model; + + std::map, int> spritesheetIds{}; + auto spritesheet_id_get = [&](const Model* source, int id) + { + if (source == &model) return id; + auto [it, isNew] = spritesheetIds.try_emplace({source, id}); + if (!isNew) return it->second; + auto spritesheet = item_get(source->content.spritesheets, id); + it->second = item_next_id_get(content.spritesheets); + content.spritesheets.push_back( + {.id = it->second, .path = spritesheet ? path_get(*source, spritesheet->path) : std::filesystem::path{}}); + return it->second; + }; + + // (animation layer, source, source layer) -> the plain layer standing in for it. + std::map, int> layerIds{}; + auto layer_id_get = [&](const Draw& draw) + { + auto [it, isNew] = layerIds.try_emplace({draw.id, draw.source, draw.sourceId}); + if (!isNew) return it->second; + auto parent = item_get(content.layers, draw.id); + auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId); + it->second = item_next_id_get(content.layers); + content.layers.push_back({.id = it->second, + .name = parent->name + "/" + (sourceLayer ? sourceLayer->name : std::string{}), + .spritesheetId = spritesheet_id_get(draw.source, draw.spritesheetId)}); + return it->second; + }; + + for (int index = 0; index < model.animations_count_get(); ++index) + { + // Drawn as stored, so an animation layer playing its own animation is still caught. + auto& source = *model.animation_get(index); + auto tracks_flatten = [&](const Track& track) + { + auto layer = item_get(content.layers, track.id); + if (!layer || !layer->is_animation()) return std::vector{track}; + std::map> frames{}; + std::vector order{}; + for (int time = 0; time < source.frameNum; ++time) + for (const auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get})) + { + if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2()) continue; + auto id = layer_id_get(draw); + auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false}); + if (isNew) order.push_back(id); + it->second[time] = draw_frame_bake(draw); + } + std::vector tracks{}; + for (auto id : order) + { + auto& baked = tracks.emplace_back(Track{.type = ItemType::LAYER, .id = id, .isVisible = track.isVisible}); + for (auto& frame : frames[id]) + if (!baked.frames.empty() && is_frame_baked_equal(frame, baked.frames.back())) + ++baked.frames.back().duration; + else + baked.frames.push_back(frame); + } + return tracks; + }; + + std::vector entries{}; + for (auto& entry : source.layers) + if (auto track = std::get_if(&entry)) + for (auto& flat : tracks_flatten(*track)) + entries.emplace_back(std::move(flat)); + else + { + auto group = std::get(entry); + group.tracks.clear(); + for (auto& groupTrack : std::get(entry).tracks) + for (auto& flat : tracks_flatten(groupTrack)) + group.tracks.push_back(std::move(flat)); + entries.emplace_back(std::move(group)); + } + model.animation_edit(index)->layers = std::move(entries); + } + std::erase_if(content.layers, [](const Layer& layer) { return layer.is_animation(); }); + return model; + } +} diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index c6bb8db..2cc9543 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -749,7 +749,7 @@ namespace anm2ed::imgui if (settings.onionskinIsEnabled && settings.onionskinIsPivotPath && !isIsolated) { - auto key = std::tuple{document.hash, reference.animationIndex, isRootTransform}; + auto key = std::tuple{document.hash, document.librariesRevision, reference.animationIndex, isRootTransform}; if (key != pivotPathsKey || pivotPaths.empty()) { pivotPathsKey = key; diff --git a/src/imgui/window/animation_preview.hpp b/src/imgui/window/animation_preview.hpp index 39380c1..5bc3f7c 100644 --- a/src/imgui/window/animation_preview.hpp +++ b/src/imgui/window/animation_preview.hpp @@ -34,7 +34,7 @@ namespace anm2ed::imgui std::vector points{}; }; std::vector pivotPaths{}; - std::tuple pivotPathsKey{}; + std::tuple pivotPathsKey{}; void recording_start(Manager&, Settings&, Document&, const model::Animation*); void recording_stop(Manager&, Document&); diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp index 855429c..c4160ad 100644 --- a/src/imgui/window/items.cpp +++ b/src/imgui/window/items.cpp @@ -167,17 +167,22 @@ namespace anm2ed::imgui track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, TOOLTIP_ADD_LAYER, TOOLTIP_REMOVE_UNUSED_LAYERS, EDIT_REMOVE_UNUSED_LAYERS, EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, layers_get); - ListRows rows{ - .label_get = [&](int id) { return layer_label_get(*model::item_get(layers, id)); }, - .tooltip_draw = - [&](int id) - { - auto layer = model::item_get(layers, id); - item_tooltip_draw(resources, layer->name, id); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)).c_str()); - }, - .activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }}; + ListRows rows{.label_get = [&](int id) { return layer_label_get(*model::item_get(layers, id)); }, + .is_invalid = [&](int id) + { return document.is_layer_animation_missing(*model::item_get(layers, id)); }, + .tooltip_draw = + [&](int id) + { + auto layer = model::item_get(layers, id); + item_tooltip_draw(resources, layer->name, id); + if (document.is_layer_animation_missing(*layer)) + ImGui::TextUnformatted(localize.get(TOOLTIP_LAYER_ANIMATION_MISSING)); + else if (!layer->is_animation()) + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_SPRITESHEET_ID), + std::make_format_args(layer->spritesheetId)) + .c_str()); + }, + .activate = [&](int id) { manager.item_properties_open(ElementType::LAYER_ELEMENT, id); }}; list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE_UNUSED}}, [&]() { content_list_draw(panel, SelectionKind::LAYERS, item_ids_get(layers), rows); }); } diff --git a/src/imgui/window/panel.cpp b/src/imgui/window/panel.cpp index 5330b61..a29a980 100644 --- a/src/imgui/window/panel.cpp +++ b/src/imgui/window/panel.cpp @@ -122,9 +122,11 @@ namespace anm2ed::imgui auto font = rows.font_get ? rows.font_get(key) : isFocused ? font::ITALICS : font::REGULAR; auto label = rows.label_get(key); + auto isInvalid = rows.is_invalid && rows.is_invalid(key); ImGui::PushID(key); ImGui::SetNextItemSelectionUserData(index); if (font != font::REGULAR) ImGui::PushFont(panel.resources.fonts[font].get(), font::SIZE); + if (isInvalid) ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID); if (arrowKey == key) ImGui::SetKeyboardFocusHere(); bool isActivated{}; @@ -157,6 +159,7 @@ namespace anm2ed::imgui if (isActivated || ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) row_select(selection, focus, rows, key); + if (isInvalid) ImGui::PopStyleColor(); if (font != font::REGULAR) ImGui::PopFont(); row_scroll_update(state, key, arrowKey); if (state.newId == key) state.newId = -1; diff --git a/src/imgui/window/panel.hpp b/src/imgui/window/panel.hpp index 86c79d9..b16ca68 100644 --- a/src/imgui/window/panel.hpp +++ b/src/imgui/window/panel.hpp @@ -72,6 +72,7 @@ namespace anm2ed::imgui std::function name_get{}; std::function rename{}; std::function is_locked{}; + std::function is_invalid{}; std::function font_get{}; std::function tooltip_draw{}; std::function image_get{}; diff --git a/src/model/common.hpp b/src/model/common.hpp index c236248..3b0f3e7 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -165,9 +165,17 @@ namespace anm2ed constexpr Flags SERIALIZE_ANM2ED_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; + namespace model + { + class Model; + } + + // How a document saves: the editor's document alone (extended), or the game's copy with the editor's embedded; + // `gameModel` is the game's copy when it differs from the document (animation layers flattened). struct Options { bool isExtendedFormat{}; + const model::Model* gameModel{}; }; #define FRAME_CHANGE_SCALARS \ diff --git a/src/model/draw.cpp b/src/model/draw.cpp index ba01acf..97dc112 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -212,7 +212,8 @@ namespace anm2ed::model } } layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); - draws.push_back({type, id, groupType, sample, time, frame, parent, &model, layer ? layer->spritesheetId : -1}); + draws.push_back( + {type, id, groupType, sample, time, frame, parent, &model, layer ? layer->spritesheetId : -1, id}); } }; if (animation.root.isVisible) track_draws_add(animation.root, DrawType::ROOT, -1, NONE, nullptr); diff --git a/src/model/draw.hpp b/src/model/draw.hpp index b2a3425..d3ec8e4 100644 --- a/src/model/draw.hpp +++ b/src/model/draw.hpp @@ -50,6 +50,7 @@ namespace anm2ed::model glm::mat4 parent{1.0f}; const Model* source{}; int spritesheetId{-1}; + int sourceId{-1}; // the layer of `source` drawn (a child's, for an animation layer's draws) }; // A trigger that fires, from the animation played or a child animation (whose ids belong to `source`). diff --git a/src/model/xml.cpp b/src/model/xml.cpp index 62e2976..b98fdf6 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -1766,7 +1766,7 @@ namespace anm2ed::model { if (options.isExtendedFormat) return model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_EXTENDED_DOCUMENT); - model_write(sink, model, SERIALIZE_ISAAC_DEFAULT, + model_write(sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT, [&]() { model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT, {}, SOURCE_DOCUMENT_TAG); }); } diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 5e6dc59..3962970 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -234,7 +234,7 @@ namespace anm2ed X(FORMAT_EVENT_LABEL, "Event: {0}", "Evento: {0}", "Событие: {0}", "事件: {0}", "이벤트: {0}") \ X(FORMAT_ID, "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}") \ X(FORMAT_ISAAC_ALPHA_OFFSET_FRAMES, "{} frame(s) use an alpha offset, which the game doesn't support; it will be dropped.", "{} Frame(s) usan un desplazamiento de alfa, que el juego no soporta; se descartará.", "{} кадр(ов) используют смещение альфы, которое игра не поддерживает; оно будет отброшено.", "{} 帧使用了透明度偏移,游戏不支持;将被丢弃。", "{}개의 프레임이 알파 오프셋을 사용합니다. 게임에서 지원하지 않으므로 제거됩니다.") \ - X(FORMAT_ISAAC_ANIMATION_LAYERS, "{} layer(s) play animations, which the game doesn't support; they will draw nothing.", "{} capa(s) reproducen animaciones, que el juego no soporta; no dibujarán nada.", "{} слой(ёв) проигрывают анимации, которые игра не поддерживает; они ничего не отобразят.", "{} 个图层播放动画,游戏不支持;它们将不显示任何内容。", "{}개의 레이어가 애니메이션을 재생합니다. 게임에서 지원하지 않으므로 아무것도 그리지 않습니다.") \ + X(FORMAT_ISAAC_ANIMATION_LAYERS, "{} layer(s) play animations, which the game doesn't support; they will be flattened into plain layers (one per layer of the animation, a frame at a time, without skew).", "{} capa(s) reproducen animaciones, que el juego no soporta; se aplanarán en capas normales (una por capa de la animación, Frame a Frame, sin inclinación).", "{} слой(ёв) проигрывают анимации, которые игра не поддерживает; они будут развёрнуты в обычные слои (по одному на слой анимации, покадрово, без наклона).", "{} 个图层播放动画,游戏不支持;它们将被展开为普通图层(动画的每个图层一个,逐帧,无倾斜)。", "{}개의 레이어가 애니메이션을 재생합니다. 게임에서 지원하지 않으므로 일반 레이어로 펼쳐집니다(애니메이션의 레이어마다 하나씩, 프레임 단위, 기울이기 제외).") \ X(FORMAT_ISAAC_BLUR_FRAMES, "{} frame(s) blur their layer, which the game doesn't support; they will draw sharp.", "{} Frame(s) desenfocan su capa, que el juego no soporta; se dibujarán nítidos.", "{} кадр(ов) размывают слой, что игра не поддерживает; они будут нарисованы чётко.", "{} 个帧模糊了图层,游戏不支持,将清晰绘制。", "프레임 {}개가 게임이 지원하지 않는 레이어 흐림을 사용합니다. 선명하게 그려집니다.") \ X(FORMAT_ISAAC_DEPTH_FRAMES, "{} frame(s) change their layer's depth, which the game doesn't support; they will draw in timeline order.", "{} Frame(s) cambian la profundidad de su capa, que el juego no soporta; se dibujarán en el orden de la línea de tiempo.", "{} кадр(ов) меняют глубину слоя, что игра не поддерживает; они будут рисоваться в порядке таймлайна.", "{} 个帧改变了图层深度,游戏不支持,将按时间轴顺序绘制。", "프레임 {}개가 게임이 지원하지 않는 레이어 깊이를 바꿉니다. 타임라인 순서로 그려집니다.") \ X(FORMAT_ISAAC_EASED_FRAMES, "{} eased frame(s) will be baked into one-frame steps.", "{} Frame(s) con suavizado se convertirán en pasos de un Frame.", "{} кадр(ов) со сглаживанием будут запечены в покадровые шаги.", "{} 个缓动帧将被烘焙为逐帧步进。", "이징 프레임 {}개가 1프레임 단위로 베이크됩니다.") \ @@ -585,8 +585,9 @@ namespace anm2ed X(TOOLTIP_EVENT_BUILT_IN, "A built-in event: it can't be renamed, and is added to the file when a trigger first uses it.", "Un evento integrado: no se puede renombrar y se añade al archivo cuando un trigger lo usa por primera vez.", "Встроенное событие: его нельзя переименовать; оно добавляется в файл, когда триггер впервые его использует.", "内置事件:不能重命名,当触发器首次使用时添加到文件中。", "내장 이벤트: 이름을 바꿀 수 없으며 트리거가 처음 사용할 때 파일에 추가됩니다.") \ X(TOOLTIP_ISAAC_COMPATIBILITY_WARNING, "Before saving, list anything the game doesn't support and what will happen to it.", "Antes de guardar, muestra lo que el juego no soporta y lo que pasará con ello.", "Перед сохранением показывать всё, что игра не поддерживает, и что с этим произойдёт.", "保存前列出游戏不支持的内容及其处理方式。", "저장하기 전에 게임이 지원하지 않는 항목과 그 처리 방식을 알려줍니다.") \ X(TOOLTIP_LAYER_ANIMATION, "The animation this layer plays.", "La animación que reproduce esta capa.", "Анимация, которую проигрывает этот слой.", "此图层播放的动画。", "이 레이어가 재생하는 애니메이션.") \ + X(TOOLTIP_LAYER_ANIMATION_MISSING, "This layer's animation isn't in its file; it draws nothing.", "La animación de esta capa no está en su archivo; no dibuja nada.", "Анимации этого слоя нет в её файле; слой ничего не рисует.", "此图层的动画不在其文件中;它不会绘制任何内容。", "이 레이어의 애니메이션이 파일에 없어 아무것도 그리지 않습니다.") \ X(TOOLTIP_LAYER_LIBRARY, "Where the animation comes from: this file, or a library.", "De dónde viene la animación: este archivo o una biblioteca.", "Откуда берётся анимация: этот файл или библиотека.", "动画来自哪里:此文件或库。", "애니메이션의 출처: 이 파일 또는 라이브러리.") \ - X(TOOLTIP_LAYER_SOURCE, "Show a spritesheet, or play an animation (from this file or a library).\n(Animations are editor only; the game draws nothing for them.)", "Muestra un spritesheet o reproduce una animación (de este archivo o de una biblioteca).\n(Las animaciones son solo del editor; el juego no dibuja nada para ellas.)", "Показывать спрайт-лист или проигрывать анимацию (из этого файла или библиотеки).\n(Анимации только для редактора; игра для них ничего не рисует.)", "显示图集,或播放动画(来自此文件或库)。\n(动画仅限编辑器;游戏不会绘制它们。)", "스프라이트 시트를 표시하거나 애니메이션을 재생합니다(이 파일 또는 라이브러리에서).\n(애니메이션은 에디터 전용이며 게임에서는 아무것도 그리지 않습니다.)") \ + X(TOOLTIP_LAYER_SOURCE, "Show a spritesheet, or play an animation (from this file or a library).\n(A Rebirth save flattens animation layers into plain layers for the game.)", "Muestra un spritesheet o reproduce una animación (de este archivo o de una biblioteca).\n(Un guardado de Rebirth aplana las capas de animación en capas normales para el juego.)", "Показывать спрайт-лист или проигрывать анимацию (из этого файла или библиотеки).\n(При сохранении для Rebirth слои анимации разворачиваются в обычные слои для игры.)", "显示图集,或播放动画(来自此文件或库)。\n(Rebirth 保存会为游戏将动画图层展开为普通图层。)", "스프라이트 시트를 표시하거나 애니메이션을 재생합니다(이 파일 또는 라이브러리에서).\n(Rebirth 저장 시 게임을 위해 애니메이션 레이어를 일반 레이어로 펼칩니다.)") \ X(TOOLTIP_LIBRARY_ADD, "Add an .anm2 whose animations layers can play.", "Añade un .anm2 cuyas animaciones pueden reproducir las capas.", "Добавить .anm2, анимации которого могут проигрывать слои.", "添加一个 .anm2,图层可以播放其中的动画。", "레이어가 애니메이션을 재생할 수 있는 .anm2를 추가합니다.") \ X(TOOLTIP_LIBRARY_INVALID, "This library could not be loaded. Check the file.", "Esta biblioteca no se pudo cargar. Revisa el archivo.", "Эту библиотеку не удалось загрузить. Проверьте файл.", "无法加载此库。请检查文件。", "이 라이브러리를 불러올 수 없습니다. 파일을 확인하세요.") \ X(TOOLTIP_LIBRARY_OPEN, "Open the library in its own tab to edit it; saving it updates every file that uses it.", "Abre la biblioteca en su propia pestaña para editarla; al guardarla se actualiza cada archivo que la usa.", "Открыть библиотеку в отдельной вкладке для редактирования; сохранение обновит все файлы, которые её используют.", "在单独的标签页中打开库进行编辑;保存后所有使用它的文件都会更新。", "라이브러리를 자체 탭에서 열어 편집합니다. 저장하면 이를 사용하는 모든 파일이 업데이트됩니다.") \ diff --git a/tests/draw.cpp b/tests/draw.cpp index 75e2424..8c5e163 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -157,3 +157,35 @@ TEST_CASE("child animations fire their triggers as they reach them") CHECK(sources_get(1) == std::vector{&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::Model&, int id) { return id == 0 ? &spin : nullptr; }; + auto flat = + edit::animation_layers_flatten(anm2, library_get, [](const model::Model&, const std::filesystem::path& path) + { return std::filesystem::path("library") / path; }); + CHECK(std::ranges::none_of(flat.content.layers, &model::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& model, const model::LibraryGet& get, float time) + { + std::vector points{}; + for (const auto& draw : + model::animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get})) + if (draw.type == model::DrawType::LAYER) + points.push_back(glm::round(glm::vec2(draw.parent * model::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::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, &model::Layer::is_animation) == 3); +} diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 7dba325..655bdc4 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -5,6 +5,7 @@ #include #include +#include #include "canvas.hpp" #include "document.hpp" @@ -227,3 +228,33 @@ TEST_CASE("converting SVG spritesheets writes PNGs beside them") 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(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()); + document.model.isExtendedFormat = false; + REQUIRE(document.save(directory / "rebirth.anm2")); + std::ifstream file(directory / "rebirth.anm2"); + std::string saved(std::istreambuf_iterator(file), {}); + auto game = saved.substr(0, saved.find("