diff --git a/CMakeLists.txt b/CMakeLists.txt index e878507..462c830 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -108,7 +108,7 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS src/*.hpp) set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) -file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/anm2/*.cpp ${CORE_DIR}/edit/*.cpp) +file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/anm2/*.cpp ${CORE_DIR}/edit/*.cpp ${CORE_DIR}/model/*.cpp) foreach(CORE_FILE log resource/strings resource/image resource/audio_data resource/asset_store util/file util/path util/math util/string util/time util/working_directory util/xml util/pack util/imgui/multiselect snapshots storage playback selection) list(APPEND CORE_SRC ${CORE_DIR}/${CORE_FILE}.cpp) diff --git a/src/anm2/animation.cpp b/src/anm2/animation.cpp deleted file mode 100644 index d3f59cc..0000000 --- a/src/anm2/animation.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include "internal.hpp" - -using namespace anm2ed::util; -using namespace tinyxml2; - -namespace anm2ed -{ - Element Anm2::frame_effective(int layerId, const Element& frame) const - { - auto resolved = frame; - if (frame.regionId == -1) return resolved; - - auto layer = element_get(ElementType::LAYER_ELEMENT, layerId); - if (!layer) return resolved; - - auto spritesheet = element_get(ElementType::SPRITESHEET, layer->spritesheetId); - if (!spritesheet) return resolved; - - auto region = child_id_get(*spritesheet, ElementType::REGION, frame.regionId); - if (!region) return resolved; - - resolved.crop = region->crop; - resolved.size = region->size; - resolved.pivot = region->pivot; - return resolved; - } - - glm::vec4 Anm2::animation_rect(const Element& animation, bool isRootTransform) const - { - constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; - - float minX = std::numeric_limits::infinity(); - float minY = std::numeric_limits::infinity(); - float maxX = -std::numeric_limits::infinity(); - float maxY = -std::numeric_limits::infinity(); - bool isAny{}; - - for (float t = 0.0f; t < (float)animation.frameNum; t += 1.0f) - { - glm::mat4 transform(1.0f); - - auto root = animation_item_get(animation, ItemType::ROOT); - if (isRootTransform && root) - { - auto rootFrame = frame_generate(*root, t); - transform *= frame_parent_model_get(rootFrame); - } - - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](const Element& layerAnimation) - { - if (!layerAnimation.isVisible || !is_track_group_visible(*layerAnimations, layerAnimation)) return; - - auto itemTransform = transform; - if (isRootTransform && layerAnimation.groupId != -1) - if (auto group = child_id_get(*layerAnimations, ElementType::GROUP, layerAnimation.groupId)) - if (auto groupRoot = child_first_get(*group, ElementType::ROOT_ANIMATION)) - { - auto groupRootFrame = frame_generate(*groupRoot, t); - itemTransform *= frame_parent_model_get(groupRootFrame); - } - - auto frame = frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, t)); - if (frame.size == glm::vec2() || !frame.isVisible) return; - - auto layerTransform = - itemTransform * math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.shear)); - for (auto& corner : CORNERS) - { - auto world = layerTransform * glm::vec4(corner, 0.0f, 1.0f); - minX = std::min(minX, world.x); - minY = std::min(minY, world.y); - maxX = std::max(maxX, world.x); - maxY = std::max(maxY, world.y); - isAny = true; - } - }); - } - - if (!isAny) return glm::vec4(-1.0f); - return {minX, minY, maxX - minX, maxY - minY}; - } - - int Anm2::item_add(ItemType type, int animationIndex, const Element& item, int insertBeforeId, - types::destination::Type destination) - { - auto row = track_container_get(type); - auto elements = row ? element_get(row->elements) : nullptr; - if (!elements) return -1; - - auto id = item.id == -1 ? element_child_next_id_get(*elements, row->element) : item.id; - auto element = child_id_get(*elements, row->element, id); - if (!element) - { - element = &elements->children.emplace_back(element_make(row->element)); - element->id = id; - } - - if (!item.name.empty()) element->name = item.name; - element->spritesheetId = element_get(ElementType::SPRITESHEET, item.spritesheetId) ? item.spritesheetId : 0; - element->isShowRect = item.isShowRect; - - auto add = [&](Element& animation) - { - if (animation_item_get(animation, type, id)) return; - auto& tracks = child_ensure(animation, row->container); - auto track = element_make(row->track); - track.*(row->id) = id; - auto before = std::ranges::find_if(tracks.children, [&](const Element& child) - { return child.type == row->track && track_id_get(child) == insertBeforeId; }); - tracks.children.insert(insertBeforeId == -1 ? tracks.children.end() : before, track); - }; - - if (destination == types::destination::ALL) - { - if (auto animations = element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) add(animation); - } - else if (auto animation = element_get(ElementType::ANIMATION, animationIndex)) - add(*animation); - - return id; - } -} diff --git a/src/anm2/anm2.cpp b/src/anm2/anm2.cpp index ddb8937..341d750 100644 --- a/src/anm2/anm2.cpp +++ b/src/anm2/anm2.cpp @@ -7,28 +7,6 @@ namespace anm2ed { constexpr const char* CREATED_ON_FORMAT = "%m/%d/%Y %I:%M:%S %p"; - int animations_count_get(const Element& animations) - { - int count{}; - for (const auto& child : animations.children) - if (child.type == ElementType::ANIMATION) ++count; - return count; - } - - int animations_child_index_get(const Element& animations, int animationIndex) - { - int current{}; - for (int i = 0; i < (int)animations.children.size(); ++i) - if (animations.children[i].type == ElementType::ANIMATION && current++ == animationIndex) return i; - return -1; - } - - int animations_child_insert_index_get(const Element& animations, int animationIndex) - { - auto childIndex = animations_child_index_get(animations, std::max(animationIndex, 0)); - return childIndex == -1 ? (int)animations.children.size() : childIndex; - } - bool is_source_document_tag(std::string_view tag) { return tag == SOURCE_DOCUMENT_TAG; } const XMLElement* source_document_get(const XMLElement* rootElement) @@ -66,7 +44,6 @@ namespace anm2ed shader_frame_ids_repair(anm2.root); region_frame_ids_repair(anm2.root); anm2.region_frames_sync(true); - anm2.uids_repair(); anm2.isValid = true; return true; } @@ -88,8 +65,6 @@ namespace anm2ed root.children.push_back(element_make(ElementType::ANIMATIONS)); } - Anm2::Anm2(const std::filesystem::path& path, std::string* errorString) : Anm2() { load(path, errorString); } - bool Anm2::load(const std::filesystem::path& path, std::string* errorString) { XMLDocument document{}; @@ -170,16 +145,4 @@ namespace anm2ed return out; } - std::uint64_t Anm2::hash(Options options) const - { - return anm2_hash_get(root, options); - } - - bool Anm2::is_special_interpolated_frames() const { return ::anm2ed::is_special_interpolated_frames(root); } - - void Anm2::special_interpolated_frames_bake(int interval, bool isRoundScale, bool isRoundRotation) - { - ::anm2ed::special_interpolated_frames_bake(root, std::max(interval, FRAME_DURATION_MIN), isRoundScale, - isRoundRotation); - } } diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index a7f637a..1b2297b 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -14,278 +14,10 @@ #include #include -#include "icon.hpp" -#include "strings.hpp" -#include "types.hpp" - -#define ANM2_ELEMENT_TYPES \ - X(UNKNOWN, "", UNKNOWN) \ - X(ANIMATED_ACTOR, "AnimatedActor", UNKNOWN) \ - X(INFO, "Info", UNKNOWN) \ - X(CONTENT, "Content", UNKNOWN) \ - X(SPRITESHEETS, "Spritesheets", UNKNOWN) \ - X(SPRITESHEET, "Spritesheet", SPRITESHEETS) \ - X(SHADERS, "Shaders", UNKNOWN) \ - X(SHADER, "Shader", SHADERS) \ - X(UNIFORM, "Uniform", UNKNOWN) \ - X(COMPONENT, "Component", UNKNOWN) \ - X(REGION, "Region", UNKNOWN) \ - X(LAYERS, "Layers", UNKNOWN) \ - X(LAYER_ELEMENT, "Layer", LAYERS) \ - X(NULLS, "Nulls", UNKNOWN) \ - X(NULL_ELEMENT, "Null", NULLS) \ - X(EVENTS, "Events", UNKNOWN) \ - X(EVENT_ELEMENT, "Event", EVENTS) \ - X(SOUNDS, "Sounds", UNKNOWN) \ - X(SOUND_ELEMENT, "Sound", SOUNDS) \ - X(ANIMATIONS, "Animations", UNKNOWN) \ - X(ANIMATION, "Animation", ANIMATIONS) \ - X(ROOT_ANIMATION, "RootAnimation", UNKNOWN) \ - X(LAYER_ANIMATIONS, "LayerAnimations", UNKNOWN) \ - X(LAYER_ANIMATION_GROUPS, "LayerAnimationGroups", UNKNOWN) \ - X(LAYER_ANIMATION, "LayerAnimation", UNKNOWN) \ - X(NULL_ANIMATIONS, "NullAnimations", UNKNOWN) \ - X(NULL_ANIMATION_GROUPS, "NullAnimationGroups", UNKNOWN) \ - X(NULL_ANIMATION, "NullAnimation", UNKNOWN) \ - X(GROUP, "Group", UNKNOWN) \ - X(TRIGGERS, "Triggers", UNKNOWN) \ - X(FRAME, "Frame", UNKNOWN) \ - X(TRIGGER, "Trigger", UNKNOWN) +#include "model/common.hpp" namespace anm2ed { - enum class ElementType - { -#define X(symbol, tag, container) symbol, - ANM2_ELEMENT_TYPES -#undef X - COUNT - }; - - inline constexpr ElementType ELEMENT_CONTAINERS[] = { -#define X(symbol, tag, container) ElementType::container, - ANM2_ELEMENT_TYPES -#undef X - }; - - enum class Interpolation - { - NONE, - LINEAR, - EASE_IN, - EASE_OUT, - EASE_IN_OUT, - COUNT - }; - - enum class Origin - { - CUSTOM, - TOP_LEFT, - CENTER, - COUNT - }; - - enum class ItemType - { - NONE, - ROOT, - LAYER, - NULL_, - TRIGGER, - COUNT - }; - - inline constexpr int NONE = (int)ItemType::NONE; - inline constexpr int ROOT = (int)ItemType::ROOT; - inline constexpr int LAYER = (int)ItemType::LAYER; - inline constexpr int NULL_ = (int)ItemType::NULL_; - inline constexpr int TRIGGER = (int)ItemType::TRIGGER; - - inline constexpr int FRAME_DURATION_MIN = 1; - inline constexpr int FRAME_DURATION_MAX = 1000000; - inline constexpr int FRAME_NUM_MIN = 1; - inline constexpr int FRAME_NUM_MAX = FRAME_DURATION_MAX; - inline constexpr int FPS_MIN = 1; - inline constexpr int FPS_MAX = 120; - - enum class SpritesheetMergeOrigin - { - APPEND_RIGHT, - APPEND_BOTTOM, - COUNT - }; - - inline constexpr int APPEND_RIGHT = (int)SpritesheetMergeOrigin::APPEND_RIGHT; - inline constexpr int APPEND_BOTTOM = (int)SpritesheetMergeOrigin::APPEND_BOTTOM; - - inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); - inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); - inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); - - inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); - inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); - inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); - - inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); - inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); - inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); - - inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); - -#define ANM2_ITEM_TYPES \ - X(NONE, STRING_UNDEFINED, "", resource::icon::NONE, glm::vec4(), glm::vec4(), glm::vec4(), UNKNOWN, UNKNOWN) \ - X(ROOT, BASIC_ROOT, "RootAnimation", resource::icon::ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED, \ - ROOT_ANIMATION, UNKNOWN) \ - X(LAYER, BASIC_LAYER_ANIMATION, "LayerAnimation", resource::icon::LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, \ - LAYER_COLOR_HOVERED, LAYER_ANIMATION, LAYER_ANIMATIONS) \ - X(NULL_, BASIC_NULL_ANIMATION, "NullAnimation", resource::icon::NULL_, NULL_COLOR, NULL_COLOR_ACTIVE, \ - NULL_COLOR_HOVERED, NULL_ANIMATION, NULL_ANIMATIONS) \ - X(TRIGGER, BASIC_TRIGGERS, "Triggers", resource::icon::TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, \ - TRIGGER_COLOR_HOVERED, TRIGGERS, UNKNOWN) - - constexpr StringType TYPE_STRINGS[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) string, - ANM2_ITEM_TYPES -#undef X - }; - - constexpr const char* TYPE_ITEM_STRINGS[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) itemString, - ANM2_ITEM_TYPES -#undef X - }; - - constexpr resource::icon::Type TYPE_ICONS[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) icon, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) color, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) colorActive, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR_HOVERED[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) colorHovered, - ANM2_ITEM_TYPES -#undef X - }; - - inline constexpr ElementType TYPE_TRACKS[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) ElementType::track, - ANM2_ITEM_TYPES -#undef X - }; - - inline constexpr ElementType TYPE_CONTAINERS[] = { -#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) ElementType::container, - ANM2_ITEM_TYPES -#undef X - }; - - enum class RegionFrameMapping - { - PRESERVE, - SET - }; - - enum FileMergePreset - { - FILE_MERGE_PRESET_MERGE_BY_NAME, - FILE_MERGE_PRESET_APPEND_AS_NEW, - FILE_MERGE_PRESET_REPLACE_MATCHING, - FILE_MERGE_PRESET_COUNT - }; - - enum class ChangeType - { - ADJUST, - ADD, - SUBTRACT, - MULTIPLY, - DIVIDE - }; - - enum Flag - { - SERIALIZE_GROUPS = 1 << 0, - SERIALIZE_REGIONS = 1 << 1, - SERIALIZE_SOUNDS = 1 << 2, - SERIALIZE_REDUNDANT_FRAME_REGION_VALUES = 1 << 3, - SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES = 1 << 4, - SERIALIZE_BAKE_GROUP_FRAMES = 1 << 5, - SERIALIZE_NESTED_GROUPS = 1 << 6, - SERIALIZE_EXTENSIONS = 1 << 7, - SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES = 1 << 8 - }; - - using Flags = int; - - constexpr bool has_flag(Flags flags, Flag flag) { return (flags & flag) != 0; } - constexpr Flags SERIALIZE_EDITOR_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | - SERIALIZE_REDUNDANT_FRAME_REGION_VALUES | SERIALIZE_EXTENSIONS; - constexpr Flags SERIALIZE_DEFAULT = - SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES | SERIALIZE_BAKE_GROUP_FRAMES; - constexpr Flags SERIALIZE_ISAAC_DEFAULT = SERIALIZE_BAKE_GROUP_FRAMES | SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES; - constexpr Flags SERIALIZE_ANM2ED_DEFAULT = - SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; - - struct Options - { - Flags flags{SERIALIZE_DEFAULT}; - bool isExtendedFormat{}; - }; - -#define FRAME_CHANGE_SCALARS \ - X(cropX, crop.x, true, false, changeIsCropX, changeCrop.x) \ - X(cropY, crop.y, true, false, changeIsCropY, changeCrop.y) \ - X(sizeX, size.x, true, false, changeIsSizeX, changeSize.x) \ - X(sizeY, size.y, true, false, changeIsSizeY, changeSize.y) \ - X(pivotX, pivot.x, true, false, changeIsPivotX, changePivot.x) \ - X(pivotY, pivot.y, true, false, changeIsPivotY, changePivot.y) \ - X(positionX, position.x, false, false, changeIsPositionX, changePosition.x) \ - X(positionY, position.y, false, false, changeIsPositionY, changePosition.y) \ - X(scaleX, scale.x, false, false, changeIsScaleX, changeScale.x) \ - X(scaleY, scale.y, false, false, changeIsScaleY, changeScale.y) \ - X(shearX, shear.x, false, false, changeIsShearX, changeShear.x) \ - X(shearY, shear.y, false, false, changeIsShearY, changeShear.y) \ - X(rotation, rotation, false, false, changeIsRotation, changeRotation) \ - X(tintR, tint.r, false, true, changeIsTintR, changeTint.r) \ - X(tintG, tint.g, false, true, changeIsTintG, changeTint.g) \ - X(tintB, tint.b, false, true, changeIsTintB, changeTint.b) \ - X(tintA, tint.a, false, true, changeIsTintA, changeTint.a) \ - X(colorOffsetR, colorOffset.r, false, true, changeIsColorOffsetR, changeColorOffset.r) \ - X(colorOffsetG, colorOffset.g, false, true, changeIsColorOffsetG, changeColorOffset.g) \ - X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) - - struct FrameChange - { - std::optional regionId{}; -#define X(name, member, isLayerOnly, isColor, isEnabled, value) std::optional name{}; - FRAME_CHANGE_SCALARS -#undef X - std::optional duration{}; - std::optional shaderId{}; - std::optional isVisible{}; - std::optional interpolation{}; - std::optional isFlipX{}; - std::optional isFlipY{}; - }; - - inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, - BASIC_EASE_IN_OUT}; - struct Element { ElementType type{ElementType::UNKNOWN}; @@ -326,7 +58,6 @@ namespace anm2ed std::vector soundIds{}; std::vector> extraAttributes{}; std::string text{}; - std::uint64_t uid{}; glm::vec2 pivot{}; glm::vec2 crop{}; glm::vec2 position{}; @@ -337,28 +68,6 @@ namespace anm2ed glm::vec4 tint{types::color::WHITE}; }; - struct Reference - { - int animationIndex{-1}; - int itemType{(int)ItemType::NONE}; - int itemID{-1}; - int frameIndex{-1}; - int groupType{(int)ItemType::NONE}; - int groupId{-1}; - - auto operator<=>(const Reference&) const = default; - }; - - // A Reference expressed by runtime uids, so it survives inserts, deletes and moves. - struct Handle - { - std::uint64_t animation{}; - std::uint64_t item{}; - std::uint64_t frame{}; - - auto operator<=>(const Handle&) const = default; - }; - struct TrackContainer { ItemType itemType; @@ -483,9 +192,6 @@ namespace anm2ed return container ? track_find(*container, trackType, id, isGrouped ? groupId : GROUP_ANY) : nullptr; } - int track_frame_child_index_get(const Element&, int); - int track_frame_insert_child_index_get(const Element&, int); - template ElementPointer track_frame_get(E& track, int index) { auto childIndex = track_frame_child_index_get(track, index); @@ -519,35 +225,16 @@ namespace anm2ed } Element element_make(ElementType); + Element& child_ensure(Element&, ElementType); Element element_read(const tinyxml2::XMLElement*); std::string element_to_string(const Element&, Flags = SERIALIZE_EDITOR_DEFAULT); std::string element_to_string(const Element&, ElementType, Flags = SERIALIZE_EDITOR_DEFAULT); - tinyxml2::XMLElement* element_to_xml(tinyxml2::XMLDocument&, const Element&, Flags = SERIALIZE_EDITOR_DEFAULT); tinyxml2::XMLElement* element_to_xml(tinyxml2::XMLDocument&, const Element&, ElementType, Flags = SERIALIZE_EDITOR_DEFAULT); - Element& child_ensure(Element&, ElementType); - int element_child_next_id_get(const Element&, ElementType); - int element_child_max_id_get(const Element&, ElementType); - bool element_child_id_erase(Element&, ElementType, int); - int track_frames_count_get(const Element&); - int animations_count_get(const Element&); - int animations_child_index_get(const Element&, int); - int animations_child_insert_index_get(const Element&, int); Element root_animation_make(); - float interpolation_factor(Interpolation, float); void frame_mix(Element&, const Element&, float); Element frame_generate(const Element&, float); - glm::mat4 frame_parent_model_get(const Element&); - int frame_index_from_at_frame_get(const Element&, int); - int frame_index_from_time_get(const Element&, float); - float frame_time_from_index_get(const Element&, int); - void frame_bake(Element&, int, int, bool, bool); - void frames_generate_from_grid(Element&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); - bool frames_deserialize(Element&, const std::string&, int, std::set&, std::string* = nullptr); - void frames_sort_by_at_frame(Element&); - void frames_change(Element&, FrameChange, ItemType, ChangeType, const std::set&); int track_length_get(const Element&); - int animation_length_get(const Element&); class Anm2 { @@ -556,57 +243,14 @@ namespace anm2ed Element root{}; Anm2(); - Anm2(const std::filesystem::path&, std::string* = nullptr); bool load(const std::filesystem::path&, std::string* = nullptr); bool load_string(std::string_view, std::string* = nullptr); bool save(const std::filesystem::path&, std::string* = nullptr, Options = {}) const; std::string to_string(Options = {}) const; tinyxml2::XMLElement* to_element(tinyxml2::XMLDocument&, Options = {}) const; - std::uint64_t hash(Options = {}) const; - bool is_special_interpolated_frames() const; - void special_interpolated_frames_bake(int, bool, bool); void region_frames_sync(bool); Anm2 normalized_for_serialize(Flags = SERIALIZE_DEFAULT) const; - - template ElementPointer element_get(this Self&, ElementType); - template ElementPointer element_get(this Self&, ElementType, int); - template ElementPointer element_get(this Self&, Reference); - std::set element_unused(ElementType, const Element* = nullptr) const; - std::set region_unused(int) const; - bool deserialize(ElementType, const std::string&, bool, std::string* = nullptr, const std::filesystem::path& = {}, - int = -1); - Element frame_effective(int, const Element&) const; - glm::vec4 animation_rect(const Element&, bool) const; - int item_add(ItemType, int, const Element&, int = -1, types::destination::Type = types::destination::ALL); - bool animations_deserialize(const std::string&, int, std::set&, std::string* = nullptr, - std::set* = nullptr); - int animations_merge(int, std::set&, types::merge::Type = types::merge::APPEND, bool = true); - bool file_merge(const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); - bool regions_generate(const std::set&, const std::set&, const std::string&, RegionFrameMapping); - void regions_scan(); - void uids_repair(); - Handle handle_get(Reference, bool = false) const; }; - // uid -> where that element is now (as a Reference) and what it is, built in one walk of the animations. - class UidIndex - { - public: - struct Location - { - Reference reference{}; - ElementType type{}; - }; - - private: - std::unordered_map locations{}; - - public: - UidIndex() = default; - explicit UidIndex(const Anm2&); - bool contains(std::uint64_t) const; - std::optional reference_get(std::uint64_t) const; - ElementType type_get(std::uint64_t) const; - }; } diff --git a/src/anm2/element.cpp b/src/anm2/element.cpp index 61b9b05..063e01d 100644 --- a/src/anm2/element.cpp +++ b/src/anm2/element.cpp @@ -62,35 +62,6 @@ namespace anm2ed return remap; } - int element_child_max_id_get(const Element& element, ElementType type) - { - int maxId{-1}; - for (const auto& child : element.children) - if (child.type == type) maxId = std::max(maxId, child.id); - return maxId; - } - - int element_child_next_id_get(const Element& element, ElementType type) - { - return element_child_max_id_get(element, type) + 1; - } - - bool element_child_id_erase(Element& element, ElementType type, int id) - { - return std::erase_if(element.children, [&](const Element& child) { return child.type == type && child.id == id; }); - } - - float interpolation_factor(Interpolation interpolation, float value) - { - value = glm::clamp(value, 0.0f, 1.0f); - if (interpolation == Interpolation::LINEAR) return value; - if (interpolation == Interpolation::EASE_IN) return value * value; - if (interpolation == Interpolation::EASE_OUT) return 1.0f - ((1.0f - value) * (1.0f - value)); - if (interpolation == Interpolation::EASE_IN_OUT) - return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f); - return 0.0f; - } - bool is_track_child_valid(ElementType parentType, ElementType childType) { if (parentType == ElementType::CONTENT && childType == ElementType::SHADERS) return true; @@ -110,143 +81,4 @@ namespace anm2ed return true; } - bool is_track_group_visible(const Element& container, const Element& track) - { - auto group = track.groupId == -1 ? nullptr : child_id_get(container, ElementType::GROUP, track.groupId); - return !group || group->isVisible; - } - - int track_frame_child_index_get(const Element& track, int index) - { - if (index < 0) return -1; - auto frameType = track_frame_type_get(track); - int frameIndex{}; - for (int i = 0; i < (int)track.children.size(); ++i) - if (track.children[i].type == frameType && frameIndex++ == index) return i; - return -1; - } - - int track_frame_insert_child_index_get(const Element& track, int index) - { - auto childIndex = track_frame_child_index_get(track, std::max(0, index)); - return childIndex == -1 ? (int)track.children.size() : childIndex; - } - - int track_frames_count_get(const Element& track) - { - auto frameType = track_frame_type_get(track); - return (int)std::ranges::count_if(track.children, [&](const Element& child) { return child.type == frameType; }); - } - - template ElementPointer Anm2::element_get(this Self& self, ElementType type) - { - if (type == ElementType::ANIMATED_ACTOR) return &self.root; - if (type == ElementType::ANIMATIONS) return element_first_get(self.root, type); - - auto content = child_first_get(self.root, ElementType::CONTENT); - if (!content) return nullptr; - if (type == ElementType::CONTENT) return content; - if (auto container = child_first_get(*content, type)) return container; - if constexpr (!std::is_const_v) - if (type != ElementType::UNKNOWN && std::ranges::contains(ELEMENT_CONTAINERS, type)) - return &content->children.emplace_back(element_make(type)); - return element_first_get(self.root, type); - } - - template ElementPointer Anm2::element_get(this Self& self, ElementType type, int id) - { - if (type != ElementType::ANIMATION) - { - auto container = self.element_get(ELEMENT_CONTAINERS[(int)type]); - return container ? child_id_get(*container, type, id) : nullptr; - } - - auto animations = self.element_get(ElementType::ANIMATIONS); - auto childIndex = animations ? animations_child_index_get(*animations, id) : -1; - return childIndex == -1 ? nullptr : &animations->children[childIndex]; - } - - template ElementPointer Anm2::element_get(this Self& self, Reference reference) - { - auto animation = self.element_get(ElementType::ANIMATION, reference.animationIndex); - auto item = animation ? animation_item_get(*animation, (ItemType)reference.itemType, reference.itemID, - reference.groupType, reference.groupId) - : nullptr; - if (reference.frameIndex < 0 || !item) return item; - return track_frame_get(*item, reference.frameIndex); - } - -#define X(Self) \ - template ElementPointer Anm2::element_get(this Self&, ElementType); \ - template ElementPointer Anm2::element_get(this Self&, ElementType, int); \ - template ElementPointer Anm2::element_get(this Self&, Reference); - X(Anm2) - X(const Anm2) -#undef X - - std::set children_unused_get(const Element* element, ElementType type, const std::set& used) - { - std::set unused{}; - if (element) - for (const auto& child : element->children) - if (child.type == type && !used.contains(child.id)) unused.insert(child.id); - return unused; - } - - std::set Anm2::element_unused(ElementType type, const Element* animation) const - { - std::set used{}; - auto row = track_container_get(type); - auto used_insert = [&](const Element& animation) - { - if (row) - if (auto tracks = child_first_get(animation, row->container)) - tracks_each(*tracks, row->track, [&](const Element& track) { used.insert(track.*(row->id)); }); - - if (auto triggers = child_first_get(animation, ElementType::TRIGGERS)) - for (const auto& trigger : triggers->children) - if (trigger.type == ElementType::TRIGGER) - { - if (type == ElementType::EVENT_ELEMENT) used.insert(trigger.eventId); - if (type == ElementType::SOUND_ELEMENT) used.insert(trigger.soundIds.begin(), trigger.soundIds.end()); - } - - if (type == ElementType::SHADER) - if (auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS)) - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](const Element& track) - { - for (const auto& frame : track.children) - if (frame.type == ElementType::FRAME) used.insert(frame.shaderId); - }); - }; - - if (type == ElementType::SPRITESHEET) - { - if (auto layers = element_get(ElementType::LAYERS)) - for (const auto& layer : layers->children) - if (layer.type == ElementType::LAYER_ELEMENT) used.insert(layer.spritesheetId); - } - else if (animation) - used_insert(*animation); - else if (auto animations = element_get(ElementType::ANIMATIONS)) - for (const auto& child : animations->children) - if (child.type == ElementType::ANIMATION) used_insert(child); - - return children_unused_get(element_get(ELEMENT_CONTAINERS[(int)type]), type, used); - } - - std::set Anm2::region_unused(int spritesheetId) const - { - std::set used{}; - animations_tracks_each(root, ElementType::LAYER_ANIMATION, - [&](const Element& track) - { - auto layer = element_get(ElementType::LAYER_ELEMENT, track.layerId); - if (!layer || layer->spritesheetId != spritesheetId) return; - for (const auto& frame : track.children) - if (frame.type == ElementType::FRAME) used.insert(frame.regionId); - }); - return children_unused_get(element_get(ElementType::SPRITESHEET, spritesheetId), ElementType::REGION, used); - } } diff --git a/src/anm2/frames.cpp b/src/anm2/frames.cpp index 8f2204c..cf22efb 100644 --- a/src/anm2/frames.cpp +++ b/src/anm2/frames.cpp @@ -40,12 +40,6 @@ namespace anm2ed return frames; } - glm::mat4 frame_parent_model_get(const Element& frame) - { - return math::quad_model_parent_get(frame.position, {}, math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.shear)); - } - Element frame_generate(const Element& track, float time) { auto frame = element_make(track_frame_type_get(track)); @@ -101,207 +95,6 @@ namespace anm2ed return frame; } - int frame_index_from_at_frame_get(const Element& track, int atFrame) - { - int index{}; - for (const auto& frame : track.children) - { - if (frame.type != ElementType::TRIGGER) continue; - if (frame.atFrame == atFrame) return index; - ++index; - } - return -1; - } - - int frame_index_from_time_get(const Element& track, float time) - { - if (track.type == ElementType::TRIGGERS) return frame_index_from_at_frame_get(track, (int)time); - - auto frameType = track_frame_type_get(track); - auto frameCount = track_frames_count_get(track); - if (frameCount == 0) return -1; - if (time <= 0.0f) return 0; - - float duration{}; - int index{}; - for (const auto& frame : track.children) - { - if (frame.type != frameType) continue; - duration += frame.duration; - if (time < duration) return index; - ++index; - } - - return frameCount - 1; - } - - float frame_time_from_index_get(const Element& track, int index) - { - if (index < 0) return 0.0f; - auto frameType = track_frame_type_get(track); - float time{}; - int frameIndex{}; - for (const auto& frame : track.children) - { - if (frame.type != frameType) continue; - if (frameIndex == index) return frameType == ElementType::TRIGGER ? (float)frame.atFrame : time; - time += frame.duration; - ++frameIndex; - } - return 0.0f; - } - - void frame_bake(Element& track, int index, int interval, bool isRoundScale, bool isRoundRotation) - { - auto childIndex = track_frame_child_index_get(track, index); - if (childIndex == -1) return; - - auto original = track.children[childIndex]; - if (original.duration <= FRAME_DURATION_MIN) - { - track.children[childIndex].interpolation = Interpolation::NONE; - return; - } - - auto nextFrame = track_frame_get(track, index + 1); - auto baked = frame_bake_split(original, nextFrame ? *nextFrame : original, interval, isRoundScale, isRoundRotation); - track.children.erase(track.children.begin() + childIndex); - track.children.insert(track.children.begin() + childIndex, std::make_move_iterator(baked.begin()), - std::make_move_iterator(baked.end())); - } - - void frames_generate_from_grid(Element& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot, - int columns, int count, int duration) - { - for (int i = 0; i < count; ++i) - { - auto frame = element_make(ElementType::FRAME); - frame.duration = duration; - frame.pivot = pivot; - frame.size = size; - frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns)); - track.children.emplace_back(frame); - } - } - - void frames_sort_by_at_frame(Element& track) - { - std::sort(track.children.begin(), track.children.end(), - [](const Element& a, const Element& b) { return a.atFrame < b.atFrame; }); - } - - bool frames_deserialize(Element& track, const std::string& string, int start, std::set& indices, - std::string* errorString) - { - XMLDocument document{}; - if (document.Parse(string.c_str()) != XML_SUCCESS) - { - if (errorString) *errorString = document.ErrorStr(); - return false; - } - - auto frameType = track_frame_type_get(track); - auto tag = element_tag_get(frameType).data(); - auto first = document.FirstChildElement(tag); - if (!first) - { - if (errorString) *errorString = std::format("No valid {}(s).", tag); - return false; - } - - if (frameType == ElementType::FRAME) - { - start = std::clamp(start, 0, track_frames_count_get(track)); - std::vector frames{}; - for (auto element = first; element; element = element->NextSiblingElement(tag)) - { - auto frame = element_read(element); - if (frame.type != ElementType::FRAME) continue; - frames.push_back(std::move(frame)); - } - if (frames.empty()) return false; - auto count = (int)frames.size(); - track.children.reserve(track.children.size() + frames.size()); - auto childIndex = track_frame_insert_child_index_get(track, start); - track.children.insert(track.children.begin() + childIndex, std::make_move_iterator(frames.begin()), - std::make_move_iterator(frames.end())); - for (int offset = 0; offset < count; ++offset) - indices.insert(start + offset); - return !indices.empty(); - } - - auto has_conflict = [&](int value) - { - for (auto& trigger : track.children) - if (trigger.type == ElementType::TRIGGER && trigger.atFrame == value) return true; - return false; - }; - - std::vector atFrames{}; - int count{}; - for (auto element = first; element; element = element->NextSiblingElement(tag)) - { - auto trigger = element_read(element); - if (trigger.type != ElementType::TRIGGER) continue; - trigger.atFrame = start + count; - while (has_conflict(trigger.atFrame)) - ++trigger.atFrame; - atFrames.push_back(trigger.atFrame); - track.children.push_back(trigger); - ++count; - } - frames_sort_by_at_frame(track); - for (auto atFrame : atFrames) - if (auto index = frame_index_from_at_frame_get(track, atFrame); index != -1) indices.insert(index); - return !indices.empty(); - } - - void frames_change(Element& track, FrameChange change, ItemType itemType, ChangeType changeType, - const std::set& selection) - { - auto apply = [&](auto& target, const auto& optionalValue) - { - if (!optionalValue) return; - auto value = *optionalValue; - if (changeType == ChangeType::ADJUST) target = value; - if (changeType == ChangeType::ADD) target += value; - if (changeType == ChangeType::SUBTRACT) target -= value; - if (changeType == ChangeType::MULTIPLY) target *= value; - if (changeType == ChangeType::DIVIDE && value != decltype(value){}) target /= value; - }; - - for (auto index : selection) - { - auto frame = track_frame_get(track, index); - if (!frame) continue; - - if (change.isVisible) frame->isVisible = *change.isVisible; - if (change.interpolation) frame->interpolation = *change.interpolation; - if (change.isFlipX) frame->scale.x = -frame->scale.x; - if (change.isFlipY) frame->scale.y = -frame->scale.y; - - apply(frame->duration, change.duration); - if (change.duration) frame->duration = std::max(FRAME_DURATION_MIN, frame->duration); - if (itemType == ItemType::LAYER && change.regionId) frame->regionId = *change.regionId; - if (itemType == ItemType::LAYER && change.shaderId) frame->shaderId = *change.shaderId; -#define X(name, member, isLayerOnly, isColor, isEnabled, value) \ - if (!isLayerOnly || itemType == ItemType::LAYER) apply(frame->member, change.name); - FRAME_CHANGE_SCALARS -#undef X - } - } - - bool is_special_interpolated_frames(const Element& element) - { - if (element.type == ElementType::FRAME && element.interpolation != Interpolation::NONE && - element.interpolation != Interpolation::LINEAR) - return true; - - for (const auto& child : element.children) - if (is_special_interpolated_frames(child)) return true; - return false; - } - bool is_frame_interpolation_baked(const Element& frame, InterpolationBakeType type) { if (frame.interpolation == Interpolation::NONE) return false; @@ -344,11 +137,6 @@ namespace anm2ed interpolated_frames_bake(child, interval, isRoundScale, isRoundRotation, type); } - void special_interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation) - { - interpolated_frames_bake(element, interval, isRoundScale, isRoundRotation, InterpolationBakeType::SPECIAL); - } - void all_interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation) { interpolated_frames_bake(element, interval, isRoundScale, isRoundRotation, InterpolationBakeType::ALL); @@ -369,28 +157,4 @@ namespace anm2ed return length; } - int animation_length_get(const Element& animation) - { - int length{}; - auto group_roots_length_apply = [&](const Element& container) - { - for (const auto& child : container.children) - if (child.type == ElementType::GROUP) - if (auto rootAnimation = child_first_get(child, ElementType::ROOT_ANIMATION)) - length = std::max(length, track_length_get(*rootAnimation)); - }; - - if (auto rootAnimation = child_first_get(animation, ElementType::ROOT_ANIMATION)) - length = std::max(length, track_length_get(*rootAnimation)); - for (const auto& row : TRACK_CONTAINERS) - if (auto container = child_first_get(animation, row.container)) - { - group_roots_length_apply(*container); - tracks_each(*container, row.track, - [&](const Element& track) { length = std::max(length, track_length_get(track)); }); - } - if (auto triggers = child_first_get(animation, ElementType::TRIGGERS)) - length = std::max(length, track_length_get(*triggers)); - return std::max(length, FRAME_DURATION_MIN); - } } diff --git a/src/anm2/handle.cpp b/src/anm2/handle.cpp deleted file mode 100644 index 99f7e32..0000000 --- a/src/anm2/handle.cpp +++ /dev/null @@ -1,109 +0,0 @@ -#include "internal.hpp" - -#include - -#include "uid.hpp" - -namespace anm2ed -{ - void Anm2::uids_repair() - { - std::unordered_set seen{}; - element_each(root, - [&](Element& element) - { - if (element.uid == 0 || !seen.insert(element.uid).second) element.uid = util::uid_next(); - }); - } - - Handle Anm2::handle_get(Reference reference, bool isGroup) const - { - Handle handle{}; - auto animation = element_get(ElementType::ANIMATION, reference.animationIndex); - if (!animation) return handle; - handle.animation = animation->uid; - - auto item = isGroup ? animation_group_get(*animation, reference.itemType, reference.itemID) - : reference.itemType == NONE - ? nullptr - : animation_item_get(*animation, (ItemType)reference.itemType, reference.itemID, - reference.groupType, reference.groupId); - if (!item) return handle; - handle.item = item->uid; - - if (auto frame = isGroup ? nullptr : track_frame_get(*item, reference.frameIndex)) handle.frame = frame->uid; - return handle; - } - - using Locations = std::unordered_map; - - void track_locations_add(Locations& locations, const Element& track, Reference reference) - { - locations[track.uid] = {reference, track.type}; - auto frameType = track_frame_type_get(track); - for (const auto& frame : track.children) - if (frame.type == frameType) - { - ++reference.frameIndex; - locations[frame.uid] = {reference, frame.type}; - } - } - - UidIndex::UidIndex(const Anm2& anm2) - { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return; - - int animationIndex{}; - for (const auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - locations[animation.uid] = {{animationIndex}, animation.type}; - - for (const auto& child : animation.children) - { - if (child.type == ElementType::ROOT_ANIMATION) track_locations_add(locations, child, {animationIndex, ROOT}); - if (child.type == ElementType::TRIGGERS) track_locations_add(locations, child, {animationIndex, TRIGGER}); - - auto row = track_container_get(child.type); - if (!row || row->container != child.type) continue; - auto type = (int)row->itemType; - - auto tracks_add = [&](this auto&& self, const Element& parent, int groupId) -> void - { - for (const auto& track : parent.children) - if (track.type == ElementType::GROUP) - { - locations[track.uid] = {{animationIndex, type, track.id}, track.type}; - self(track, track.id); - } - else if (track.type == ElementType::ROOT_ANIMATION && groupId != -1) - track_locations_add(locations, track, {animationIndex, ROOT, -1, -1, type, groupId}); - else if (track.type == row->track) - { - auto trackGroupId = groupId != -1 ? groupId : track.groupId; - track_locations_add( - locations, track, - {animationIndex, type, track_id_get(track), -1, trackGroupId == -1 ? NONE : type, trackGroupId}); - } - }; - tracks_add(child, -1); - } - ++animationIndex; - } - } - - bool UidIndex::contains(std::uint64_t uid) const { return uid && locations.contains(uid); } - - std::optional UidIndex::reference_get(std::uint64_t uid) const - { - auto it = locations.find(uid); - return it == locations.end() ? std::nullopt : std::optional(it->second.reference); - } - - ElementType UidIndex::type_get(std::uint64_t uid) const - { - auto it = locations.find(uid); - return it == locations.end() ? ElementType::UNKNOWN : it->second.type; - } -} diff --git a/src/anm2/hash.cpp b/src/anm2/hash.cpp index 8205abf..a1e94ff 100644 --- a/src/anm2/hash.cpp +++ b/src/anm2/hash.cpp @@ -64,13 +64,6 @@ namespace anm2ed void close() override { byte_append(']'); } }; - std::uint64_t element_hash(const Element& element, Flags flags) - { - HashSink sink{}; - element_emit(sink, element, ElementType::UNKNOWN, flags); - return sink.hash; - } - std::uint64_t anm2_hash_get(const Element& root, Options options) { HashSink sink{}; diff --git a/src/anm2/internal.hpp b/src/anm2/internal.hpp index 1f3616f..248c5f5 100644 --- a/src/anm2/internal.hpp +++ b/src/anm2/internal.hpp @@ -75,14 +75,11 @@ namespace anm2ed void region_ids_remap(Element&); void region_frame_ids_repair(Element&); bool is_track_child_valid(ElementType, ElementType); - bool is_track_group_visible(const Element&, const Element&); bool is_nested_group_parent(ElementType, Flags); bool is_group_id_serialized(Flags); bool element_write_skip(const Element&, ElementType, Flags); bool is_frame_bake_serialized(const Element&, Flags); - bool is_special_interpolated_frames(const Element&); std::vector frame_bake_split(const Element&, const Element&, int, bool, bool); - void special_interpolated_frames_bake(Element&, int, bool, bool); void all_interpolated_frames_bake(Element&, int, bool, bool); int color_write(float); bool is_region_matched(const Element&, const Element&); @@ -115,5 +112,4 @@ namespace anm2ed } std::uint64_t anm2_hash_get(const Element&, Options); - std::uint64_t element_hash(const Element&, Flags); } diff --git a/src/anm2/merge.cpp b/src/anm2/merge.cpp deleted file mode 100644 index 9bc187e..0000000 --- a/src/anm2/merge.cpp +++ /dev/null @@ -1,410 +0,0 @@ -#include "internal.hpp" - -using namespace anm2ed::util; -using namespace tinyxml2; - -namespace anm2ed -{ - bool Anm2::animations_deserialize(const std::string& string, int start, std::set& indices, - std::string* errorString, std::set* groupIds) - { - XMLDocument document{}; - if (document.Parse(string.c_str()) != XML_SUCCESS) - { - if (errorString) *errorString = document.ErrorStr(); - return false; - } - - auto animations = element_get(ElementType::ANIMATIONS); - if (!animations) - { - if (errorString) *errorString = "No animations container."; - return false; - } - - start = std::clamp(start, 0, animations_count_get(*animations)); - - std::vector items{}; - std::map groupRemap{}; - auto nextGroupId = element_child_next_id_get(*animations, ElementType::GROUP); - for (auto element = document.FirstChildElement(); element; element = element->NextSiblingElement()) - { - auto item = element_read(element); - if (item.type != ElementType::ANIMATION && item.type != ElementType::GROUP) continue; - - if (item.type == ElementType::GROUP) - { - auto sourceGroupId = item.id; - if (!groupRemap.contains(sourceGroupId)) groupRemap[sourceGroupId] = nextGroupId++; - item.id = groupRemap[sourceGroupId]; - if (groupIds) groupIds->insert(item.id); - } - - items.push_back(item); - } - - if (items.empty()) - { - if (errorString) *errorString = "No valid animation(s)."; - return false; - } - - int count{}; - for (auto& item : items) - { - if (item.type == ElementType::ANIMATION) - { - if (auto mapped = groupRemap.find(item.groupId); mapped != groupRemap.end()) item.groupId = mapped->second; - indices.insert(start + count); - ++count; - } - } - - auto childIndex = animations_child_insert_index_get(*animations, start); - animations->children.insert(animations->children.begin() + childIndex, items.begin(), items.end()); - return true; - } - - void track_merge(Element& destination, const Element& source, types::merge::Type type) - { - switch (type) - { - case types::merge::APPEND: - destination.children.insert(destination.children.end(), source.children.begin(), source.children.end()); - break; - case types::merge::PREPEND: - destination.children.insert(destination.children.begin(), source.children.begin(), source.children.end()); - break; - case types::merge::REPLACE: - if (destination.children.size() < source.children.size()) destination.children.resize(source.children.size()); - for (int i = 0; i < (int)source.children.size(); ++i) - destination.children[i] = source.children[i]; - break; - case types::merge::IGNORE: - default: - break; - } - } - - void animation_tracks_merge(Element& destination, const Element& source, ElementType containerType, - types::merge::Type type) - { - auto sourceTracks = child_first_get(source, containerType); - if (!sourceTracks) return; - - auto destinationTracks = &child_ensure(destination, containerType); - - std::unordered_map groupRemap{}; - std::set matchedGroupIds{}; - for (const auto& sourceGroup : sourceTracks->children) - { - if (sourceGroup.type != ElementType::GROUP) continue; - - auto destinationGroup = std::find_if(destinationTracks->children.begin(), destinationTracks->children.end(), - [&](const Element& child) - { - return child.type == ElementType::GROUP && - child.name == sourceGroup.name && - !matchedGroupIds.contains(child.id); - }); - - if (destinationGroup == destinationTracks->children.end()) - { - auto group = sourceGroup; - group.id = element_child_next_id_get(*destinationTracks, ElementType::GROUP); - destinationTracks->children.push_back(std::move(group)); - destinationGroup = std::prev(destinationTracks->children.end()); - } - else if (auto sourceRoot = child_first_get(sourceGroup, ElementType::ROOT_ANIMATION)) - track_merge(child_ensure(*destinationGroup, ElementType::ROOT_ANIMATION), *sourceRoot, type); - - groupRemap[sourceGroup.id] = destinationGroup->id; - matchedGroupIds.insert(destinationGroup->id); - } - - for (const auto& sourceTrack : sourceTracks->children) - { - if (sourceTrack.type == ElementType::GROUP) continue; - - auto mappedGroup = groupRemap.find(sourceTrack.groupId); - auto groupId = mappedGroup != groupRemap.end() ? mappedGroup->second : -1; - - if (auto destinationTrack = track_find(*destinationTracks, sourceTrack.type, track_id_get(sourceTrack), groupId)) - track_merge(*destinationTrack, sourceTrack, type); - else - { - auto track = sourceTrack; - track.groupId = groupId; - destinationTracks->children.push_back(std::move(track)); - } - } - } - - int Anm2::animations_merge(int target, std::set& sources, types::merge::Type type, bool isDeleteAfter) - { - auto animations = element_get(ElementType::ANIMATIONS); - auto targetAnimation = element_get(ElementType::ANIMATION, target); - if (!animations || !targetAnimation) return target; - - if (!targetAnimation->name.ends_with(ANIMATION_MERGED_SUFFIX)) - targetAnimation->name += std::string(ANIMATION_MERGED_SUFFIX); - - for (auto index : sources) - { - if (index == target) continue; - auto source = element_get(ElementType::ANIMATION, index); - targetAnimation = element_get(ElementType::ANIMATION, target); - if (!source || !targetAnimation) continue; - - auto single_track_merge = [&](ElementType trackType) - { - if (auto sourceTrack = child_first_get(*source, trackType)) - track_merge(child_ensure(*targetAnimation, trackType), *sourceTrack, type); - }; - - single_track_merge(ElementType::ROOT_ANIMATION); - for (const auto& row : TRACK_CONTAINERS) - animation_tracks_merge(*targetAnimation, *source, row.container, type); - single_track_merge(ElementType::TRIGGERS); - } - - int finalIndex = target; - if (isDeleteAfter) - for (auto it = sources.rbegin(); it != sources.rend(); ++it) - { - auto source = *it; - auto sourceChildIndex = animations_child_index_get(*animations, source); - if (source == target || sourceChildIndex == -1) continue; - animations->children.erase(animations->children.begin() + sourceChildIndex); - if (source < finalIndex) --finalIndex; - } - - if (auto finalAnimation = element_get(ElementType::ANIMATION, finalIndex)) - finalAnimation->frameNum = animation_length_get(*finalAnimation); - return finalIndex; - } - - bool Anm2::file_merge(const std::filesystem::path& path, const std::filesystem::path& directory, - FileMergePreset preset) - { - Anm2 source(path); - if (!source.isValid) return false; - - auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; - std::map> remaps{}; - - auto path_remap = [&](const std::filesystem::path& original) - { - if (directory.empty() || original.empty()) return original; - std::error_code ec{}; - auto absolute = - original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec); - if (ec) absolute = path.parent_path() / original; - auto relative = std::filesystem::relative(absolute, directory, ec); - return ec ? original : relative; - }; - - auto id_remap = [&](ElementType type, int id) - { - auto it = remaps[type].find(id); - return it == remaps[type].end() ? -1 : it->second; - }; - - auto name_find = [](Element& container, ElementType type, const std::string& name) - { return child_find(container, [&](const Element& child) { return child.type == type && child.name == name; }); }; - - auto name_unique_get = [&](Element& container, ElementType type, const std::string& name) - { - auto candidate = name; - for (int i = 2; name_find(container, type, candidate); ++i) - candidate = std::format("{} {}", name, i); - return candidate; - }; - - auto named_element_merge = [&](Element& container, Element item) - { - auto existing = isAppendAsNew ? nullptr : name_find(container, item.type, item.name); - if (existing) - { - item.id = existing->id; - *existing = item; - return item.id; - } - item.id = element_child_next_id_get(container, item.type); - if (isAppendAsNew) item.name = name_unique_get(container, item.type, item.name); - container.children.push_back(item); - return item.id; - }; - - auto spritesheet_import = [&](int sourceId) - { - auto& remap = remaps[ElementType::SPRITESHEET]; - if (remap.contains(sourceId)) return remap[sourceId]; - auto spritesheet = source.element_get(ElementType::SPRITESHEET, sourceId); - auto destination = element_get(ElementType::SPRITESHEETS); - if (sourceId < 0 || !spritesheet || !destination) return -1; - - auto imported = *spritesheet; - imported.id = element_child_next_id_get(*destination, ElementType::SPRITESHEET); - imported.path = path_remap(imported.path); - destination->children.push_back(imported); - return remap[sourceId] = imported.id; - }; - - auto sourceSounds = source.element_get(ElementType::SOUNDS); - auto destinationSounds = element_get(ElementType::SOUNDS); - if (sourceSounds && destinationSounds) - for (auto sound : sourceSounds->children) - { - if (sound.type != ElementType::SOUND_ELEMENT) continue; - auto sourceId = sound.id; - sound.path = path_remap(sound.path); - auto existing = isAppendAsNew ? nullptr - : child_find(*destinationSounds, [&](const Element& child) - { return child.type == sound.type && child.path == sound.path; }); - sound.id = existing ? existing->id : element_child_next_id_get(*destinationSounds, sound.type); - if (existing) - *existing = sound; - else - destinationSounds->children.push_back(sound); - remaps[sound.type][sourceId] = sound.id; - } - - for (auto type : {ElementType::LAYER_ELEMENT, ElementType::NULL_ELEMENT, ElementType::EVENT_ELEMENT}) - { - auto sourceContainer = source.element_get(ELEMENT_CONTAINERS[(int)type]); - auto destinationContainer = element_get(ELEMENT_CONTAINERS[(int)type]); - if (!sourceContainer || !destinationContainer) continue; - for (auto item : sourceContainer->children) - { - if (item.type != type) continue; - if (type == ElementType::LAYER_ELEMENT) - { - auto existing = isAppendAsNew ? nullptr : name_find(*destinationContainer, type, item.name); - item.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(item.spritesheetId); - } - remaps[type][item.id] = named_element_merge(*destinationContainer, item); - } - } - - auto item_remap = [&](Element& item) - { - for (auto& frame : item.children) - { - if (frame.type != ElementType::FRAME && frame.type != ElementType::TRIGGER) continue; - for (auto& soundId : frame.soundIds) - soundId = id_remap(ElementType::SOUND_ELEMENT, soundId); - frame.eventId = id_remap(ElementType::EVENT_ELEMENT, frame.eventId); - } - }; - - auto animation_build = [&](const Element& incoming) - { - auto animation = element_make(ElementType::ANIMATION); - animation.name = incoming.name; - animation.frameNum = incoming.frameNum; - animation.isLoop = incoming.isLoop; - - auto single_track_build = [&](ElementType type) - { - if (auto track = child_first_get(incoming, type)) item_remap(animation.children.emplace_back(*track)); - }; - - single_track_build(ElementType::ROOT_ANIMATION); - for (const auto& row : TRACK_CONTAINERS) - { - auto sourceTracks = child_first_get(incoming, row.container); - if (!sourceTracks) continue; - auto container = element_make(row.container); - for (auto item : sourceTracks->children) - { - if (item.type == ElementType::GROUP) - { - std::erase_if(item.children, - [](const Element& child) { return child.type != ElementType::ROOT_ANIMATION; }); - if (item.children.empty()) item.children.push_back(root_animation_make()); - if (item.id == -1) item.id = element_child_next_id_get(container, ElementType::GROUP); - container.children.push_back(item); - continue; - } - if (item.type != row.track) continue; - item.*(row.id) = id_remap(row.element, item.*(row.id)); - if (item.*(row.id) < 0) continue; - item_remap(item); - container.children.push_back(item); - } - animation.children.push_back(container); - } - single_track_build(ElementType::TRIGGERS); - return animation; - }; - - auto sourceAnimations = source.element_get(ElementType::ANIMATIONS); - auto destinationAnimations = element_get(ElementType::ANIMATIONS); - if (!sourceAnimations || !destinationAnimations) return true; - - std::string defaultAnimationName{}; - for (const auto& incoming : sourceAnimations->children) - { - if (incoming.type != ElementType::ANIMATION) continue; - auto processed = animation_build(incoming); - auto destination = name_find(*destinationAnimations, ElementType::ANIMATION, processed.name); - if (isAppendAsNew) - processed.name = name_unique_get(*destinationAnimations, ElementType::ANIMATION, processed.name); - if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; - - if (!destination || isAppendAsNew) - { - destinationAnimations->children.push_back(processed); - continue; - } - - if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING) - { - *destination = processed; - continue; - } - - destination->isLoop = processed.isLoop; - for (auto type : {ElementType::ROOT_ANIMATION, ElementType::TRIGGERS}) - if (auto track = child_first_get(processed, type); track && !track->children.empty()) - child_ensure(*destination, type) = *track; - - for (const auto& row : TRACK_CONTAINERS) - { - auto sourceTracks = child_first_get(processed, row.container); - if (!sourceTracks) continue; - auto& destinationTracks = child_ensure(*destination, row.container); - - std::unordered_map groupRemap{}; - for (auto item : sourceTracks->children) - { - if (item.type != ElementType::GROUP) continue; - auto sourceGroupId = item.id; - item.id = element_child_next_id_get(destinationTracks, ElementType::GROUP); - destinationTracks.children.push_back(item); - groupRemap[sourceGroupId] = item.id; - } - - for (auto item : sourceTracks->children) - { - if (item.type != row.track) continue; - if (item.groupId != -1) item.groupId = groupRemap.contains(item.groupId) ? groupRemap[item.groupId] : -1; - if (auto existing = track_find(destinationTracks, row.track, track_id_get(item))) - { - if (!item.children.empty()) *existing = item; - } - else - destinationTracks.children.push_back(item); - } - } - - destination->frameNum = std::max({destination->frameNum, processed.frameNum, animation_length_get(*destination)}); - } - - if (destinationAnimations->defaultAnimation.empty() && !sourceAnimations->defaultAnimation.empty()) - destinationAnimations->defaultAnimation = - defaultAnimationName.empty() ? sourceAnimations->defaultAnimation : defaultAnimationName; - return true; - } -} diff --git a/src/anm2/normalize.cpp b/src/anm2/normalize.cpp index 24f8b6d..b56afc5 100644 --- a/src/anm2/normalize.cpp +++ b/src/anm2/normalize.cpp @@ -65,6 +65,17 @@ namespace anm2ed frame_ids_remap(*animations, &Element::shaderId, identity); } + bool is_region_matched(const Element& region, const Element& frame) + { + return region.type == ElementType::REGION && glm::ivec2(region.crop) == glm::ivec2(frame.crop) && + glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); + } + + Element* region_match_get(Element& spritesheet, const Element& frame) + { + return child_find(spritesheet, [&](const Element& region) { return is_region_matched(region, frame); }); + } + void region_frame_ids_repair(Element& root) { layer_frames_each(root, diff --git a/src/anm2/regions.cpp b/src/anm2/regions.cpp deleted file mode 100644 index 26638fe..0000000 --- a/src/anm2/regions.cpp +++ /dev/null @@ -1,82 +0,0 @@ -#include "internal.hpp" - -namespace anm2ed -{ - std::string region_name_get(const std::string& format, int number) - { - try - { - return std::vformat(format, std::make_format_args(number)); - } - catch (const std::format_error&) - { - return format; - } - } - - bool is_region_matched(const Element& region, const Element& frame) - { - return region.type == ElementType::REGION && glm::ivec2(region.crop) == glm::ivec2(frame.crop) && - glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); - } - - Element* region_match_get(Element& spritesheet, const Element& frame) - { - return child_find(spritesheet, [&](const Element& region) { return is_region_matched(region, frame); }); - } - - bool Anm2::regions_generate(const std::set& animationIndices, const std::set& frameReferences, - const std::string& format, RegionFrameMapping mapping) - { - std::vector> frames{}; - for (auto animationIndex : animationIndices) - if (auto animation = element_get(ElementType::ANIMATION, animationIndex)) - layer_frames_each(root, *animation, - [&](Element& frame, Element& spritesheet) { frames.emplace_back(&frame, &spritesheet); }); - - for (auto frameReference : frameReferences) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) continue; - auto frame = element_get(frameReference); - auto layer = element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); - auto spritesheet = layer ? element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (frame && frame->type == ElementType::FRAME && frame->regionId == -1 && spritesheet) - frames.emplace_back(frame, spritesheet); - } - - std::unordered_map regionNumbers{}; - bool isChanged{}; - for (auto [frame, spritesheet] : frames) - { - auto region = region_match_get(*spritesheet, *frame); - if (!region) - { - auto id = element_child_next_id_get(*spritesheet, ElementType::REGION); - region = &spritesheet->children.emplace_back(element_make(ElementType::REGION)); - region->id = id; - region->name = region_name_get(format, ++regionNumbers[spritesheet->id]); - region->crop = frame->crop; - region->size = frame->size; - region->pivot = frame->pivot; - isChanged = true; - } - if (mapping == RegionFrameMapping::SET && frame->regionId != region->id) - { - frame->regionId = region->id; - isChanged = true; - } - } - - return isChanged; - } - - void Anm2::regions_scan() - { - layer_frames_each(root, - [](Element& frame, Element& spritesheet) - { - if (frame.regionId != -1) return; - if (auto region = region_match_get(spritesheet, frame)) frame.regionId = region->id; - }); - } -} diff --git a/src/anm2/xml.cpp b/src/anm2/xml.cpp index 2a9083c..728bd37 100644 --- a/src/anm2/xml.cpp +++ b/src/anm2/xml.cpp @@ -540,11 +540,6 @@ namespace anm2ed return sink.root; } - XMLElement* element_to_xml(XMLDocument& document, const Element& element, Flags flags) - { - return element_to_xml(document, element, ElementType::UNKNOWN, flags); - } - std::string element_to_string(const Element& element, ElementType parentType, Flags flags) { XMLDocument document{}; @@ -557,49 +552,4 @@ namespace anm2ed return element_to_string(element, ElementType::UNKNOWN, flags); } - bool Anm2::deserialize(ElementType type, const std::string& string, bool isAppend, std::string* errorString, - const std::filesystem::path& directory, int spritesheetId) - { - XMLDocument document{}; - if (document.Parse(string.c_str()) != XML_SUCCESS) - { - if (errorString) *errorString = document.ErrorStr(); - return false; - } - - auto tag = element_tag_get(type); - if (tag.empty() || !document.FirstChildElement(tag.data())) - { - if (errorString) *errorString = std::format("No valid {}(s).", tag); - return false; - } - - auto containerType = type == ElementType::REGION ? ElementType::SPRITESHEET : ELEMENT_CONTAINERS[(int)type]; - auto container = - type == ElementType::REGION ? element_get(containerType, spritesheetId) : element_get(containerType); - if (!container) - { - if (errorString) *errorString = std::format("No {} container.", element_tag_get(containerType)); - return false; - } - - auto isPath = type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET; - std::optional workingDirectory{}; - if (isPath && !directory.empty()) workingDirectory.emplace(directory); - - for (auto xmlElement = document.FirstChildElement(tag.data()); xmlElement; - xmlElement = xmlElement->NextSiblingElement(tag.data())) - { - auto element = element_read(xmlElement); - if (element.type != type) continue; - if (isAppend) - element.id = element_child_next_id_get(*container, type); - else - element_child_id_erase(*container, type, element.id); - if (isPath) element.path = path::backslash_handle(element.path); - container->children.push_back(element); - } - - return true; - } } diff --git a/src/document.cpp b/src/document.cpp index bd27bc9..af274ad 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -15,6 +15,8 @@ #include "file.hpp" #include "log.hpp" #include "manager.hpp" +#include "model/frames.hpp" +#include "model/xml.hpp" #include "pack.hpp" #include "path.hpp" #include "strings.hpp" @@ -107,8 +109,8 @@ namespace anm2ed::document return false; } - template - void storage_labels_set(Storage& storage, const Element* container, ElementType type, bool isNone, Label&& label_get) + template + void storage_labels_set(Storage& storage, const Items& items, bool isNone, Label&& label_get) { std::vector labels{}; std::vector ids{}; @@ -117,44 +119,40 @@ namespace anm2ed::document labels.emplace_back(localize.get(BASIC_NONE)); ids.emplace_back(-1); } - if (container) - for (auto& element : container->children) - if (element.type == type) - { - labels.emplace_back(label_get(element)); - ids.emplace_back(element.id); - } + for (const auto& item : items) + { + labels.emplace_back(label_get(item)); + ids.emplace_back(item.id); + } storage.labels_set(std::move(labels), std::move(ids)); } - std::string element_name_get(const Element& element) { return element.name; } + std::string item_name_get(const auto& item) { return item.name; } // Loads assets for elements that are new or whose path changed, and forgets those of removed elements. - template - void resources_sync(Document& document, ElementType type, std::map& keys, + template + void resources_sync(Document& document, const Items& items, std::map& keys, std::unordered_map& paths, Load&& load) { std::set validIds{}; util::WorkingDirectory workingDirectory(document.directory_get()); - if (auto container = document.anm2.element_get(ELEMENT_CONTAINERS[(int)type])) - for (auto& element : container->children) + for (auto& element : items) + { + validIds.insert(element.id); + auto path = paths.find(element.id); + if (!keys.contains(element.id) || path == paths.end() || path->second != element.path) { - if (element.type != type) continue; - validIds.insert(element.id); - auto path = paths.find(element.id); - if (!keys.contains(element.id) || path == paths.end() || path->second != element.path) - { - load(element.id, path::case_insensitive_find(element.path)); - paths[element.id] = element.path; - } + load(element.id, path::case_insensitive_find(element.path)); + paths[element.id] = element.path; } + } std::erase_if(keys, [&](const auto& pair) { return !validIds.contains(pair.first); }); std::erase_if(paths, [&](const auto& pair) { return !validIds.contains(pair.first); }); } // A spritesheet is dirty when its path or image asset differs from what was last saved. - uint64_t spritesheet_hash_get(const Element& spritesheet, std::uint64_t imageKey) + uint64_t spritesheet_hash_get(const model::Spritesheet& spritesheet, std::uint64_t imageKey) { auto seed = std::hash{}(path::to_utf8(spritesheet.path)); return seed ^ (imageKey + HASH_COMBINE_CONSTANT + (seed << 6) + (seed >> 2)); @@ -169,7 +167,7 @@ namespace anm2ed::document void frame_time_sync(Document& document) { auto reference = document.reference_get(); - auto item = document.anm2.element_get(item_reference_get(reference)); + auto item = document.model.track_get(reference); auto frameIndex = reference.frameIndex; document.frameTime = item && frameIndex >= 0 ? frame_time_from_index_get(*item, frameIndex) : 0.0f; } @@ -180,8 +178,9 @@ namespace anm2ed Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) { tabId = document::document_tab_id_next(); - if (!isNew) anm2 = Anm2(path, errorString); - if (isNew ? !save(path, errorString) : !anm2.isValid) + model = model::model_make(); + if (!isNew) model::model_load(model, path, errorString); + if (isNew ? !save(path, errorString) : !model.isValid) { isValid = false; this->path.clear(); @@ -189,7 +188,8 @@ namespace anm2ed } this->path = path; - isValid = anm2.isValid; + isValid = model.isValid; + model.uids_repair(); clean(); change(); } @@ -207,7 +207,7 @@ namespace anm2ed { auto absolutePath = !path.empty() ? path : this->path; auto absolutePathUtf8 = path::to_utf8(absolutePath); - if (anm2.save(absolutePath, errorString, options)) + if (model::model_save(model, absolutePath, errorString, options)) { this->path = absolutePath; toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); @@ -237,7 +237,7 @@ namespace anm2ed { auto autosavePath = autosave_path_get(); auto autosavePathUtf8 = path::to_utf8(autosavePath); - if (anm2.save(autosavePath, errorString, options)) + if (model::model_save(model, autosavePath, errorString, options)) { autosaveHash = hash; lastAutosaveTime = 0.0f; @@ -251,12 +251,12 @@ namespace anm2ed void Document::texture_change(int id) { - if (texture_get(id) && anm2.element_get(ElementType::SPRITESHEET, id)) change(); + if (texture_get(id) && model::item_get(model.content.spritesheets, id)) change(); } bool Document::texture_reload(int id) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); + auto spritesheet = model::item_get(model.content.spritesheets, id); if (!spritesheet) return false; util::WorkingDirectory workingDirectory(directory_get()); texture_set(id, resource::Image(path::case_insensitive_find(spritesheet->path))); @@ -266,7 +266,7 @@ namespace anm2ed bool Document::sound_reload(int id) { - auto sound = anm2.element_get(ElementType::SOUND_ELEMENT, id); + auto sound = model::item_get(model.content.sounds, id); if (!sound) return false; util::WorkingDirectory workingDirectory(directory_get()); sound_set(id, resource::AudioData(path::case_insensitive_find(sound->path))); @@ -284,7 +284,7 @@ namespace anm2ed return false; }; - auto shaderElement = anm2.element_get(ElementType::SHADER, shaderId); + auto shaderElement = model::item_get(model.content.shaders, shaderId); if (!shaderElement) { document::shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); @@ -323,35 +323,33 @@ namespace anm2ed void Document::assets_sync() { - document::resources_sync(*this, ElementType::SPRITESHEET, textures, texturePaths, + document::resources_sync(*this, model.content.spritesheets, textures, texturePaths, [&](int id, const std::filesystem::path& path) { texture_set(id, resource::Image(path)); }); - document::resources_sync(*this, ElementType::SOUND_ELEMENT, sounds, soundPaths, + document::resources_sync(*this, model.content.sounds, sounds, soundPaths, [&](int id, const std::filesystem::path& path) { sound_set(id, resource::AudioData(path)); }); std::set validShaderIds{}; util::WorkingDirectory workingDirectory(directory_get()); - if (auto shaderElements = anm2.element_get(ElementType::SHADERS)) - for (auto& shaderElement : shaderElements->children) + for (auto& shaderElement : model.content.shaders) + { + auto id = shaderElement.id; + validShaderIds.insert(id); + auto isReload = !shaders.contains(id) || !shaderVertexPaths.contains(id) || !shaderFragmentPaths.contains(id) || + shaderVertexPaths.at(id) != shaderElement.vertex || + shaderFragmentPaths.at(id) != shaderElement.fragment; + if (shaderElement.fragment.empty()) { - if (shaderElement.type != ElementType::SHADER) continue; - auto id = shaderElement.id; - validShaderIds.insert(id); - auto isReload = !shaders.contains(id) || !shaderVertexPaths.contains(id) || !shaderFragmentPaths.contains(id) || - shaderVertexPaths.at(id) != shaderElement.vertex || - shaderFragmentPaths.at(id) != shaderElement.fragment; - if (shaderElement.fragment.empty()) - { - shaders.erase(id); - shaderVertexPaths.erase(id); - shaderFragmentPaths.erase(id); - } - else if (isReload) - shader_reload(id); - else if (auto shader = shader_get(id)) - resource::shader::uniform_configs_apply(shaderElement, shader->uniforms); + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); } + else if (isReload) + shader_reload(id); + else if (auto shader = shader_get(id)) + resource::shader::uniform_configs_apply(shaderElement, shader->uniforms); + } auto is_invalid = [&](const auto& pair) { return !validShaderIds.contains(pair.first); }; std::erase_if(shaders, is_invalid); @@ -396,14 +394,14 @@ namespace anm2ed bool Document::regions_trim(int spritesheetId, const std::set& ids) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + auto spritesheet = model::item_get(model.content.spritesheets, spritesheetId); auto texture = texture_get(spritesheetId); if (!spritesheet || !texture || !texture->is_valid() || texture->pixels.empty()) return false; bool isChanged{}; for (auto id : ids) { - auto region = child_id_get(*spritesheet, ElementType::REGION, id); + auto region = model::item_get(spritesheet->regions, id); if (!region) continue; auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0)); @@ -453,15 +451,14 @@ namespace anm2ed glm::ivec2 size{}; }; - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); + auto spritesheet = model::item_get(model.content.spritesheets, id); auto texture = texture_get(id); if (!spritesheet || !texture || !texture->is_valid() || texture->pixels.empty()) return false; padding = std::max(0, padding); std::vector items{}; - for (auto& region : spritesheet->children) + for (auto& region : spritesheet->regions) { - if (region.type != ElementType::REGION) continue; auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size)); auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size)); items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))}); @@ -507,8 +504,8 @@ namespace anm2ed } texture_set(id, resource::Image(packedPixels.data(), packedSize)); - for (auto& region : spritesheet->children) - if (region.type == ElementType::REGION && crops.contains(region.id)) region.crop = crops.at(region.id); + for (auto& region : spritesheet->regions) + if (crops.contains(region.id)) region.crop = crops.at(region.id); assets_sync(); return true; @@ -519,27 +516,27 @@ namespace anm2ed { if (ids.size() < 2) return false; for (auto id : ids) - if (!anm2.element_get(ElementType::SPRITESHEET, id) || !texture_get(id) || !texture_get(id)->is_valid()) + if (!model::item_get(model.content.spritesheets, id) || !texture_get(id) || !texture_get(id)->is_valid()) return false; auto baseId = *ids.begin(); - auto base = anm2.element_get(ElementType::SPRITESHEET, baseId); + auto base = model::item_get(model.content.spritesheets, baseId); auto origin = regionOrigin == origin::ORIGIN_CENTER ? Origin::CENTER : Origin::TOP_LEFT; auto mergedTexture = *texture_get(baseId); std::unordered_map> regionIdMap{}; auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) { - auto source = anm2.element_get(ElementType::SPRITESHEET, sourceId); - auto region = element_make(ElementType::REGION); - region.id = element_child_next_id_get(*base, ElementType::REGION); + auto source = model::item_get(model.content.spritesheets, sourceId); + model::Region region{}; + region.id = model::item_next_id_get(base->regions); auto stem = path::to_utf8(source->path.stem()); region.name = stem.empty() ? std::format("#{}", sourceId) : stem; region.crop = crop; region.size = size; region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2(); region.origin = origin; - base->children.push_back(region); + base->regions.push_back(region); }; if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedTexture.size); @@ -552,56 +549,53 @@ namespace anm2ed if (!isMakeRegions) continue; location_region_add(id, offset, texture->size); - for (auto sourceRegion : anm2.element_get(ElementType::SPRITESHEET, id)->children) + for (auto sourceRegion : model::item_get(model.content.spritesheets, id)->regions) { - if (sourceRegion.type != ElementType::REGION) continue; auto sourceRegionId = sourceRegion.id; - sourceRegion.id = element_child_next_id_get(*base, ElementType::REGION); + sourceRegion.id = model::item_next_id_get(base->regions); + sourceRegion.uid = util::uid_next(); sourceRegion.crop += offset; - base->children.push_back(sourceRegion); + base->regions.push_back(sourceRegion); regionIdMap[id][sourceRegionId] = sourceRegion.id; } } texture_set(baseId, std::move(mergedTexture)); std::unordered_map layerSpritesheetBefore{}; - if (auto layers = anm2.element_get(ElementType::LAYERS)) - for (auto& layer : layers->children) - if (layer.type == ElementType::LAYER_ELEMENT && ids.contains(layer.spritesheetId)) - { - layerSpritesheetBefore[layer.id] = layer.spritesheetId; - layer.spritesheetId = baseId; - } - - animations_tracks_each(anm2.root, ElementType::LAYER_ANIMATION, - [&](Element& track) - { - auto before = layerSpritesheetBefore.find(track.layerId); - if (before == layerSpritesheetBefore.end() || before->second == baseId) return; - auto& remap = regionIdMap[before->second]; - for (auto& frame : track.children) - if (frame.type == ElementType::FRAME && frame.regionId != -1) - frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; - }); - - auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS); - for (auto id : ids) - if (id != baseId) + for (auto& layer : model.content.layers) + if (ids.contains(layer.spritesheetId)) { - element_child_id_erase(*spritesheets, ElementType::SPRITESHEET, id); - textures.erase(id); + layerSpritesheetBefore[layer.id] = layer.spritesheetId; + layer.spritesheetId = baseId; } + for (int i = 0; i < model.animations_count_get(); ++i) + model::tracks_each(model.animation_edit(i)->layers, + [&](model::Track& track, auto*) + { + auto before = layerSpritesheetBefore.find(track.id); + if (before == layerSpritesheetBefore.end() || before->second == baseId) return; + auto& remap = regionIdMap[before->second]; + for (auto& frame : track.frames) + if (frame.regionId != -1) + frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; + }); + + std::erase_if(model.content.spritesheets, [&](const model::Spritesheet& spritesheet) + { return spritesheet.id != baseId && ids.contains(spritesheet.id); }); + for (auto id : ids) + if (id != baseId) textures.erase(id); + assets_sync(); return true; } - void Document::hash_set() { hash = anm2.hash(); } + void Document::hash_set() { hash = model::model_hash(model); } void Document::clean() { assets_sync(); - saveHash = anm2.hash(); + saveHash = model::model_hash(model); hash = saveHash; lastAutosaveTime = 0.0f; isForceDirty = false; @@ -617,16 +611,14 @@ namespace anm2ed void Document::spritesheet_hashes_sync() { std::set validIds{}; - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) - { - validIds.insert(spritesheet.id); - auto currentHash = document::spritesheet_hash_get( - spritesheet, textures.contains(spritesheet.id) ? textures.at(spritesheet.id) : 0); - spritesheetHashes[spritesheet.id] = currentHash; - spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); - } + for (auto& spritesheet : model.content.spritesheets) + { + validIds.insert(spritesheet.id); + auto currentHash = document::spritesheet_hash_get( + spritesheet, textures.contains(spritesheet.id) ? textures.at(spritesheet.id) : 0); + spritesheetHashes[spritesheet.id] = currentHash; + spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); + } auto is_invalid = [&](const auto& pair) { return !validIds.contains(pair.first); }; std::erase_if(spritesheetHashes, is_invalid); @@ -641,74 +633,43 @@ namespace anm2ed hash_set(); assets_sync(); - auto events_set = [&]() + auto path_label_get = [](StringType format) { - document::storage_labels_set(event, anm2.element_get(ElementType::EVENTS), ElementType::EVENT_ELEMENT, true, - document::element_name_get); + return [format](const auto& item) + { + auto pathString = path::to_utf8(item.path); + return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); + }; }; - auto spritesheets_set = [&]() - { - document::storage_labels_set( - spritesheet, anm2.element_get(ElementType::SPRITESHEETS), ElementType::SPRITESHEET, false, - [](const Element& element) - { - auto pathString = path::to_utf8(element.path); - return std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(element.id, pathString)); - }); - spritesheet_hashes_sync(); - }; - - auto sounds_set = [&]() - { - document::storage_labels_set(sound, anm2.element_get(ElementType::SOUNDS), ElementType::SOUND_ELEMENT, true, - [](const Element& element) - { - auto pathString = path::to_utf8(element.path); - return std::vformat(localize.get(FORMAT_SOUND), - std::make_format_args(element.id, pathString)); - }); - }; - - auto regions_set = [&]() - { - regionBySpritesheet.clear(); - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& element : spritesheets->children) - if (element.type == ElementType::SPRITESHEET) - document::storage_labels_set(regionBySpritesheet[element.id], &element, ElementType::REGION, true, - document::element_name_get); - }; - - auto shaders_set = [&]() - { - document::storage_labels_set(shader, anm2.element_get(ElementType::SHADERS), ElementType::SHADER, true, - document::element_name_get); - }; - - events_set(); - spritesheets_set(); - regions_set(); - shaders_set(); - sounds_set(); + auto& content = model.content; + document::storage_labels_set(event, content.events, true, [](const auto& item) { return item.name; }); + document::storage_labels_set(spritesheet, content.spritesheets, false, path_label_get(FORMAT_SPRITESHEET)); + spritesheet_hashes_sync(); + regionBySpritesheet.clear(); + for (auto& element : content.spritesheets) + document::storage_labels_set(regionBySpritesheet[element.id], element.regions, true, + [](const auto& item) { return item.name; }); + document::storage_labels_set(shader, content.shaders, true, [](const auto& item) { return item.name; }); + document::storage_labels_set(sound, content.sounds, true, path_label_get(FORMAT_SOUND)); snapshots.commit(); - index = UidIndex(anm2); + index = model::UidIndex(model); } void Document::edit_begin(StringType label) { snapshots.push(localize.get(label)); } - edit::Uids Document::edit_run(StringType label, const std::function& operation) + edit::Uids Document::edit_run(StringType label, const std::function& operation) { edit_begin(label); - auto uids = operation(anm2); + auto uids = operation(model); change(); return uids; } std::vector Document::references_get(const edit::Uids& uids) const { - UidIndex index(anm2); + model::UidIndex index(model); std::vector references{}; for (auto uid : uids) if (auto reference = index.reference_get(uid)) references.push_back(*reference); @@ -720,7 +681,7 @@ namespace anm2ed void Document::spritesheet_hash_update(int id) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); + auto spritesheet = model::item_get(model.content.spritesheets, id); if (!spritesheet) return; assets_sync(); spritesheetHashes[id] = document::spritesheet_hash_get(*spritesheet, textures.contains(id) ? textures.at(id) : 0); @@ -734,7 +695,7 @@ namespace anm2ed bool Document::spritesheet_is_dirty(int id) { - if (!anm2.element_get(ElementType::SPRITESHEET, id)) return false; + if (!model::item_get(model.content.spritesheets, id)) return false; if (!spritesheetHashes.contains(id)) spritesheet_hash_update(id); auto saveIt = spritesheetSaveHashes.find(id); return saveIt != spritesheetSaveHashes.end() && spritesheetHashes.at(id) != saveIt->second; @@ -742,11 +703,8 @@ namespace anm2ed bool Document::spritesheet_any_dirty() { - auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS); - return spritesheets && - std::ranges::any_of( - spritesheets->children, [&](const Element& spritesheet) - { return spritesheet.type == ElementType::SPRITESHEET && spritesheet_is_dirty(spritesheet.id); }); + return std::ranges::any_of(model.content.spritesheets, [&](const model::Spritesheet& spritesheet) + { return spritesheet_is_dirty(spritesheet.id); }); } std::filesystem::path Document::directory_get() const { return path.parent_path(); } @@ -760,7 +718,7 @@ namespace anm2ed Reference Document::reference_get() const { return selection_focus_get(selection, index); } - void Document::reference_set(Reference reference) { selection_focus_set(selection, anm2, reference); } + void Document::reference_set(Reference reference) { selection_focus_set(selection, model, reference); } std::set Document::selected_get(SelectionKind kind) const { @@ -769,7 +727,7 @@ namespace anm2ed void Document::selected_set(SelectionKind kind, const std::set& references) { - selection_references_set(selection, anm2, kind, references); + selection_references_set(selection, model, kind, references); } std::set Document::animations_selected_get() const @@ -792,8 +750,8 @@ namespace anm2ed { std::set result{}; itemReference.frameIndex = -1; - auto item = itemReference.itemType == NONE ? nullptr : anm2.element_get(itemReference); - for (int frameIndex = 0; item && frameIndex < track_frames_count_get(*item); ++frameIndex) + auto item = itemReference.itemType == NONE ? nullptr : model.track_get(itemReference); + for (int frameIndex = 0; item && frameIndex < (int)item->frames.size(); ++frameIndex) { itemReference.frameIndex = frameIndex; result.insert(itemReference); @@ -825,8 +783,7 @@ namespace anm2ed // Selects frames together with their tracks; the focus moves to the first frame unless it is already selected. void Document::frame_references_set(std::set frameReferences) { - std::erase_if(frameReferences, - [&](const Reference& frame) { return frame.frameIndex < 0 || !anm2.element_get(frame); }); + std::erase_if(frameReferences, [&](const Reference& frame) { return !model.frame_get(frame); }); std::set tracks{}; for (auto frame : frameReferences) tracks.insert(document::item_reference_get(frame)); @@ -855,23 +812,21 @@ namespace anm2ed Storage* Document::layer_regions_get(int layerId) { - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, layerId); + auto layer = model::item_get(model.content.layers, layerId); auto regions = layer ? regionBySpritesheet.find(layer->spritesheetId) : regionBySpritesheet.end(); return regions == regionBySpritesheet.end() ? nullptr : ®ions->second; } - Element* Document::frame_get() + const model::Frame* Document::frame_get() const { return model.frame_get(reference_get()); } + const model::Track* Document::item_get() const { return model.track_get(reference_get()); } + const model::Spritesheet* Document::spritesheet_get() const { - auto reference = reference_get(); - return reference.frameIndex < 0 ? nullptr : anm2.element_get(reference); + return model::item_get(model.content.spritesheets, spritesheet.reference); } - Element* Document::item_get() { return anm2.element_get(document::item_reference_get(reference_get())); } - Element* Document::spritesheet_get() { return anm2.element_get(ElementType::SPRITESHEET, spritesheet.reference); } void Document::spritesheets_add(const std::vector& paths) { - auto items = anm2.element_get(ElementType::SPRITESHEETS); - if (!items) return; + auto& items = model.content.spritesheets; auto directory = directory_get(); std::vector> loaded{}; @@ -895,9 +850,8 @@ namespace anm2ed std::set added{}; for (auto& [relativePath, texture] : loaded) { - auto& element = items->children.emplace_back(element_make(ElementType::SPRITESHEET)); - element.id = element_child_next_id_get(*items, ElementType::SPRITESHEET); - element.path = relativePath; + auto& element = + items.emplace_back(model::Spritesheet{.id = model::item_next_id_get(items), .path = relativePath}); texture_set(element.id, std::move(texture)); texturePaths[element.id] = element.path; added.insert(element.id); @@ -911,8 +865,8 @@ namespace anm2ed void Document::sounds_add(const std::vector& paths) { - auto items = anm2.element_get(ElementType::SOUNDS); - if (!items || std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) return; + auto& items = model.content.sounds; + if (std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) return; edit_begin(EDIT_ADD_SOUND); @@ -920,9 +874,9 @@ namespace anm2ed for (auto& path : paths) { if (path.empty()) continue; - auto& element = items->children.emplace_back(element_make(ElementType::SOUND_ELEMENT)); - element.id = element_child_next_id_get(*items, ElementType::SOUND_ELEMENT); - element.path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get())); + auto& element = items.emplace_back(model::Sound{ + .id = model::item_next_id_get(items), + .path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get()))}); WorkingDirectory workingDirectory(directory_get()); sound_set(element.id, resource::AudioData(path::case_insensitive_find(element.path))); soundPaths[element.id] = element.path; diff --git a/src/document.hpp b/src/document.hpp index c1487c2..785c594 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -84,10 +84,9 @@ namespace anm2ed #define X(type, name) type& name = current.name; SNAPSHOT_STEP_STATE_FIELDS #undef X - Anm2& anm2 = current.anm2; std::string& message = current.message; EditTarget editTarget{EditTarget::NONE}; - UidIndex index{}; + model::UidIndex index{}; Document(const std::filesystem::path&, bool = false, std::string* = nullptr); Document(const Document&) = delete; @@ -113,21 +112,21 @@ namespace anm2ed void clean(); void change(); void edit_begin(StringType); - edit::Uids edit_run(StringType, const std::function&); + edit::Uids edit_run(StringType, const std::function&); // Snapshots for undo, runs the operation on the model, then commits; void operations select nothing. template edit::Uids edit_apply(StringType label, Operation&& operation) { return edit_run(label, - [&](Anm2& anm2) -> edit::Uids + [&](model::Model& model) -> edit::Uids { - if constexpr (std::is_void_v>) + if constexpr (std::is_void_v>) { - operation(anm2); + operation(model); return {}; } else - return operation(anm2); + return operation(model); }); } std::vector references_get(const edit::Uids&) const; @@ -157,9 +156,9 @@ namespace anm2ed std::vector layer_references_get(); Storage* layer_regions_get(int); - Element* frame_get(); - Element* item_get(); - Element* spritesheet_get(); + const model::Frame* frame_get() const; + const model::Track* item_get() const; + const model::Spritesheet* spritesheet_get() const; void spritesheets_add(const std::vector&); void sounds_add(const std::vector&); diff --git a/src/edit/animations.cpp b/src/edit/animations.cpp index c4ef6a8..fb68394 100644 --- a/src/edit/animations.cpp +++ b/src/edit/animations.cpp @@ -1,182 +1,422 @@ #include "edit.hpp" -#include "vector.hpp" +#include "model/xml.hpp" + +using namespace anm2ed::model; namespace anm2ed::edit { - std::set animation_group_ids_get(const Element& animations) + constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; + + using AnimationPointer = std::shared_ptr; + + std::set animation_group_ids_get(const Model& model) { - std::set result{}; - for (const auto& item : animations.children) - if (item.type == ElementType::GROUP) result.insert(item.id); - return result; + std::set ids{}; + for (const auto& entry : model.animations.entries) + if (auto group = std::get_if(&entry)) ids.insert(group->id); + return ids; } - std::set animation_group_indices_get(const Element& animations, int groupId) + std::set animation_group_indices_get(const Model& model, int groupId) { - std::set result{}; - int animationIndex{}; - for (const auto& animation : animations.children) - if (animation.type == ElementType::ANIMATION) - { - if (animation.groupId == groupId) result.insert(animationIndex); - ++animationIndex; - } - return result; + std::set indices{}; + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.animation_group_id_get(i) == groupId) indices.insert(i); + return indices; } - // An empty copy of a track container: same tracks and groups, no frames. - Element track_container_shell_copy(const Element* source, const TrackContainer& row) + // Animations and whole groups taken out of the list, remembering the order they had. + struct AnimationsTaken { - auto destination = element_make(row.container); - if (!source) return destination; + std::vector animations{}; + std::vector groups{}; + }; - auto nextGroupId = element_child_next_id_get(*source, ElementType::GROUP); - std::set copiedTrackIds{}; - auto track_push = [&](const Element& track, int groupId) - { - if (track.type != row.track || !copiedTrackIds.insert(track_id_get(track)).second) return; - auto item = element_make(row.track); - item.*(row.id) = track.*(row.id); - item.groupId = track.groupId != -1 ? track.groupId : groupId; - item.isVisible = track.isVisible; - destination.children.push_back(item); - }; + AnimationsTaken animations_take(Model& model, const std::set& indices, const std::set& groupIds) + { + AnimationsTaken taken{}; + int index{}; + std::erase_if(model.animations.entries, + [&](AnimationEntry& entry) + { + if (auto animation = std::get_if(&entry)) + { + if (!indices.contains(index++)) return false; + taken.animations.push_back(std::move(*animation)); + return true; + } + auto& group = std::get(entry); + if (groupIds.contains(group.id)) + { + index += (int)group.animations.size(); + taken.groups.push_back(std::move(group)); + return true; + } + std::erase_if(group.animations, + [&](AnimationPointer& animation) + { + if (!indices.contains(index++)) return false; + taken.animations.push_back(std::move(animation)); + return true; + }); + return false; + }); + return taken; + } - for (const auto& sourceItem : source->children) + // Where an animation with this uid sits: its top-level entry, and its group (or nullptr) and position there. + struct AnimationPlace + { + int entry{-1}; + AnimationGroup* group{}; + int position{-1}; + }; + + AnimationPlace animation_place_get(Model& model, std::uint64_t uid) + { + auto& entries = model.animations.entries; + for (int i = 0; i < (int)entries.size(); ++i) { - if (sourceItem.type != ElementType::GROUP) + if (auto animation = std::get_if(&entries[i])) { - track_push(sourceItem, -1); + if ((*animation)->uid == uid) return {i, nullptr, -1}; continue; } - auto group = element_make(ElementType::GROUP); - group.id = sourceItem.id >= 0 ? sourceItem.id : nextGroupId++; - group.name = sourceItem.name; - group.isExpanded = sourceItem.isExpanded; - group.isVisible = sourceItem.isVisible; - group.children.push_back(root_animation_make()); - destination.children.push_back(group); - for (const auto& child : sourceItem.children) - track_push(child, group.id); + auto& group = std::get(entries[i]); + for (int j = 0; j < (int)group.animations.size(); ++j) + if (group.animations[j]->uid == uid) return {i, &group, j}; } - return destination; + return {}; + } + + int animation_group_entry_get(const Model& model, int groupId) + { + auto& entries = model.animations.entries; + for (int i = 0; i < (int)entries.size(); ++i) + if (auto group = std::get_if(&entries[i]); group && group->id == groupId) return i; + return -1; + } + + AnimationGroup* animation_group_find(Model& model, int groupId) + { + auto entry = animation_group_entry_get(model, groupId); + return entry == -1 ? nullptr : &std::get(model.animations.entries[entry]); + } + + // Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given. + void animations_insert(Model& model, int index, int groupId, std::vector animations) + { + auto before = model.animation_get(index); + auto place = before ? animation_place_get(model, before->uid) : AnimationPlace{}; + if (auto group = animation_group_find(model, groupId)) + { + auto position = place.group == group ? place.position : (int)group->animations.size(); + group->animations.insert(group->animations.begin() + position, animations.begin(), animations.end()); + return; + } + auto& entries = model.animations.entries; + auto position = place.entry == -1 ? (int)entries.size() : place.entry; + entries.insert(entries.begin() + position, animations.begin(), animations.end()); + } + + void animation_groups_remove(Model& model, const std::set& groupIds) + { + auto& entries = model.animations.entries; + for (int i = 0; i < (int)entries.size(); ++i) + { + auto group = std::get_if(&entries[i]); + if (!group || !groupIds.contains(group->id)) continue; + auto animations = std::move(group->animations); + entries.erase(entries.begin() + i); + entries.insert(entries.begin() + i, animations.begin(), animations.end()); + i += (int)animations.size() - 1; + } + } + + // An empty copy of a track list: same tracks and groups, no frames. + std::vector track_entries_shell_get(const std::vector& entries) + { + std::vector shell{}; + auto track_shell_get = [](const Track& track) + { return Track{.type = track.type, .id = track.id, .isVisible = track.isVisible}; }; + for (const auto& entry : entries) + if (auto track = std::get_if(&entry)) + shell.emplace_back(track_shell_get(*track)); + else + { + const auto& group = std::get(entry); + TrackGroup copy{ + .id = group.id, .name = group.name, .isExpanded = group.isExpanded, .isVisible = group.isVisible}; + for (const auto& groupTrack : group.tracks) + copy.tracks.push_back(track_shell_get(groupTrack)); + shell.emplace_back(std::move(copy)); + } + return shell; } // Adds an animation with the same (empty) tracks as the template animation. - Uids animation_add(Anm2& anm2, int index, int groupId, int templateIndex, const std::string& name) + Uids animation_add(Model& model, int index, int groupId, int templateIndex, const std::string& name) { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return {}; - - auto animation = element_make(ElementType::ANIMATION); - animation.name = name; - animation.groupId = groupId; - animation.children.push_back(root_animation_make()); - auto templateAnimation = anm2.element_get(ElementType::ANIMATION, templateIndex); - for (const auto& row : TRACK_CONTAINERS) - animation.children.push_back(track_container_shell_copy( - templateAnimation ? child_first_get(*templateAnimation, row.container) : nullptr, row)); - animation.children.push_back(element_make(ElementType::TRIGGERS)); - animation = element_clone(animation); - - if (animations_count_get(*animations) == 0) animations->defaultAnimation = animation.name; - animations->children.insert(animations->children.begin() + animations_child_insert_index_get(*animations, index), - animation); - return {animation.uid}; + Animation animation{.name = name}; + if (auto source = model.animation_get(templateIndex)) + { + animation.layers = track_entries_shell_get(source->layers); + animation.nulls = track_entries_shell_get(source->nulls); + } + if (model.animations_count_get() == 0) model.animations.defaultAnimation = animation.name; + auto uid = animation.uid; + animations_insert(model, index, groupId, {std::make_shared(std::move(animation))}); + return {uid}; } - Uids animations_remove(Anm2& anm2, const std::set& indices, const std::set& groupIds) + Uids animations_remove(Model& model, const std::set& indices, const std::set& groupIds) { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return {}; - animation_groups_remove(*animations, groupIds); - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (auto childIndex = animations_child_index_get(*animations, *it); childIndex != -1) - animations->children.erase(animations->children.begin() + childIndex); + animations_take(model, indices, {}); + animation_groups_remove(model, groupIds); return {}; } - void animation_groups_remove(Element& animations, const std::set& groupIds) + // Moves animations and whole groups beside a target animation or group; animations dropped on their own join the + // target's group (or the group dropped into). + Uids animations_move(Model& model, const std::set& indices, const std::set& groupIds, + AnimationTarget target) { - for (auto& item : animations.children) - if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; - std::erase_if(animations.children, - [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); - } + auto targetAnimation = model.animation_get(target.animationIndex); + auto targetUid = targetAnimation ? targetAnimation->uid : 0; + if (targetAnimation && groupIds.contains(model.animation_group_id_get(target.animationIndex))) return {}; + if (targetAnimation && indices.contains(target.animationIndex)) return {}; + if (!targetAnimation && groupIds.contains(target.groupId)) return {}; - // Moves animations and whole groups to a child position; animations moved on their own join targetGroupId. - Uids animations_move(Anm2& anm2, const std::set& indices, const std::set& groupIds, int targetChildIndex, - int targetGroupId) - { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return {}; - auto existingGroupIds = animation_group_ids_get(*animations); - auto groupId = existingGroupIds.contains(targetGroupId) ? targetGroupId : -1; + auto taken = animations_take(model, indices, groupIds); + if (taken.animations.empty() && taken.groups.empty()) return {}; Uids uids{}; - std::vector childIndices{}; - int animationIndex{}; - for (int i = 0; i < (int)animations->children.size(); ++i) - { - auto& item = animations->children[i]; - if (item.type == ElementType::GROUP && groupIds.contains(item.id)) childIndices.push_back(i); - if (item.type != ElementType::ANIMATION) continue; - auto isGroupMoved = groupIds.contains(item.groupId); - auto isMoved = indices.contains(animationIndex++); - if (isMoved && !isGroupMoved) - { - item.groupId = groupId; - uids.push_back(item.uid); - } - if (isGroupMoved || isMoved) childIndices.push_back(i); - } + for (const auto& animation : taken.animations) + uids.push_back(animation->uid); - util::vector::move_indices_to_position(animations->children, childIndices, targetChildIndex); + auto& entries = model.animations.entries; + auto topIndex = (int)entries.size(); + if (targetUid) + { + auto place = animation_place_get(model, targetUid); + if (place.group) + place.group->animations.insert(place.group->animations.begin() + place.position + target.isAfter, + taken.animations.begin(), taken.animations.end()); + else if (place.entry != -1) + entries.insert(entries.begin() + place.entry + target.isAfter, taken.animations.begin(), + taken.animations.end()); + place = animation_place_get(model, targetUid); + if (place.entry != -1) topIndex = place.entry + (target.isAfter || place.group); + } + else if (auto entry = animation_group_entry_get(model, target.groupId); entry != -1) + { + auto& group = std::get(entries[entry]); + if (target.isInto) + group.animations.insert(group.animations.end(), taken.animations.begin(), taken.animations.end()); + else + entries.insert(entries.begin() + entry + target.isAfter, taken.animations.begin(), taken.animations.end()); + if (!target.isInto && !target.isAfter) entry += (int)taken.animations.size(); + topIndex = entry + (target.isAfter || target.isInto); + } + else + entries.insert(entries.end(), taken.animations.begin(), taken.animations.end()); + + entries.insert(entries.begin() + std::clamp(topIndex, 0, (int)entries.size()), + std::make_move_iterator(taken.groups.begin()), std::make_move_iterator(taken.groups.end())); return uids; } - Uids animations_group(Anm2& anm2, const std::set& indices, const std::string& name) + // Wraps ungrouped animations in a new group placed where the first of them was. + Uids animations_group(Model& model, const std::set& indices, const std::string& name) { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (!animations || indices.empty()) return {}; - - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*animations, ElementType::GROUP); - group.name = name; - for (auto index : indices) - if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) animation->groupId = group.id; - animations->children.insert( - animations->children.begin() + animations_child_index_get(*animations, *indices.begin()), group); + if (indices.empty()) return {}; + auto first = model.animation_get(*indices.begin()); + if (!first) return {}; + auto firstUid = first->uid; + auto entry = animation_place_get(model, firstUid).entry; + auto groupIds = animation_group_ids_get(model); + auto taken = animations_take(model, indices, {}); + AnimationGroup group{ + .id = groupIds.empty() ? 0 : *groupIds.rbegin() + 1, .name = name, .animations = std::move(taken.animations)}; + auto& entries = model.animations.entries; + entries.insert(entries.begin() + std::clamp(entry, 0, (int)entries.size()), std::move(group)); return {}; } - Uids animations_paste(Anm2& anm2, const std::string& text, int start, int targetGroupId, std::set& groupIds, + // Pastes clipboard animations (and groups, which get new ids) before the animation at `start`; lone animations join + // `targetGroupId` when no group came with them. + Uids animations_paste(Model& model, const std::string& text, int start, int targetGroupId, std::set& groupIds, std::string* errorString) { - std::set indices{}; - if (!anm2.animations_deserialize(text, start, indices, errorString, &groupIds)) return {}; - anm2.uids_repair(); + auto entries = animations_from_string(text, errorString); + if (entries.empty()) return {}; + auto existingGroupIds = animation_group_ids_get(model); + auto nextGroupId = existingGroupIds.empty() ? 0 : *existingGroupIds.rbegin() + 1; Uids uids{}; - for (auto index : indices) - if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) + std::vector loose{}; + std::vector placed{}; + for (auto& entry : entries) + if (auto animation = std::get_if(&entry)) { - if (targetGroupId != -1 && groupIds.empty()) animation->groupId = targetGroupId; - uids.push_back(animation->uid); + uids.push_back((*animation)->uid); + loose.push_back(*animation); + placed.push_back(entry); } + else + { + auto& group = std::get(entry); + group.id = nextGroupId++; + groupIds.insert(group.id); + for (const auto& animation : group.animations) + uids.push_back(animation->uid); + placed.push_back(std::move(entry)); + } + + if (groupIds.empty() && targetGroupId != -1 && animation_group_find(model, targetGroupId)) + { + animations_insert(model, start, targetGroupId, std::move(loose)); + return uids; + } + + auto before = model.animation_get(start); + auto position = before ? animation_place_get(model, before->uid).entry : (int)model.animations.entries.size(); + model.animations.entries.insert(model.animations.entries.begin() + position, + std::make_move_iterator(placed.begin()), std::make_move_iterator(placed.end())); return uids; } - Uids animations_merge(Anm2& anm2, int target, std::set sources, types::merge::Type type, bool isDeleteAfter, + void track_merge(Track& destination, const Track& source, types::merge::Type type) + { + std::vector frames{}; + for (const auto& frame : source.frames) + frames.push_back(frame_clone(frame)); + switch (type) + { + case types::merge::APPEND: + destination.frames.insert(destination.frames.end(), frames.begin(), frames.end()); + break; + case types::merge::PREPEND: + destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end()); + break; + case types::merge::REPLACE: + if (destination.frames.size() < frames.size()) destination.frames.resize(frames.size()); + std::ranges::copy(frames, destination.frames.begin()); + break; + default: + break; + } + } + + // Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id + // within their group (else are added). + void track_entries_merge(std::vector& destination, const std::vector& source, + types::merge::Type type) + { + std::map groupRemap{}; + std::set matchedGroupIds{}; + int nextGroupId{}; + groups_each(destination, [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); }); + + groups_each(source, + [&](const TrackGroup& sourceGroup) + { + TrackGroup* matched{}; + groups_each(destination, + [&](TrackGroup& group) + { + if (!matched && group.name == sourceGroup.name && !matchedGroupIds.contains(group.id)) + matched = &group; + }); + if (matched) + track_merge(matched->root, sourceGroup.root, type); + else + { + TrackGroup group{.id = nextGroupId++, + .name = sourceGroup.name, + .isExpanded = sourceGroup.isExpanded, + .isVisible = sourceGroup.isVisible, + .root = track_clone(sourceGroup.root), + .extras = sourceGroup.extras}; + destination.emplace_back(std::move(group)); + matched = &std::get(destination.back()); + } + groupRemap[sourceGroup.id] = matched->id; + matchedGroupIds.insert(matched->id); + }); + + tracks_each(source, + [&](const Track& sourceTrack, const TrackGroup* sourceGroup) + { + TrackGroup* group{}; + if (sourceGroup) + groups_each(destination, + [&](TrackGroup& candidate) + { + if (candidate.id == groupRemap[sourceGroup->id]) group = &candidate; + }); + Track* existing{}; + if (group) + { + for (auto& track : group->tracks) + if (track.id == sourceTrack.id) existing = &track; + } + else + for (auto& entry : destination) + if (auto track = std::get_if(&entry); track && track->id == sourceTrack.id) + existing = track; + + if (existing) + track_merge(*existing, sourceTrack, type); + else if (group) + group->tracks.push_back(track_clone(sourceTrack)); + else + destination.emplace_back(track_clone(sourceTrack)); + }); + } + + // Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting + // the sources; `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid. + Uids animations_merge(Model& model, int target, std::set sources, types::merge::Type type, bool isDeleteAfter, const std::set& ungroupIds) { - auto merged = sources.size() > 1 || !sources.contains(target) - ? anm2.animations_merge(target, sources, type, isDeleteAfter) - : target; - if (merged == -1) return {}; - if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) animation_groups_remove(*animations, ungroupIds); - auto animation = anm2.element_get(ElementType::ANIMATION, merged); - return animation ? Uids{animation->uid} : Uids{}; + if (!model.animation_get(target)) return {}; + auto isMerge = sources.size() > 1 || !sources.contains(target); + if (isMerge) + { + auto& merged = *model.animation_edit(target); + if (!merged.name.ends_with(ANIMATION_MERGED_SUFFIX)) merged.name += std::string(ANIMATION_MERGED_SUFFIX); + for (auto index : sources) + { + if (index == target) continue; + auto source = model.animation_get(index); + if (!source) continue; + auto sourceCopy = *source; + auto& destination = *model.animation_edit(target); + track_merge(destination.root, sourceCopy.root, type); + track_entries_merge(destination.layers, sourceCopy.layers, type); + track_entries_merge(destination.nulls, sourceCopy.nulls, type); + track_merge(destination.triggers, sourceCopy.triggers, type); + } + + auto targetUid = model.animation_get(target)->uid; + if (isDeleteAfter) + { + sources.erase(target); + animations_take(model, sources, {}); + } + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.animation_get(i)->uid == targetUid) + { + auto& finalAnimation = *model.animation_edit(i); + finalAnimation.frameNum = animation_length_get(finalAnimation); + target = i; + } + } + + auto uid = model.animation_get(target)->uid; + animation_groups_remove(model, ungroupIds); + return {uid}; } } diff --git a/src/edit/content.cpp b/src/edit/content.cpp index 91af55d..3aeb176 100644 --- a/src/edit/content.cpp +++ b/src/edit/content.cpp @@ -1,94 +1,187 @@ #include "edit.hpp" -#include "vector.hpp" +#include +#include -namespace anm2ed -{ - std::string region_name_get(const std::string&, int); -} +#include "model/frames.hpp" +#include "model/xml.hpp" + +using namespace anm2ed::model; namespace anm2ed::edit { - // Clears frame references to the spritesheet's unused regions, then removes them. - Uids regions_remove_unused(Anm2& anm2, int spritesheetId) + std::string region_name_get(const std::string& format, int number) { - auto unused = anm2.region_unused(spritesheetId); - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (unused.empty() || !spritesheet) return {}; + try + { + return std::vformat(format, std::make_format_args(number)); + } + catch (const std::format_error&) + { + return format; + } + } - animations_tracks_each(anm2.root, ElementType::LAYER_ANIMATION, - [&](Element& track) - { - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, track.layerId); - if (!layer || layer->spritesheetId != spritesheetId) return; - for (auto& frame : track.children) - if (frame.type == ElementType::FRAME && unused.contains(frame.regionId)) - frame.regionId = -1; - }); - for (auto id : unused) - element_child_id_erase(*spritesheet, ElementType::REGION, id); + bool is_region_matched(const Region& region, const Frame& frame) + { + return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) && + glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); + } + + // Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id. + template void layer_frames_each(Model& model, int animationIndex, Callback&& callback) + { + auto animation = model.animation_get(animationIndex); + if (!animation) return; + std::vector> tracks{}; + tracks_each(animation->layers, + [&](const Track& track, const TrackGroup* group) + { + if (model.layer_spritesheet_get(track.id)) tracks.emplace_back(track.id, group ? group->id : -1); + }); + for (auto [id, groupId] : tracks) + { + auto spritesheetId = model.layer_spritesheet_get(id)->id; + auto track = model.track_edit({animationIndex, LAYER, id, -1, groupId == -1 ? NONE : LAYER, groupId}); + for (auto& frame : track->frames) + callback(frame, spritesheetId); + } + } + + // Makes a region for each distinct crop/size/pivot among the frames (and points frames at them when mapping is SET). + Uids regions_generate(Model& model, const std::set& animationIndices, const std::set& frames, + const std::string& format, RegionFrameMapping mapping) + { + std::unordered_map regionNumbers{}; + auto frame_apply = [&](Frame& frame, int spritesheetId) + { + auto& regions = item_get(model.content.spritesheets, spritesheetId)->regions; + auto region = + std::ranges::find_if(regions, [&](const Region& region) { return is_region_matched(region, frame); }); + if (region == regions.end()) + { + regions.push_back({.id = item_next_id_get(regions), + .name = region_name_get(format, ++regionNumbers[spritesheetId]), + .crop = frame.crop, + .size = frame.size, + .pivot = frame.pivot}); + region = regions.end() - 1; + } + if (mapping == RegionFrameMapping::SET) frame.regionId = region->id; + }; + + for (auto index : animationIndices) + layer_frames_each(model, index, frame_apply); + + for (auto reference : frames) + { + auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr; + auto source = model.frame_get(reference); + if (spritesheet && source && source->regionId == -1) frame_apply(*model.frame_edit(reference), spritesheet->id); + } return {}; } - // Pastes regions into a spritesheet at a child position; they get fresh ids after the existing ones. - Uids regions_paste(Anm2& anm2, int spritesheetId, const std::string& text, int insertIndex, std::string* errorString) + // Points frames without a region at a region of their spritesheet with the same crop/size/pivot. + Uids regions_scan(Model& model) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) return {}; - auto maxId = element_child_max_id_get(*spritesheet, ElementType::REGION); - if (!anm2.deserialize(ElementType::REGION, text, true, errorString, {}, spritesheetId)) return {}; + for (int i = 0; i < model.animations_count_get(); ++i) + layer_frames_each(model, i, + [&](Frame& frame, int spritesheetId) + { + if (frame.regionId != -1) return; + for (const auto& region : item_get(model.content.spritesheets, spritesheetId)->regions) + if (is_region_matched(region, frame)) + { + frame.regionId = region.id; + break; + } + }); + return {}; + } - spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - std::vector pasted{}; - for (int i = 0; i < (int)spritesheet->children.size(); i++) - if (spritesheet->children[i].type == ElementType::REGION && spritesheet->children[i].id > maxId) - pasted.push_back(i); - util::vector::move_indices_to_position(spritesheet->children, pasted, insertIndex); + // Copies each layer frame's region crop/size/pivot onto it; frames pointing at a missing region lose it. + Uids region_frames_sync(Model& model) + { + for (int i = 0; i < model.animations_count_get(); ++i) + layer_frames_each(model, i, + [&](Frame& frame, int spritesheetId) + { + if (frame.regionId == -1) return; + auto region = + item_get(item_get(model.content.spritesheets, spritesheetId)->regions, frame.regionId); + if (!region) + { + frame.regionId = -1; + return; + } + frame.crop = region->crop; + frame.size = region->size; + frame.pivot = region->pivot; + }); + return {}; + } + + // Clears frame references to the spritesheet's unused regions, then removes them. + Uids regions_remove_unused(Model& model, int spritesheetId) + { + auto unused = model.region_unused_get(spritesheetId); + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + if (unused.empty() || !spritesheet) return {}; + std::erase_if(spritesheet->regions, [&](const Region& region) { return unused.contains(region.id); }); + return {}; + } + + // Pastes regions into a spritesheet at a position; they get fresh ids after the existing ones. + Uids regions_paste(Model& model, int spritesheetId, const std::string& text, int insertIndex, + std::string* errorString) + { + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + if (!spritesheet) return {}; + auto regions = items_from_string(text, errorString); + for (auto& region : regions) + region.id = item_next_id_get(spritesheet->regions) + (int)(®ion - regions.data()); + insertIndex = std::clamp(insertIndex, 0, (int)spritesheet->regions.size()); + spritesheet->regions.insert(spritesheet->regions.begin() + insertIndex, regions.begin(), regions.end()); return {}; } // Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length. - Uids animation_grid_generate(Anm2& anm2, const std::vector& tracks, const GridOptions& options) + Uids animation_grid_generate(Model& model, const std::vector& tracks, const GridOptions& options) { Uids uids{}; for (auto reference : tracks) { - auto track = anm2.element_get(reference); - auto animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID); - auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!track || !animation) continue; - - auto start = (int)track->children.size(); - frames_generate_from_grid(*track, options.start, options.size, options.pivot, options.columns, options.count, + if (!model.track_get(reference)) continue; + auto spritesheetId = + model.layer_spritesheet_get(reference.itemID) ? model.layer_spritesheet_get(reference.itemID)->id : -1; + auto& track = *model.track_edit(reference); + auto start = (int)track.frames.size(); + frames_generate_from_grid(track, options.start, options.size, options.pivot, options.columns, options.count, options.delay); - for (int i = start; i < (int)track->children.size(); ++i) + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + for (int i = start; i < (int)track.frames.size(); ++i) { - auto& frame = track->children[i]; - if (frame.type != ElementType::FRAME) continue; + auto& frame = track.frames[i]; + uids.push_back(frame.uid); if (!options.isMakeRegions || !spritesheet) continue; - - auto region = element_make(ElementType::REGION); - region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - region.name = region_name_get(options.regionNameFormat, i - start); - region.crop = frame.crop; - region.size = frame.size; - region.pivot = frame.pivot; + auto& region = + spritesheet->regions.emplace_back(Region{.id = item_next_id_get(spritesheet->regions), + .name = region_name_get(options.regionNameFormat, i - start), + .crop = frame.crop, + .size = frame.size, + .pivot = frame.pivot}); frame.regionId = region.id; - spritesheet->children.push_back(region); } - animation->frameNum = animation_length_get(*animation); - - anm2.uids_repair(); - for (int i = start; i < (int)track->children.size(); ++i) - uids.push_back(track->children[i].uid); + auto& animation = *model.animation_edit(reference.animationIndex); + animation.frameNum = animation_length_get(animation); } return uids; } // Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the // given animations. - Uids frames_change_apply(Anm2& anm2, const ChangeTargets& targets, FrameChange change, ChangeType type) + Uids frames_change_apply(Model& model, const ChangeTargets& targets, FrameChange change, ChangeType type) { std::map> frames{}; std::set wholeTracks{}; @@ -98,30 +191,250 @@ namespace anm2ed::edit index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index); } - auto whole_apply = [&](Element* track, ItemType itemType) + auto whole_apply = [&](Track& track) { - if (!track) return; std::set indices{}; - for (int i = 0; i < track_frames_count_get(*track); ++i) + for (int i = 0; i < (int)track.frames.size(); ++i) indices.insert(i); - frames_change(*track, change, itemType, type, indices); + frames_change(track, change, track.type, type, indices); }; for (auto& [reference, indices] : frames) - if (auto track = anm2.element_get(reference)) - frames_change(*track, change, (ItemType)reference.itemType, type, indices); + if (auto track = model.track_edit(reference)) frames_change(*track, change, track->type, type, indices); for (auto reference : wholeTracks) - whole_apply(anm2.element_get(reference), (ItemType)reference.itemType); - for (auto animationIndex : targets.animations) + if (auto track = model.track_edit(reference)) whole_apply(*track); + for (auto index : targets.animations) { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); + auto animation = model.animation_edit(index); if (!animation) continue; - if (targets.isRoot) whole_apply(animation_item_get(*animation, ItemType::ROOT), ItemType::ROOT); - for (const auto& row : TRACK_CONTAINERS) - if (auto container = child_first_get(*animation, row.container); - container && (row.itemType == ItemType::LAYER ? targets.isLayers : targets.isNulls)) - tracks_each(*container, row.track, [&](Element& track) { whole_apply(&track, row.itemType); }); + if (targets.isRoot) whole_apply(animation->root); + if (targets.isLayers) tracks_each(animation->layers, [&](Track& track, auto*) { whole_apply(track); }); + if (targets.isNulls) tracks_each(animation->nulls, [&](Track& track, auto*) { whole_apply(track); }); } return {}; } + + // Merges another anm2 file: content matched by name (or path for sounds) is replaced unless appending as new, + // animations are added, replaced, or merged track by track depending on the preset. + bool file_merge(Model& model, const std::filesystem::path& path, const std::filesystem::path& directory, + FileMergePreset preset) + { + Model source{}; + if (!model_load(source, path) || !source.isValid) return false; + + auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; + std::map> remaps{}; + auto& content = model.content; + + auto path_remap = [&](const std::filesystem::path& original) + { + if (directory.empty() || original.empty()) return original; + std::error_code ec{}; + auto absolute = + original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec); + if (ec) absolute = path.parent_path() / original; + auto relative = std::filesystem::relative(absolute, directory, ec); + return ec ? original : relative; + }; + + auto id_remap = [&](ElementType type, int id) + { + auto it = remaps[type].find(id); + return it == remaps[type].end() ? -1 : it->second; + }; + + auto name_find = [](auto& items, const std::string& name) + { + auto it = std::ranges::find_if(items, [&](const auto& item) { return item.name == name; }); + return it == items.end() ? nullptr : &*it; + }; + + auto name_unique_get = [&](auto& items, const std::string& name) + { + auto candidate = name; + for (int i = 2; name_find(items, candidate); ++i) + candidate = std::format("{} {}", name, i); + return candidate; + }; + + auto named_merge = [&](auto& items, auto item) + { + auto existing = isAppendAsNew ? nullptr : name_find(items, item.name); + if (existing) + { + item.id = existing->id; + item.uid = existing->uid; + *existing = item; + return item.id; + } + item.id = item_next_id_get(items); + if (isAppendAsNew) item.name = name_unique_get(items, item.name); + items.push_back(item); + return item.id; + }; + + auto spritesheet_import = [&](int sourceId) + { + auto& remap = remaps[ElementType::SPRITESHEET]; + if (remap.contains(sourceId)) return remap[sourceId]; + auto spritesheet = item_get(source.content.spritesheets, sourceId); + if (sourceId < 0 || !spritesheet) return -1; + auto imported = *spritesheet; + imported.id = item_next_id_get(content.spritesheets); + imported.path = path_remap(imported.path); + content.spritesheets.push_back(imported); + return remap[sourceId] = imported.id; + }; + + for (auto sound : source.content.sounds) + { + auto sourceId = sound.id; + sound.path = path_remap(sound.path); + auto existing = isAppendAsNew ? content.sounds.end() + : std::ranges::find_if(content.sounds, [&](const Sound& other) + { return other.path == sound.path; }); + sound.id = existing != content.sounds.end() ? existing->id : item_next_id_get(content.sounds); + if (existing != content.sounds.end()) + *existing = sound; + else + content.sounds.push_back(sound); + remaps[ElementType::SOUND_ELEMENT][sourceId] = sound.id; + } + + for (auto layer : source.content.layers) + { + auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name); + auto sourceId = layer.id; + layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId); + remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer); + } + for (auto null : source.content.nulls) + remaps[ElementType::NULL_ELEMENT][null.id] = named_merge(content.nulls, null); + for (auto event : source.content.events) + remaps[ElementType::EVENT_ELEMENT][event.id] = named_merge(content.events, event); + + auto track_remap = [&](Track& track) + { + for (auto& frame : track.frames) + { + for (auto& soundId : frame.soundIds) + soundId = id_remap(ElementType::SOUND_ELEMENT, soundId); + frame.eventId = id_remap(ElementType::EVENT_ELEMENT, frame.eventId); + } + }; + + auto entries_remap = [&](std::vector& entries, ElementType type) + { + std::vector result{}; + auto track_keep = [&](Track& track) + { + track.id = id_remap(type, track.id); + if (track.id < 0) return false; + track_remap(track); + return true; + }; + for (auto& entry : entries) + if (auto track = std::get_if(&entry)) + { + if (track_keep(*track)) result.push_back(std::move(entry)); + } + else + { + auto& group = std::get(entry); + std::erase_if(group.tracks, [&](Track& groupTrack) { return !track_keep(groupTrack); }); + result.push_back(std::move(entry)); + } + entries = std::move(result); + }; + + auto animation_build = [&](const Animation& incoming) + { + auto animation = animation_clone(incoming); + animation.extras = animation.layersExtras = animation.nullsExtras = {}; + track_remap(animation.root); + track_remap(animation.triggers); + entries_remap(animation.layers, ElementType::LAYER_ELEMENT); + entries_remap(animation.nulls, ElementType::NULL_ELEMENT); + return animation; + }; + + auto animation_find = [&](const std::string& name) -> int + { + for (int i = 0; i < model.animations_count_get(); ++i) + if (model.animation_get(i)->name == name) return i; + return -1; + }; + + std::string defaultAnimationName{}; + for (auto [index, incoming] : source.animations_get()) + { + auto processed = animation_build(*incoming); + auto destination = animation_find(processed.name); + if (isAppendAsNew) + { + auto candidate = processed.name; + for (int i = 2; animation_find(candidate) != -1; ++i) + candidate = std::format("{} {}", processed.name, i); + processed.name = candidate; + } + if (incoming->name == source.animations.defaultAnimation) defaultAnimationName = processed.name; + + if (destination == -1 || isAppendAsNew) + { + model.animations.entries.emplace_back(std::make_shared(std::move(processed))); + continue; + } + + auto& target = *model.animation_edit(destination); + if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING) + { + processed.uid = target.uid; + target = std::move(processed); + continue; + } + + target.isLoop = processed.isLoop; + if (!processed.root.frames.empty()) target.root = processed.root; + if (!processed.triggers.frames.empty()) target.triggers = processed.triggers; + + for (auto [targetEntries, sourceEntries] : + {std::pair{&target.layers, &processed.layers}, std::pair{&target.nulls, &processed.nulls}}) + { + auto nextGroupId = 0; + groups_each(*targetEntries, + [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); }); + for (auto& entry : *sourceEntries) + { + if (auto group = std::get_if(&entry)) + { + auto copy = *group; + copy.id = nextGroupId++; + std::erase_if(copy.tracks, + [&](const Track& track) + { + auto existing = animation_track_get(target, (int)track.type, track.id); + if (existing && !track.frames.empty()) *existing = track; + return existing != nullptr; + }); + targetEntries->push_back(std::move(copy)); + continue; + } + auto& track = std::get(entry); + if (auto existing = animation_track_get(target, (int)track.type, track.id)) + { + if (!track.frames.empty()) *existing = track; + } + else + targetEntries->push_back(track); + } + } + + target.frameNum = std::max({target.frameNum, processed.frameNum, animation_length_get(target)}); + } + + if (model.animations.defaultAnimation.empty() && !source.animations.defaultAnimation.empty()) + model.animations.defaultAnimation = + defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName; + return true; + } } diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp index 8d98a75..f923810 100644 --- a/src/edit/edit.hpp +++ b/src/edit/edit.hpp @@ -6,7 +6,7 @@ #include #include -#include "anm2/anm2.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 // the caller may want to select (the first one is the focus); selection itself stays with the UI. @@ -51,39 +51,54 @@ namespace anm2ed::edit bool isNulls{}; }; - Element element_clone(Element); - Element* track_get(Anm2&, Reference); + struct AnimationTarget + { + int animationIndex{-1}; + int groupId{-1}; + bool isAfter{}; + bool isInto{}; + }; + std::map> frames_by_track_get(const std::set&); - Uids frame_insert(Anm2&, Reference, int); - Uids frames_delete(Anm2&, const std::set&); - Uids frames_duplicate(Anm2&, const std::set&, Reference); - Uids frames_reverse(Anm2&, const std::set&); - Uids frames_bake(Anm2&, const std::set&, int, bool, bool); - Uids frame_split(Anm2&, Reference, int); - Uids frames_move(Anm2&, const std::set&, Reference, int); - Uids frame_durations_set(Anm2&, const std::map&); - Uids trigger_at_frame_set(Anm2&, Reference, int); - Uids frames_paste(Anm2&, Reference, const std::set&, const std::string&, int, std::string*); - Uids root_bake_into(Anm2&, const std::set&, const std::set&, RootBakeOptions); - void frame_root_transform_apply(Element&, const Element&, bool, bool, bool); + Uids frame_insert(model::Model&, Reference, int); + Uids frames_delete(model::Model&, const std::set&); + Uids frames_duplicate(model::Model&, const std::set&, Reference); + Uids frames_reverse(model::Model&, const std::set&); + Uids frames_bake(model::Model&, const std::set&, int, bool, bool); + Uids frame_split(model::Model&, Reference, int); + Uids frames_move(model::Model&, const std::set&, Reference, int); + Uids frame_durations_set(model::Model&, const std::map&); + Uids trigger_at_frame_set(model::Model&, Reference, int); + Uids triggers_sort(model::Model&, Reference); + Uids frames_paste(model::Model&, Reference, const std::set&, const std::string&, int, std::string*); + Uids root_bake_into(model::Model&, const std::set&, const std::set&, RootBakeOptions); + void frame_root_transform_apply(model::Frame&, const model::Frame&, bool, bool, bool); - Uids items_remove(Anm2&, int, const std::map>&, const std::map>&); - Uids items_group(Anm2&, int, int, const std::set&, const std::string&); - Uids items_move(Anm2&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); - Uids animation_length_fit(Anm2&, int); + Uids items_remove(model::Model&, int, const std::map>&, const std::map>&); + Uids items_group(model::Model&, int, int, const std::set&, const std::string&); + Uids items_move(model::Model&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); + Uids animation_length_fit(model::Model&, int); + int item_add(model::Model&, ItemType, int, int, const std::string&, int, bool, int, types::destination::Type); - std::set animation_group_ids_get(const Element&); - std::set animation_group_indices_get(const Element&, int); - void animation_groups_remove(Element&, const std::set&); - Uids animation_add(Anm2&, int, int, int, const std::string&); - Uids animations_remove(Anm2&, const std::set&, const std::set&); - Uids animations_move(Anm2&, const std::set&, const std::set&, int, int); - Uids animations_group(Anm2&, const std::set&, const std::string&); - Uids animations_paste(Anm2&, const std::string&, int, int, std::set&, std::string*); - Uids regions_remove_unused(Anm2&, int); - Uids regions_paste(Anm2&, int, const std::string&, int, std::string*); - Uids animation_grid_generate(Anm2&, const std::vector&, const GridOptions&); - Uids frames_change_apply(Anm2&, const ChangeTargets&, FrameChange, ChangeType); - Uids animations_merge(Anm2&, int, std::set, types::merge::Type, bool, const std::set&); + std::set animation_group_ids_get(const model::Model&); + std::set animation_group_indices_get(const model::Model&, int); + void animation_groups_remove(model::Model&, const std::set&); + Uids animation_add(model::Model&, int, int, int, const std::string&); + Uids animations_remove(model::Model&, const std::set&, const std::set&); + Uids animations_move(model::Model&, const std::set&, const std::set&, AnimationTarget); + Uids animations_group(model::Model&, const std::set&, const std::string&); + Uids animations_paste(model::Model&, const std::string&, int, int, std::set&, std::string*); + Uids animations_merge(model::Model&, int, std::set, types::merge::Type, bool, const std::set&); + + std::string region_name_get(const std::string&, int); + Uids regions_generate(model::Model&, const std::set&, const std::set&, const std::string&, + RegionFrameMapping); + Uids regions_scan(model::Model&); + Uids region_frames_sync(model::Model&); + Uids regions_remove_unused(model::Model&, int); + Uids regions_paste(model::Model&, int, const std::string&, int, std::string*); + Uids animation_grid_generate(model::Model&, const std::vector&, const GridOptions&); + Uids frames_change_apply(model::Model&, const ChangeTargets&, FrameChange, ChangeType); + bool file_merge(model::Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); } diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 8b11066..ebb02e3 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -1,26 +1,17 @@ #include "edit.hpp" +#include #include #include "math.hpp" -#include "uid.hpp" +#include "model/frames.hpp" +#include "model/xml.hpp" using namespace anm2ed::util; +using namespace anm2ed::model; namespace anm2ed::edit { - Element element_clone(Element element) - { - element_each(element, [](Element& child) { child.uid = uid_next(); }); - return element; - } - - Element* track_get(Anm2& anm2, Reference reference) - { - reference.frameIndex = -1; - return anm2.element_get(reference); - } - std::map> frames_by_track_get(const std::set& frames) { std::map> result{}; @@ -32,75 +23,73 @@ namespace anm2ed::edit return result; } - Uids frames_uids_get(const Element& track, int start, int count) + Uids frames_uids_get(const Track& track, int start, int count) { Uids uids{}; - for (int i = start; i < start + count; ++i) - if (auto frame = track_frame_get(track, i)) uids.push_back(frame->uid); + for (int i = std::max(start, 0); i < std::min(start + count, (int)track.frames.size()); ++i) + uids.push_back(track.frames[i].uid); return uids; } - Uids frame_insert(Anm2& anm2, Reference reference, int time) + Uids frame_insert(Model& model, Reference reference, int time) { - auto track = track_get(anm2, reference); + auto track = model.track_edit(reference); if (!track) return {}; - if (reference.itemType == TRIGGER) + if (track->type == ItemType::TRIGGER) { - if (std::ranges::any_of(track->children, [&](const Element& trigger) { return trigger.atFrame == time; })) - return {}; - auto trigger = element_clone(element_make(ElementType::TRIGGER)); + if (std::ranges::any_of(track->frames, [&](const Frame& trigger) { return trigger.atFrame == time; })) return {}; + Frame trigger{}; trigger.atFrame = time; - track->children.push_back(trigger); + track->frames.push_back(trigger); frames_sort_by_at_frame(*track); return {trigger.uid}; } - auto count = track_frames_count_get(*track); - auto source = track_frame_get(*track, reference.frameIndex); - auto last = track_frame_get(*track, count - 1); - auto frame = element_clone(source ? *source : last ? *last : element_make(ElementType::FRAME)); - auto index = source ? std::clamp(reference.frameIndex + 1, 0, count) : count; - track->children.insert(track->children.begin() + track_frame_insert_child_index_get(*track, index), frame); + auto count = (int)track->frames.size(); + auto isSource = reference.frameIndex >= 0 && reference.frameIndex < count; + auto frame = isSource ? frame_clone(track->frames[reference.frameIndex]) + : count ? frame_clone(track->frames.back()) + : Frame{}; + auto index = isSource ? reference.frameIndex + 1 : count; + track->frames.insert(track->frames.begin() + index, frame); return {frame.uid}; } - Uids frames_delete(Anm2& anm2, const std::set& frames) + Uids frames_delete(Model& model, const std::set& frames) { for (auto& [trackReference, indices] : frames_by_track_get(frames)) - if (auto track = track_get(anm2, trackReference)) + if (auto track = model.track_edit(trackReference)) for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) - track->children.erase(track->children.begin() + childIndex); + if (*it >= 0 && *it < (int)track->frames.size()) track->frames.erase(track->frames.begin() + *it); return {}; } - Uids frames_duplicate(Anm2& anm2, const std::set& frames, Reference focus) + Uids frames_duplicate(Model& model, const std::set& frames, Reference focus) { Uids uids{}; std::uint64_t focusUid{}; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = track_get(anm2, trackReference); + auto track = model.track_edit(trackReference); if (!track) continue; - std::vector copies{}; + std::vector copies{}; int lastIndex{-1}; for (auto index : indices) - if (auto frame = track_frame_get(*track, index)) - { - copies.push_back(element_clone(*frame)); - lastIndex = index; - if (trackReference.animationIndex == focus.animationIndex && index == focus.frameIndex && - track_get(anm2, focus) == track) - focusUid = copies.back().uid; - } + { + if (index < 0 || index >= (int)track->frames.size()) continue; + copies.push_back(frame_clone(track->frames[index])); + lastIndex = index; + auto focusTrack = focus; + focusTrack.frameIndex = -1; + if (focusTrack == trackReference && index == focus.frameIndex) focusUid = copies.back().uid; + } if (copies.empty()) continue; for (const auto& copy : copies) uids.push_back(copy.uid); - auto childIndex = track_frame_insert_child_index_get(*track, lastIndex + 1); - track->children.insert(track->children.begin() + childIndex, copies.begin(), copies.end()); + track->frames.insert(track->frames.begin() + lastIndex + 1, copies.begin(), copies.end()); } if (auto it = std::ranges::find(uids, focusUid); focusUid && it != uids.end()) @@ -108,44 +97,44 @@ namespace anm2ed::edit return uids; } - Uids frames_reverse(Anm2& anm2, const std::set& frames) + // Reverses the selected frames of each track as one block placed where the first of them was. + Uids frames_reverse(Model& model, const std::set& frames) { for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = track_get(anm2, trackReference); + auto track = model.track_edit(trackReference); if (!track || indices.size() < 2) continue; - std::vector reversed{}; + std::vector reversed{}; for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) + if (*it >= 0 && *it < (int)track->frames.size()) { - reversed.push_back(std::move(track->children[childIndex])); - track->children.erase(track->children.begin() + childIndex); + reversed.push_back(std::move(track->frames[*it])); + track->frames.erase(track->frames.begin() + *it); } - auto childIndex = track_frame_insert_child_index_get(*track, *indices.begin()); - track->children.insert(track->children.begin() + childIndex, reversed.begin(), reversed.end()); + auto index = std::min(*indices.begin(), (int)track->frames.size()); + track->frames.insert(track->frames.begin() + index, reversed.begin(), reversed.end()); } return {}; } - Uids frames_bake(Anm2& anm2, const std::set& frames, int interval, bool isRoundScale, bool isRoundRotation) + Uids frames_bake(Model& model, const std::set& frames, int interval, bool isRoundScale, + bool isRoundRotation) { Uids uids{}; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = track_get(anm2, trackReference); + auto track = model.track_edit(trackReference); if (!track) continue; int inserted{}; for (auto originalIndex : indices) { auto index = originalIndex + inserted; - auto frame = track_frame_get(*track, index); - if (!frame) continue; - - auto count = frame->duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)frame->duration / interval); + if (index < 0 || index >= (int)track->frames.size()) continue; + auto duration = track->frames[index].duration; + auto count = duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)duration / interval); frame_bake(*track, index, interval, isRoundScale, isRoundRotation); - anm2.uids_repair(); uids.append_range(frames_uids_get(*track, index, count)); inserted += count - 1; } @@ -153,124 +142,138 @@ namespace anm2ed::edit return uids; } - Uids frame_split(Anm2& anm2, Reference reference, int time) + Uids frame_split(Model& model, Reference reference, int time) { - auto track = reference.itemType == TRIGGER ? nullptr : track_get(anm2, reference); - auto frame = track ? track_frame_get(*track, reference.frameIndex) : nullptr; - if (!frame || frame->duration <= 1) return {}; - - auto duration = frame->duration; - auto firstDuration = time - (int)std::round(frame_time_from_index_get(*track, reference.frameIndex)) + 1; + auto source = model.frame_get(reference); + if (!source || reference.itemType == TRIGGER || source->duration <= 1) return {}; + auto duration = source->duration; + auto firstDuration = + time - (int)std::round(frame_time_from_index_get(*model.track_get(reference), reference.frameIndex)) + 1; if (firstDuration <= 0 || firstDuration >= duration) return {}; - auto split = element_clone(*frame); + auto& track = *model.track_edit(reference); + auto& frame = track.frames[reference.frameIndex]; + auto split = frame_clone(frame); split.duration = duration - firstDuration; - if (auto next = track_frame_get(*track, reference.frameIndex + 1); - next && frame->interpolation != Interpolation::NONE) - frame_mix(split, *next, interpolation_factor(frame->interpolation, (float)firstDuration / (float)duration)); + if (reference.frameIndex + 1 < (int)track.frames.size() && frame.interpolation != Interpolation::NONE) + frame_mix(split, track.frames[reference.frameIndex + 1], + interpolation_factor(frame.interpolation, (float)firstDuration / (float)duration)); - frame->duration = firstDuration; - auto uid = frame->uid; - track->children.insert( - track->children.begin() + track_frame_insert_child_index_get(*track, reference.frameIndex + 1), split); + frame.duration = firstDuration; + auto uid = frame.uid; + track.frames.insert(track.frames.begin() + reference.frameIndex + 1, split); return {uid}; } // Moves frames (from any tracks) into one track before the frame at the given index. - Uids frames_move(Anm2& anm2, const std::set& frames, Reference target, int insertIndex) + Uids frames_move(Model& model, const std::set& frames, Reference target, int insertIndex) { - auto targetTrack = track_get(anm2, target); - if (!targetTrack) return {}; - insertIndex = std::clamp(insertIndex, 0, track_frames_count_get(*targetTrack)); target.frameIndex = -1; + auto targetTrack = model.track_get(target); + if (!targetTrack) return {}; + auto targetUid = targetTrack->uid; + insertIndex = std::clamp(insertIndex, 0, (int)targetTrack->frames.size()); - std::vector moved{}; + std::vector moved{}; for (auto& [trackReference, indices] : frames_by_track_get(frames)) { - auto track = track_get(anm2, trackReference); + auto track = model.track_edit(trackReference); if (!track) continue; - std::vector trackMoved{}; + std::vector trackMoved{}; for (auto it = indices.rbegin(); it != indices.rend(); ++it) - if (auto childIndex = track_frame_child_index_get(*track, *it); childIndex != -1) - { - trackMoved.insert(trackMoved.begin(), std::move(track->children[childIndex])); - track->children.erase(track->children.begin() + childIndex); - if (track == targetTrack && *it < insertIndex) --insertIndex; - } + { + if (*it < 0 || *it >= (int)track->frames.size()) continue; + trackMoved.insert(trackMoved.begin(), std::move(track->frames[*it])); + track->frames.erase(track->frames.begin() + *it); + if (track->uid == targetUid && *it < insertIndex) --insertIndex; + } moved.append_range(trackMoved); } if (moved.empty()) return {}; - insertIndex = std::clamp(insertIndex, 0, track_frames_count_get(*targetTrack)); - auto childIndex = track_frame_insert_child_index_get(*targetTrack, insertIndex); - targetTrack->children.insert(targetTrack->children.begin() + childIndex, moved.begin(), moved.end()); - return frames_uids_get(*targetTrack, insertIndex, (int)moved.size()); + auto& destination = *model.track_edit(target); + insertIndex = std::clamp(insertIndex, 0, (int)destination.frames.size()); + destination.frames.insert(destination.frames.begin() + insertIndex, moved.begin(), moved.end()); + return frames_uids_get(destination, insertIndex, (int)moved.size()); } - Uids frame_durations_set(Anm2& anm2, const std::map& durations) + Uids frame_durations_set(Model& model, const std::map& durations) { for (auto [reference, duration] : durations) - if (auto frame = anm2.element_get(reference)) + if (auto frame = model.frame_edit(reference)) frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX); return {}; } // Places a trigger at a frame, stepping it back past any other trigger already there. - Uids trigger_at_frame_set(Anm2& anm2, Reference reference, int atFrame) + Uids trigger_at_frame_set(Model& model, Reference reference, int atFrame) { - auto track = track_get(anm2, reference); - auto trigger = track ? track_frame_get(*track, reference.frameIndex) : nullptr; + auto trigger = model.frame_edit(reference); if (!trigger) return {}; trigger->atFrame = atFrame; - for (const auto& other : track->children) + for (const auto& other : model.track_get(reference)->frames) if (&other != trigger && other.atFrame == trigger->atFrame) trigger->atFrame--; return {}; } - Uids frames_paste(Anm2& anm2, Reference reference, const std::set& selection, const std::string& text, + Uids triggers_sort(Model& model, Reference reference) + { + if (auto track = model.track_edit(reference)) frames_sort_by_at_frame(*track); + return {}; + } + + // Pastes clipboard frames after the track's selected frames (or its current frame); triggers go at `time`, stepping + // past occupied frames. Frames lose regions that do not exist on the target layer. + Uids frames_paste(Model& model, Reference reference, const std::set& selection, const std::string& text, int time, std::string* errorString) { - auto track = track_get(anm2, reference); - if (!track) return {}; + auto source = model.track_get(reference); + if (!source) return {}; + auto frames = frames_from_string(text, source->type, errorString); + if (frames.empty()) return {}; auto trackReference = reference; trackReference.frameIndex = -1; auto selected = frames_by_track_get(selection); - auto count = (int)track->children.size(); + auto count = (int)source->frames.size(); auto insertIndex = count; if (auto it = selected.find(trackReference); it != selected.end() && !it->second.empty()) insertIndex = std::min(count, *it->second.rbegin() + 1); else if (reference.frameIndex >= 0 && reference.frameIndex < count) insertIndex = reference.frameIndex + 1; - std::set indices{}; - if (!frames_deserialize(*track, text, reference.itemType == TRIGGER ? time : insertIndex, indices, errorString)) - return {}; - - auto layer = reference.itemType == LAYER ? anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID) : nullptr; - auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - for (auto index : indices) - { - auto frame = track_frame_get(*track, index); - if (!frame) continue; - if (reference.itemType != LAYER) + auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr; + for (auto& frame : frames) + if (reference.itemType != LAYER && reference.itemType != TRIGGER) { - frame->regionId = -1; - frame->crop = frame->size = frame->pivot = {}; + frame.regionId = -1; + frame.crop = frame.size = frame.pivot = {}; } - else if (frame->regionId != -1 && - (!spritesheet || !child_id_get(*spritesheet, ElementType::REGION, frame->regionId))) - frame->regionId = -1; + else if (frame.regionId != -1 && (!spritesheet || !item_get(spritesheet->regions, frame.regionId))) + frame.regionId = -1; + + auto& track = *model.track_edit(reference); + Uids uids{}; + if (track.type != ItemType::TRIGGER) + { + track.frames.insert(track.frames.begin() + insertIndex, frames.begin(), frames.end()); + return frames_uids_get(track, insertIndex, (int)frames.size()); } - anm2.uids_repair(); - Uids uids{}; - for (auto index : indices) - uids.append_range(frames_uids_get(*track, index, 1)); + for (int i = 0; i < (int)frames.size(); ++i) + { + auto& trigger = frames[i]; + trigger.atFrame = time + i; + while (frame_index_from_at_frame_get(track, trigger.atFrame) != -1) + ++trigger.atFrame; + uids.push_back(trigger.uid); + track.frames.push_back(trigger); + } + frames_sort_by_at_frame(track); return uids; } - void frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, + void frame_root_transform_apply(Frame& frame, const Frame& rootFrame, bool isRoundScale, bool isRoundRotation, bool isUseRootPivot) { auto rootScale = math::percent_to_unit(rootFrame.scale); @@ -292,21 +295,22 @@ namespace anm2ed::edit // Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root // frames to a default frame spanning the same time. - Uids root_bake_into(Anm2& anm2, const std::set& rootFrames, const std::set& targets, + Uids root_bake_into(Model& model, const std::set& rootFrames, const std::set& targets, RootBakeOptions options) { auto byTrack = frames_by_track_get(rootFrames); if (byTrack.size() != 1 || targets.empty()) return {}; auto& [rootReference, rootIndices] = *byTrack.begin(); - auto root = track_get(anm2, rootReference); - if (!root) return {}; + auto rootTrack = model.track_get(rootReference); + if (!rootTrack) return {}; + auto root = *rootTrack; std::vector> spans{}; for (auto index : rootIndices) - if (auto frame = track_frame_get(*root, index)) + if (index >= 0 && index < (int)root.frames.size()) { - auto start = (int)frame_time_from_index_get(*root, index); - spans.emplace_back(start, start + frame->duration); + auto start = (int)frame_time_from_index_get(root, index); + spans.emplace_back(start, start + root.frames[index].duration); } if (spans.empty()) return {}; auto is_spanned = [&](int time) @@ -314,63 +318,49 @@ namespace anm2ed::edit for (auto target : targets) { - auto track = track_get(anm2, target); + auto track = model.track_edit(target); if (!track) continue; - auto frameType = track_frame_type_get(*track); if (options.isMatchRootInterpolation) - { - std::vector bakeIndices{}; - int frameIndex{}; - for (const auto& frame : track->children) - if (frame.type == frameType) - { - if (is_spanned((int)frame_time_from_index_get(*track, frameIndex))) bakeIndices.push_back(frameIndex); - ++frameIndex; - } - for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) - frame_bake(*track, *it, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation); - } + for (int index = (int)track->frames.size() - 1; index >= 0; --index) + if (is_spanned((int)frame_time_from_index_get(*track, index))) + frame_bake(*track, index, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation); - int frameIndex{}; - for (auto& frame : track->children) + for (int index = 0; index < (int)track->frames.size(); ++index) { - if (frame.type != frameType) continue; - auto start = (int)frame_time_from_index_get(*track, frameIndex++); + auto start = (int)frame_time_from_index_get(*track, index); if (is_spanned(start)) - frame_root_transform_apply(frame, frame_generate(*root, (float)start), options.isRoundScale, + frame_root_transform_apply(track->frames[index], frame_generate(root, (float)start), options.isRoundScale, options.isRoundRotation, options.isUseRootPivot); } } Uids uids{}; - std::vector rewritten{}; - int frameIndex{}; + std::vector rewritten{}; int defaultDuration{}; auto default_push = [&]() { if (defaultDuration <= 0) return; - auto frame = element_clone(element_make(ElementType::FRAME)); + Frame frame{}; frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN); uids.push_back(frame.uid); rewritten.push_back(frame); defaultDuration = 0; }; - for (const auto& frame : root->children) + for (int index = 0; index < (int)root.frames.size(); ++index) { - if (frame.type == ElementType::FRAME && rootIndices.contains(frameIndex++)) + if (rootIndices.contains(index)) { - defaultDuration += frame.duration; + defaultDuration += root.frames[index].duration; continue; } default_push(); - rewritten.push_back(frame); + rewritten.push_back(root.frames[index]); } default_push(); - root->children = std::move(rewritten); - anm2.uids_repair(); + model.track_edit(rootReference)->frames = std::move(rewritten); return uids; } } diff --git a/src/edit/tracks.cpp b/src/edit/tracks.cpp index 2742630..bc583ee 100644 --- a/src/edit/tracks.cpp +++ b/src/edit/tracks.cpp @@ -1,118 +1,205 @@ #include "edit.hpp" +using namespace anm2ed::model; + namespace anm2ed::edit { - Element* track_container_get(Anm2& anm2, int animationIndex, int type) + std::vector* track_entries_edit(Model& model, int animationIndex, int type) { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); - return animation ? child_first_get(*animation, TYPE_CONTAINERS[type]) : nullptr; + if (type != LAYER && type != NULL_) return nullptr; + auto animation = model.animation_edit(animationIndex); + return animation ? &animation_entries_get(*animation, type) : nullptr; } - Uids items_remove(Anm2& anm2, int animationIndex, const std::map>& ids, + Uids items_remove(Model& model, int animationIndex, const std::map>& ids, const std::map>& groupIds) { for (auto type : {LAYER, NULL_}) { - auto container = track_container_get(anm2, animationIndex, type); - if (!container) continue; auto typeIds = ids.contains(type) ? ids.at(type) : std::set{}; auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set{}; - std::erase_if(container->children, - [&](const Element& item) + if (typeIds.empty() && typeGroupIds.empty()) continue; + auto entries = track_entries_edit(model, animationIndex, type); + if (!entries) continue; + + std::erase_if(*entries, + [&](TrackEntry& entry) { - if (item.type == ElementType::GROUP) return typeGroupIds.contains(item.id); - return item.type == TYPE_TRACKS[type] && - (typeIds.contains(track_id_get(item)) || typeGroupIds.contains(item.groupId)); + if (auto group = std::get_if(&entry)) + { + std::erase_if(group->tracks, [&](const Track& track) { return typeIds.contains(track.id); }); + return typeGroupIds.contains(group->id); + } + return typeIds.contains(std::get(entry).id); }); } return {}; } - Uids items_group(Anm2& anm2, int animationIndex, int type, const std::set& ids, const std::string& name) + // Wraps ungrouped tracks in a new group placed where the first of them was. + Uids items_group(Model& model, int animationIndex, int type, const std::set& ids, const std::string& name) { - auto container = track_container_get(anm2, animationIndex, type); - if (!container) return {}; + auto entries = track_entries_edit(model, animationIndex, type); + if (!entries) return {}; - auto group = element_clone(element_make(ElementType::GROUP)); - group.id = element_child_next_id_get(*container, ElementType::GROUP); - group.name = name; - group.children.push_back(element_clone(root_animation_make())); + int nextId{}; + groups_each(*entries, [&](const TrackGroup& group) { nextId = std::max(nextId, group.id + 1); }); + TrackGroup group{.id = nextId, .name = name}; - auto insertIndex = (int)container->children.size(); - for (int i = 0; i < (int)container->children.size(); ++i) + auto insertIndex = -1; + for (int i = 0; i < (int)entries->size(); ++i) { - auto& item = container->children[i]; - if (item.type != TYPE_TRACKS[type] || !ids.contains(track_id_get(item))) continue; - insertIndex = std::min(insertIndex, i); - item.groupId = group.id; + auto track = std::get_if(&(*entries)[i]); + if (!track || !ids.contains(track->id)) continue; + if (insertIndex == -1) insertIndex = i; + group.tracks.push_back(std::move(*track)); + entries->erase(entries->begin() + i--); } - if (insertIndex == (int)container->children.size()) return {}; + if (insertIndex == -1) return {}; - container->children.insert(container->children.begin() + insertIndex, group); - return {group.uid}; + auto uid = group.uid; + entries->insert(entries->begin() + insertIndex, std::move(group)); + return {uid}; } - // Moves tracks and whole groups next to (or into) a target row. Layers list top-down in reverse of nulls, so the - // drop side flips for them. - Uids items_move(Anm2& anm2, int animationIndex, int type, const std::set& ids, const std::set& groupIds, + // Moves tracks and whole groups next to (or into) a target row. Layers are listed bottom-up, so for them "after" on + // screen is "before" in the file. + Uids items_move(Model& model, int animationIndex, int type, const std::set& ids, const std::set& groupIds, RowTarget target, bool isDropAfter, bool isDropIntoGroup) { - auto container = track_container_get(anm2, animationIndex, type); - if (!container) return {}; if (target.groupId != -1 && groupIds.contains(target.groupId)) return {}; if (target.isGroup && groupIds.contains(target.id)) return {}; + auto entries = track_entries_edit(model, animationIndex, type); + if (!entries) return {}; - auto trackType = TYPE_TRACKS[type]; - auto& children = container->children; - auto is_moved = [&](const Element& item) + std::vector movedTracks{}; + std::vector movedGroups{}; + std::erase_if(*entries, + [&](TrackEntry& entry) + { + if (auto group = std::get_if(&entry)) + { + if (groupIds.contains(group->id)) + { + movedGroups.push_back(std::move(entry)); + return true; + } + std::erase_if(group->tracks, + [&](Track& track) + { + if (!ids.contains(track.id)) return false; + movedTracks.push_back(std::move(track)); + return true; + }); + return false; + } + auto& track = std::get(entry); + if (!ids.contains(track.id)) return false; + movedTracks.push_back(std::move(track)); + return true; + }); + if (movedTracks.empty() && movedGroups.empty()) return {}; + + auto isAfter = type == LAYER ? !isDropAfter : isDropAfter; + auto group_find = [&](int groupId) { - return (item.type == ElementType::GROUP && groupIds.contains(item.id)) || - (item.type == trackType && (ids.contains(track_id_get(item)) || groupIds.contains(item.groupId))); + return std::ranges::find_if(*entries, + [&](const TrackEntry& entry) + { + auto group = std::get_if(&entry); + return group && group->id == groupId; + }); }; - std::vector moved{}; - std::ranges::copy_if(children, std::back_inserter(moved), is_moved); - if (moved.empty()) return {}; - - auto targetIndex = (int)children.size(); - if (target.isGroup || target.type == type) + // Where top-level items go: beside the target row, or beside the group that holds it. + auto topIndex = (int)entries->size(); + if (target.isGroup || target.groupId != -1) { - auto rowIndex = -1; - auto groupEndIndex = -1; - for (int i = 0; i < (int)children.size(); ++i) - { - auto& item = children[i]; - auto isGroupRow = item.type == ElementType::GROUP && item.id == target.id; - if ((target.isGroup && isGroupRow) || - (!target.isGroup && item.type == trackType && track_id_get(item) == target.id)) - if (rowIndex == -1) rowIndex = i; - if (isGroupRow || (item.type == trackType && item.groupId == target.id)) groupEndIndex = i; - } - if (rowIndex == -1) return {}; - if (target.isGroup) - targetIndex = type == LAYER ? (isDropAfter ? rowIndex : groupEndIndex + 1) : rowIndex + isDropAfter; - else - targetIndex = rowIndex + (type == LAYER ? !isDropAfter : isDropAfter); + auto group = group_find(target.isGroup ? target.id : target.groupId); + if (group != entries->end()) topIndex = (int)(group - entries->begin()) + isAfter; + } + else if (target.type == type) + { + auto track = std::ranges::find_if(*entries, + [&](const TrackEntry& entry) + { + auto track = std::get_if(&entry); + return track && track->id == target.id; + }); + if (track != entries->end()) topIndex = (int)(track - entries->begin()) + isAfter; } - for (int i = (int)children.size() - 1; i >= 0; --i) - if (is_moved(children[i])) - { - if (i < targetIndex) --targetIndex; - children.erase(children.begin() + i); - } + auto intoGroupId = target.isGroup && isDropIntoGroup ? target.id : !target.isGroup ? target.groupId : -1; + auto intoGroup = intoGroupId == -1 ? entries->end() : group_find(intoGroupId); + if (intoGroup != entries->end()) + { + // Into a group header lands just under it on screen; beside a grouped track lands beside it. + auto& tracks = std::get(*intoGroup).tracks; + auto beside = std::ranges::find_if(tracks, [&](const Track& track) { return track.id == target.id; }); + auto position = target.isGroup ? (type == LAYER ? tracks.end() : tracks.begin()) + : beside != tracks.end() ? beside + isAfter + : tracks.end(); + tracks.insert(position, std::make_move_iterator(movedTracks.begin()), std::make_move_iterator(movedTracks.end())); + movedTracks.clear(); + } - auto targetGroupId = target.isGroup && isDropIntoGroup ? target.id : target.type == type ? target.groupId : -1; - for (auto& item : moved) - if (item.type == trackType && !groupIds.contains(item.groupId)) item.groupId = targetGroupId; - - children.insert(children.begin() + std::clamp(targetIndex, 0, (int)children.size()), moved.begin(), moved.end()); + std::vector topMoved{}; + for (auto& track : movedTracks) + topMoved.emplace_back(std::move(track)); + topMoved.insert(topMoved.end(), std::make_move_iterator(movedGroups.begin()), + std::make_move_iterator(movedGroups.end())); + entries->insert(entries->begin() + std::clamp(topIndex, 0, (int)entries->size()), + std::make_move_iterator(topMoved.begin()), std::make_move_iterator(topMoved.end())); return {}; } - Uids animation_length_fit(Anm2& anm2, int animationIndex) + Uids animation_length_fit(Model& model, int animationIndex) { - if (auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex)) - animation->frameNum = animation_length_get(*animation); + if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = animation_length_get(*animation); return {}; } + + // Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation. + int item_add(Model& model, ItemType type, int animationIndex, int id, const std::string& name, int spritesheetId, + bool isShowRect, int insertBeforeId, types::destination::Type destination) + { + auto& content = model.content; + if (type == ItemType::LAYER) + { + if (id == -1) id = item_next_id_get(content.layers); + auto layer = item_get(content.layers, id); + if (!layer) layer = &content.layers.emplace_back(Layer{.id = id}); + if (!name.empty()) layer->name = name; + layer->spritesheetId = item_get(content.spritesheets, spritesheetId) ? spritesheetId : 0; + } + else if (type == ItemType::NULL_) + { + if (id == -1) id = item_next_id_get(content.nulls); + auto null = item_get(content.nulls, id); + if (!null) null = &content.nulls.emplace_back(Null{.id = id}); + if (!name.empty()) null->name = name; + null->isShowRect = isShowRect; + } + else + return -1; + + auto add = [&](int index) + { + if (model.track_get({index, (int)type, id})) return; + auto& entries = animation_entries_get(*model.animation_edit(index), (int)type); + auto before = std::ranges::find_if(entries, + [&](const TrackEntry& entry) + { + auto track = std::get_if(&entry); + return track && track->id == insertBeforeId; + }); + entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id}); + }; + + if (destination == types::destination::ALL) + for (int i = 0; i < model.animations_count_get(); ++i) + add(i); + else if (model.animation_get(animationIndex)) + add(animationIndex); + return id; + } } diff --git a/src/imgui/documents.cpp b/src/imgui/documents.cpp index c7f3369..0b9c19d 100644 --- a/src/imgui/documents.cpp +++ b/src/imgui/documents.cpp @@ -52,10 +52,10 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) { document.edit_apply(EDIT_MERGE_ANM2, - [&](Anm2& anm2) + [&](model::Model& model) { for (auto& path : paths) - anm2.file_merge(path, document.directory_get(), preset); + edit::file_merge(model, path, document.directory_get(), preset); }); }}); } @@ -311,12 +311,9 @@ namespace anm2ed::imgui if (isSpritesheetDirty) { - auto spritesheets = closeDocument.anm2.element_get(ElementType::SPRITESHEETS); - if (spritesheets) { - for (auto& spritesheet : spritesheets->children) + for (auto& spritesheet : closeDocument.model.content.spritesheets) { - if (spritesheet.type != ElementType::SPRITESHEET) continue; auto id = spritesheet.id; auto texture = closeDocument.texture_get(id); if (texture && closeDocument.spritesheet_is_dirty(id)) diff --git a/src/imgui/popup/item_properties.cpp b/src/imgui/popup/item_properties.cpp index c9b6300..580c03b 100644 --- a/src/imgui/popup/item_properties.cpp +++ b/src/imgui/popup/item_properties.cpp @@ -18,12 +18,6 @@ namespace anm2ed::imgui::popup addItemSpritesheetID = {}; } - std::set ItemProperties::unused_items_get(Anm2& anm2, const Element* animation, int type) - { - auto row = track_container_get((ItemType)type); - return animation && row ? anm2.element_unused(row->element, animation) : std::set{}; - } - void ItemProperties::open() { reset(); @@ -33,8 +27,14 @@ namespace anm2ed::imgui::popup bool ItemProperties::update(Manager& manager, Settings& settings, Document& document, Reference& reference) { bool isAdded{}; - auto& anm2 = document.anm2; - auto animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); + auto& model = document.model; + auto animation = model.animation_get(reference.animationIndex); + auto unused_items_get = [&](int type) + { + return animation + ? model.unused_get(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, animation) + : std::set{}; + }; popup.trigger(); @@ -81,7 +81,7 @@ namespace anm2ed::imgui::popup ImGui::SeparatorText(localize.get(LABEL_SOURCE)); - auto isUnusedItems = animation && !unused_items_get(anm2, animation, (int)type).empty(); + auto isUnusedItems = animation && !unused_items_get(type).empty(); spaced_pair( [&]() { @@ -135,7 +135,7 @@ namespace anm2ed::imgui::popup if (ImGui::BeginChild("##Existing Items", ImVec2(0, 0))) { - auto unusedItems = unused_items_get(anm2, animation, (int)type); + auto unusedItems = unused_items_get(type); if (addItemID != -1 && !unusedItems.contains(addItemID)) addItemID = -1; for (auto id : unusedItems) @@ -146,7 +146,7 @@ namespace anm2ed::imgui::popup if (type == LAYER) { - if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id)) + if (auto layer = model::item_get(model.content.layers, id)) { auto label = std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(id, layer->name, layer->spritesheetId)); @@ -159,9 +159,7 @@ namespace anm2ed::imgui::popup } else if (type == NULL_) { - auto nulls = anm2.element_get(ElementType::NULLS); - auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; - if (null) + if (auto null = model::item_get(model.content.nulls, id)) { auto label = std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); if (ImGui::Selectable(label.c_str(), isSelected)) @@ -197,19 +195,15 @@ namespace anm2ed::imgui::popup manager.command_push({manager.selected, [=](Manager&, Document& document) { - Element item{}; - item.id = queuedAddItemID; - item.name = queuedAddItemName; - item.spritesheetId = queuedAddItemSpritesheetID; - item.isShowRect = queuedAddItemIsShowRect; - int addId{-1}; document.edit_apply(EDIT_ADD_ITEM, - [&](Anm2& anm2) + [&](model::Model& model) { - addId = anm2.item_add((ItemType)queuedType, queuedAnimationIndex, - item, queuedInsertBeforeID, - (destination::Type)queuedDestination); + addId = edit::item_add( + model, (ItemType)queuedType, queuedAnimationIndex, + queuedAddItemID, queuedAddItemName, + queuedAddItemSpritesheetID, queuedAddItemIsShowRect, + queuedInsertBeforeID, (destination::Type)queuedDestination); }); if (addId != -1) @@ -218,7 +212,7 @@ namespace anm2ed::imgui::popup document.selected_set(SelectionKind::TRACKS, {document.reference_get()}); document.frame_references_clear(); if (queuedType == LAYER) - if (auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, addId)) + if (auto layer = model::item_get(document.model.content.layers, addId)) document.spritesheet.reference = layer->spritesheetId; } }}); diff --git a/src/imgui/popup/item_properties.hpp b/src/imgui/popup/item_properties.hpp index f12e838..c03d5fd 100644 --- a/src/imgui/popup/item_properties.hpp +++ b/src/imgui/popup/item_properties.hpp @@ -19,7 +19,6 @@ namespace anm2ed::imgui::popup int addItemSpritesheetID{-1}; void reset(); - std::set unused_items_get(Anm2&, const Element*, int); public: void open(); diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 11ddfbf..28ab791 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -65,25 +65,11 @@ namespace anm2ed::imgui { auto document = manager.get(); auto itemType = document ? (ItemType)document->reference_get().itemType : ItemType::NONE; - auto animation = document - ? document->anm2.element_get(ElementType::ANIMATION, document->reference_get().animationIndex) - : nullptr; + auto animation = document ? document->model.animation_get(document->reference_get().animationIndex) : nullptr; auto layerReferences = document ? document->layer_references_get() : std::vector{}; bool isGenerateAnimationFromGridAvailable = !layerReferences.empty(); - bool hasRegions = false; - if (document) - { - if (auto spritesheets = document->anm2.element_get(ElementType::SPRITESHEETS)) - { - for (auto& spritesheet : spritesheets->children) - for (auto& child : spritesheet.children) - if (spritesheet.type == ElementType::SPRITESHEET && child.type == ElementType::REGION) - { - hasRegions = true; - break; - } - } - } + bool hasRegions = document && std::ranges::any_of(document->model.content.spritesheets, [](const auto& spritesheet) + { return !spritesheet.regions.empty(); }); if (ImGui::BeginMainMenuBar()) { @@ -170,9 +156,11 @@ namespace anm2ed::imgui if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions)) { - manager.command_push( - {manager.selected, [](Manager&, Document& document) - { document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, [](Anm2& anm2) { anm2.regions_scan(); }); }}); + manager.command_push({manager.selected, [](Manager&, Document& document) + { + document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, + [](model::Model& model) { return edit::regions_scan(model); }); + }}); toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS)); @@ -265,9 +253,8 @@ namespace anm2ed::imgui std::set animationIndices{}; if (generateRegionsTarget == GENERATE_REGIONS_TARGET_ALL) { - if (auto animations = document->anm2.element_get(ElementType::ANIMATIONS)) - for (auto [i, animation] : std::views::enumerate(animations->children)) - if (animation.type == ElementType::ANIMATION) animationIndices.insert((int)i); + for (int i = 0; i < document->model.animations_count_get(); ++i) + animationIndices.insert(i); } else { @@ -279,14 +266,16 @@ namespace anm2ed::imgui auto queuedAnimationIndices = animationIndices; auto queuedFormat = settings.generateRegionNameFormat; auto queuedMapping = isGenerateRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; - manager.command_push( - {manager.selected, [=](Manager&, Document& document) - { - if (queuedAnimationIndices.empty()) return; - document.edit_apply( - EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, [&](Anm2& anm2) - { anm2.regions_generate(queuedAnimationIndices, {}, queuedFormat, queuedMapping); }); - }}); + manager.command_push({manager.selected, [=](Manager&, Document& document) + { + if (queuedAnimationIndices.empty()) return; + document.edit_apply(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, + [&](model::Model& model) + { + return edit::regions_generate(model, queuedAnimationIndices, {}, + queuedFormat, queuedMapping); + }); + }}); generateRegionsPopup.close(); } diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index e7cba6f..de90a84 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -17,6 +17,7 @@ #include "actions.hpp" #include "log.hpp" #include "math.hpp" +#include "model/frames.hpp" #include "path.hpp" #include "strings.hpp" #include "toast.hpp" @@ -56,15 +57,11 @@ namespace anm2ed::imgui for (auto& document : manager.documents) { auto documentLabel = path::to_utf8(document.filename_get()); - int animationIndex{}; - if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto label = std::format("{} ({})", animation.name, documentLabel); - options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label}); - ++animationIndex; - } + for (auto [animationIndex, animation] : document.model.animations_get()) + { + auto label = std::format("{} ({})", animation->name, documentLabel); + options.push_back({.documentId = document.tabId, .animationIndex = animationIndex, .label = label}); + } } return options; @@ -107,16 +104,18 @@ namespace anm2ed::imgui return vec4(minPoint, maxPoint - minPoint); } - std::optional animation_render_rect_get(Manager& manager, Document& document, Element* animation, + std::optional animation_render_rect_get(Manager& manager, Document& document, const model::Animation* animation, bool isRootTransform) { std::optional rect{}; - if (animation) rect = animation_rects_merge(rect, document.anm2.animation_rect(*animation, isRootTransform)); + if (animation) + rect = animation_rects_merge(rect, model::animation_rect(document.model, *animation, isRootTransform)); if (auto overlayDocument = overlay_animation_document_get(manager, document)) - if (auto overlayAnimation = overlayDocument->anm2.element_get(ElementType::ANIMATION, document.overlayIndex)) - rect = animation_rects_merge(rect, overlayDocument->anm2.animation_rect(*overlayAnimation, isRootTransform)); + if (auto overlayAnimation = overlayDocument->model.animation_get(document.overlayIndex)) + rect = animation_rects_merge(rect, + model::animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform)); return rect; } @@ -191,13 +190,12 @@ namespace anm2ed::imgui } } - int trigger_sound_id_get(Document& document, Element* animation, float time, int deterministicIndex = -1) + int trigger_sound_id_get(Document& document, const model::Animation* animation, float time, + int deterministicIndex = -1) { - if (!animation) return -1; - auto triggers = animation_item_get(*animation, ItemType::TRIGGER); - if (!triggers || !triggers->isVisible) return -1; + if (!animation || !animation->triggers.isVisible) return -1; - auto trigger = frame_generate(*triggers, time); + auto trigger = model::frame_generate(animation->triggers, time); if (!trigger.isVisible || trigger.soundIds.empty()) return -1; size_t soundIndex{}; @@ -262,7 +260,7 @@ namespace anm2ed::imgui void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSeconds) { auto& document = *manager.get(); - auto& anm2 = document.anm2; + auto& model = document.model; auto& playback = document.playback; auto& frameTime = document.frameTime; auto& zoom = document.previewZoom; @@ -420,7 +418,7 @@ namespace anm2ed::imgui if (playback.isPlaying) { - auto animation = anm2.element_get(ElementType::ANIMATION, document.reference_get().animationIndex); + auto animation = model.animation_get(document.reference_get().animationIndex); auto& isSound = settings.timelineIsSound; if (!animation) @@ -437,8 +435,7 @@ namespace anm2ed::imgui if (auto sound = document.sound_get(soundID)) audio::play(*sound, false, mixer); } - auto info = element_first_get(anm2.root, ElementType::INFO); - auto fps = std::max(info ? info->fps : 30, 1); + auto fps = std::max(model.info.fps, 1); playback.tick(fps, animation->frameNum, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, deltaSeconds); @@ -455,10 +452,10 @@ namespace anm2ed::imgui isFocused = false; auto& document = *manager.get(); - auto& anm2 = document.anm2; + auto& model = document.model; auto& playback = document.playback; auto reference = document.reference_get(); - auto animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); + auto animation = model.animation_get(reference.animationIndex); auto& pan = document.previewPan; auto& zoom = document.previewZoom; auto& backgroundColor = settings.previewBackgroundColor; @@ -488,7 +485,7 @@ namespace anm2ed::imgui auto fit_view = [&]() { - if (animation) set_to_rect(zoom, pan, anm2.animation_rect(*animation, isRootTransform)); + if (animation) set_to_rect(zoom, pan, model::animation_rect(model, *animation, isRootTransform)); }; manager.isAbleToRecord = false; @@ -673,8 +670,7 @@ namespace anm2ed::imgui manager.isRecordingStart = false; manager.isRecording = true; renderFrameIndex = 0; - auto info = element_first_get(anm2.root, ElementType::INFO); - renderAnimationFps = std::max(info ? info->fps : 30, 1); + renderAnimationFps = std::max(model.info.fps, 1); renderFrameRate = render::fps_get(settings.renderFpsMode, renderAnimationFps, settings.playbackTickRate); renderFrameCount = render::frame_count_get(manager.recordingStart, manager.recordingEnd, renderAnimationFps, renderFrameRate); @@ -808,68 +804,55 @@ namespace anm2ed::imgui return false; }; - auto render = [&](Document& sampleDocument, Element* animation, float time, vec3 colorOffset = {}, + auto render = [&](Document& sampleDocument, const model::Animation* animation, float time, vec3 colorOffset = {}, float alphaOffset = {}, const std::vector* layeredOnions = nullptr, bool isIndexMode = false) { - auto& sampleAnm2 = sampleDocument.anm2; + auto& sampleModel = sampleDocument.model; bool isActiveDocument = &sampleDocument == &document; - auto sample_time_for_item = [&](Element& item, const OnionskinSample& sample) -> std::optional + auto sample_time_for_item = [&](const model::Track& item, const OnionskinSample& sample) -> std::optional { if (!isIndexMode) { if (sample.time < 0.0f || sample.time > animation->frameNum) return std::nullopt; return sample.time; } - if (item.children.empty()) return std::nullopt; - int baseIndex = frame_index_from_time_get(item, frameTime); + if (item.frames.empty()) return std::nullopt; + int baseIndex = model::frame_index_from_time_get(item, frameTime); if (baseIndex < 0) return std::nullopt; int sampleIndex = baseIndex + sample.indexOffset; - if (!track_frame_get(item, sampleIndex)) return std::nullopt; - return frame_time_from_index_get(item, sampleIndex); + if (sampleIndex < 0 || sampleIndex >= (int)item.frames.size()) return std::nullopt; + return model::frame_time_from_index_get(item, sampleIndex); }; - auto root = animation_item_get(*animation, ItemType::ROOT); + auto root = &animation->root; auto transform_for_time = [&](float t) { auto sampleTransform = baseTransform; if (isRootTransform && root) { - auto rootFrame = frame_generate(*root, t); - sampleTransform *= frame_parent_model_get(rootFrame); + auto rootFrame = model::frame_generate(*root, t); + sampleTransform *= model::frame_parent_model_get(rootFrame); } return sampleTransform; }; auto transform = transform_for_time(time); - auto is_track_group_visible = [](const Element& container, const Element& track) + auto group_root_frame_get = [](const model::TrackGroup* group, float t) -> std::optional { - if (track.groupId == -1) return true; - for (const auto& child : container.children) - if (child.type == ElementType::GROUP && child.id == track.groupId) return child.isVisible; - return true; + if (!group) return std::nullopt; + return model::frame_generate(group->root, t); }; - auto group_root_frame_get = [](const Element& container, const Element& track, - float t) -> std::optional - { - if (track.groupId == -1) return std::nullopt; - auto group = child_id_get(container, ElementType::GROUP, track.groupId); - auto root = group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; - if (!root) return std::nullopt; - return frame_generate(*root, t); - }; - - auto group_transform_for_time = - [&](const Element& container, const Element& track, float t, const glm::mat4& sampleTransform) + auto group_transform_for_time = [&](const model::TrackGroup* group, float t, const glm::mat4& sampleTransform) { auto itemTransform = sampleTransform; if (isRootTransform) - if (auto groupRootFrame = group_root_frame_get(container, track, t)) - itemTransform *= frame_parent_model_get(*groupRootFrame); + if (auto groupRootFrame = group_root_frame_get(group, t)) + itemTransform *= model::frame_parent_model_get(*groupRootFrame); return itemTransform; }; @@ -877,7 +860,7 @@ namespace anm2ed::imgui [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, float sampleAlpha, bool isOnion) { if (!root) return; - auto rootFrame = frame_generate(*root, sampleTime); + auto rootFrame = model::frame_generate(*root, sampleTime); if (isOnlyShowLayers || !rootFrame.isVisible || !root->isVisible) return; auto rootModel = isRootTransform @@ -903,16 +886,14 @@ namespace anm2ed::imgui draw_root(time, transform, {}, 0.0f, false); - auto draw_group_root = [&](Element& group, int groupType, float sampleTime, const glm::mat4& sampleTransform, - vec3 sampleColor, float sampleAlpha, bool isOnion) + auto draw_group_root = [&](const model::TrackGroup& group, int groupType, float sampleTime, + const glm::mat4& sampleTransform, vec3 sampleColor, float sampleAlpha, bool isOnion) { - auto groupRoot = child_first_get(group, ElementType::ROOT_ANIMATION); - if (!groupRoot) return; - auto rootFrame = frame_generate(*groupRoot, sampleTime); - if (isOnlyShowLayers || !rootFrame.isVisible || !groupRoot->isVisible) return; + auto rootFrame = model::frame_generate(group.root, sampleTime); + if (isOnlyShowLayers || !rootFrame.isVisible || !group.root.isVisible) return; auto itemTransform = sampleTransform; - if (isRootTransform) itemTransform *= frame_parent_model_get(rootFrame); + if (isRootTransform) itemTransform *= model::frame_parent_model_get(rootFrame); auto rootModel = isRootTransform ? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) @@ -928,200 +909,173 @@ namespace anm2ed::imgui texture_render(shaderTexture, resources.icon_id_get(icon), rootTransform, color); }; - if (auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) + // Draws loose tracks and visible groups (their root, then their tracks) in file order. + auto entries_draw = [&](const std::vector& entries, int groupType, auto&& track_draw) { - auto layer_animation_draw = [&](auto&& self, Element& layerAnimation, bool isParentVisible = true) -> void + for (const auto& entry : entries) { - if (layerAnimation.type == ElementType::GROUP) + if (auto track = std::get_if(&entry)) { - if (isParentVisible && layerAnimation.isVisible) - { - auto groupRoot = child_first_get(layerAnimation, ElementType::ROOT_ANIMATION); - if (layeredOnions && groupRoot) - for (auto& sample : *layeredOnions) - if (auto sampleTime = sample_time_for_item(*groupRoot, sample)) - { - auto sampleTransform = transform_for_time(*sampleTime); - draw_group_root(layerAnimation, LAYER, *sampleTime, sampleTransform, sample.colorOffset, - sample.alphaOffset, true); - } - draw_group_root(layerAnimation, LAYER, time, transform, {}, 0.0f, false); - } - for (auto& child : layerAnimation.children) - self(self, child, isParentVisible && layerAnimation.isVisible); - return; + track_draw(*track, nullptr); + continue; } - if (layerAnimation.type != ElementType::LAYER_ANIMATION || !isParentVisible || !layerAnimation.isVisible || - !is_track_group_visible(*layerAnimations, layerAnimation)) - return; - - auto id = layerAnimation.layerId; - auto layer = sampleAnm2.element_get(ElementType::LAYER_ELEMENT, id); - if (!layer) return; - - auto textureInfo = sampleDocument.texture_get(layer->spritesheetId); - if (!textureInfo || !textureInfo->is_valid()) return; - - auto draw_layer = [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, - float sampleAlpha, bool isOnion) - { - auto frame = frame_generate(layerAnimation, sampleTime); - if (!frame.isVisible) return; - - auto& texture = *textureInfo; - - auto texSize = vec2(texture.size); - if (texSize.x <= 0.0f || texSize.y <= 0.0f) return; - - frame = sampleAnm2.frame_effective(id, frame); - auto crop = frame.crop; - auto size = frame.size; - auto pivot = frame.pivot; - - auto layerModel = math::quad_model_get(size, frame.position, pivot, math::percent_to_unit(frame.scale), - frame.rotation, math::percent_to_unit(frame.shear)); - auto itemTransform = - group_transform_for_time(*layerAnimations, layerAnimation, sampleTime, sampleTransform); - auto layerTransform = itemTransform * layerModel; - - auto uvMin = crop / texSize; - auto uvMax = (crop + size) / texSize; - - vec3 frameColorOffset = frame.colorOffset + colorOffset + sampleColor; - vec4 frameTint = frame.tint; - - if (isRootTransform && root) - { - auto rootFrame = frame_generate(*root, sampleTime); - frameColorOffset += rootFrame.colorOffset; - frameTint *= rootFrame.tint; - } - if (isRootTransform) - if (auto groupRootFrame = group_root_frame_get(*layerAnimations, layerAnimation, sampleTime)) - { - frameColorOffset += groupRootFrame->colorOffset; - frameTint *= groupRootFrame->tint; - } - - frameTint.a = std::max(0.0f, frameTint.a - (alphaOffset + sampleAlpha)); - - auto vertices = math::uv_vertices_get(uvMin, uvMax); - auto customShader = sampleDocument.shader_get(frame.shaderId); - auto& layerShader = customShader ? *customShader : shaderTexture; - - texture_render(layerShader, resource::texture::id_get(texture), layerTransform, frameTint, - frameColorOffset, vertices.data(), vec2(texture.size), sampleTime); - - auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) - : is_layer_animation_selected(sampleDocument, id) ? SELECTED_LAYER_BORDER_COLOR - : color::RED; - - if (isBorder) rect_render(shaderLine, layerTransform, layerModel, color); - - if (isPivots) - { - auto pivotModel = math::quad_model_get(PIVOT_SIZE, frame.position, PIVOT_SIZE * 0.5f, - math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.shear)); - auto pivotTransform = itemTransform * pivotModel; - - texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, color); - } - }; - + auto& group = std::get(entry); + if (!group.isVisible) continue; if (layeredOnions) for (auto& sample : *layeredOnions) - if (auto sampleTime = sample_time_for_item(layerAnimation, sample)) - { - auto sampleTransform = transform_for_time(*sampleTime); - draw_layer(*sampleTime, sampleTransform, sample.colorOffset, sample.alphaOffset, true); - } + if (auto sampleTime = sample_time_for_item(group.root, sample)) + draw_group_root(group, groupType, *sampleTime, transform_for_time(*sampleTime), sample.colorOffset, + sample.alphaOffset, true); + draw_group_root(group, groupType, time, transform, {}, 0.0f, false); + for (const auto& groupTrack : group.tracks) + track_draw(groupTrack, &group); + } + }; - draw_layer(time, transform, {}, 0.0f, false); - }; - for (auto& layerAnimation : layerAnimations->children) - layer_animation_draw(layer_animation_draw, layerAnimation); - } + entries_draw(animation->layers, LAYER, + [&](const model::Track& layerAnimation, const model::TrackGroup* group) + { + if (!layerAnimation.isVisible) return; - if (auto nullAnimations = child_first_get(*animation, ElementType::NULL_ANIMATIONS)) - { - auto null_animation_draw = [&](auto&& self, Element& nullAnimation, bool isParentVisible = true) -> void - { - if (nullAnimation.type == ElementType::GROUP) - { - if (isParentVisible && nullAnimation.isVisible) - { - auto groupRoot = child_first_get(nullAnimation, ElementType::ROOT_ANIMATION); - if (layeredOnions && groupRoot) - for (auto& sample : *layeredOnions) - if (auto sampleTime = sample_time_for_item(*groupRoot, sample)) - { - auto sampleTransform = transform_for_time(*sampleTime); - draw_group_root(nullAnimation, NULL_, *sampleTime, sampleTransform, sample.colorOffset, - sample.alphaOffset, true); - } - draw_group_root(nullAnimation, NULL_, time, transform, {}, 0.0f, false); - } - for (auto& child : nullAnimation.children) - self(self, child, isParentVisible && nullAnimation.isVisible); - return; - } - if (nullAnimation.type != ElementType::NULL_ANIMATION || !isParentVisible || !nullAnimation.isVisible || - !is_track_group_visible(*nullAnimations, nullAnimation) || isOnlyShowLayers) - return; + auto id = layerAnimation.id; + auto layer = model::item_get(sampleModel.content.layers, id); + if (!layer) return; - auto id = nullAnimation.nullId; - auto nulls = sampleAnm2.element_get(ElementType::NULLS); - auto nullInfo = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; - if (!nullInfo) return; - auto isShowRect = nullInfo->isShowRect; + auto textureInfo = sampleDocument.texture_get(layer->spritesheetId); + if (!textureInfo || !textureInfo->is_valid()) return; - auto draw_null = [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, - float sampleAlpha, bool isOnion) - { - auto frame = frame_generate(nullAnimation, sampleTime); - if (!frame.isVisible) return; + auto draw_layer = [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, + float sampleAlpha, bool isOnion) + { + auto frame = model::frame_generate(layerAnimation, sampleTime); + if (!frame.isVisible) return; - auto icon = isShowRect ? icon::POINT : isAltIcons ? icon::TARGET_ALT : icon::TARGET; + auto& texture = *textureInfo; - auto& size = isShowRect ? POINT_SIZE : TARGET_SIZE; - auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) - : isActiveDocument && id == reference.itemID && referenceItemType == ItemType::NULL_ - ? color::RED - : NULL_COLOR; + auto texSize = vec2(texture.size); + if (texSize.x <= 0.0f || texSize.y <= 0.0f) return; - auto nullModel = - math::quad_model_get(size, frame.position, size * 0.5f, math::percent_to_unit(frame.scale), - frame.rotation, math::percent_to_unit(frame.shear)); - auto itemTransform = - group_transform_for_time(*nullAnimations, nullAnimation, sampleTime, sampleTransform); - auto nullTransform = itemTransform * nullModel; + frame = sampleModel.frame_effective(id, frame); + auto crop = frame.crop; + auto size = frame.size; + auto pivot = frame.pivot; - texture_render(shaderTexture, resources.icon_id_get(icon), nullTransform, color); + auto layerModel = + math::quad_model_get(size, frame.position, pivot, math::percent_to_unit(frame.scale), + frame.rotation, math::percent_to_unit(frame.shear)); + auto itemTransform = group_transform_for_time(group, sampleTime, sampleTransform); + auto layerTransform = itemTransform * layerModel; - if (isShowRect) - { - auto rectModel = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), - frame.rotation, math::percent_to_unit(frame.shear)); - auto rectTransform = itemTransform * rectModel; + auto uvMin = crop / texSize; + auto uvMax = (crop + size) / texSize; - rect_render(shaderLine, rectTransform, rectModel, color); - } - }; + vec3 frameColorOffset = frame.colorOffset + colorOffset + sampleColor; + vec4 frameTint = frame.tint; - if (layeredOnions) - for (auto& sample : *layeredOnions) - if (auto sampleTime = sample_time_for_item(nullAnimation, sample)) - { - auto sampleTransform = transform_for_time(*sampleTime); - draw_null(*sampleTime, sampleTransform, sample.colorOffset, sample.alphaOffset, true); - } + if (isRootTransform && root) + { + auto rootFrame = model::frame_generate(*root, sampleTime); + frameColorOffset += rootFrame.colorOffset; + frameTint *= rootFrame.tint; + } + if (isRootTransform) + if (auto groupRootFrame = group_root_frame_get(group, sampleTime)) + { + frameColorOffset += groupRootFrame->colorOffset; + frameTint *= groupRootFrame->tint; + } - draw_null(time, transform, {}, 0.0f, false); - }; - for (auto& nullAnimation : nullAnimations->children) - null_animation_draw(null_animation_draw, nullAnimation); - } + frameTint.a = std::max(0.0f, frameTint.a - (alphaOffset + sampleAlpha)); + + auto vertices = math::uv_vertices_get(uvMin, uvMax); + auto customShader = sampleDocument.shader_get(frame.shaderId); + auto& layerShader = customShader ? *customShader : shaderTexture; + + texture_render(layerShader, resource::texture::id_get(texture), layerTransform, frameTint, + frameColorOffset, vertices.data(), vec2(texture.size), sampleTime); + + auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) + : is_layer_animation_selected(sampleDocument, id) ? SELECTED_LAYER_BORDER_COLOR + : color::RED; + + if (isBorder) rect_render(shaderLine, layerTransform, layerModel, color); + + if (isPivots) + { + auto pivotModel = math::quad_model_get(PIVOT_SIZE, frame.position, PIVOT_SIZE * 0.5f, + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); + auto pivotTransform = itemTransform * pivotModel; + + texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, color); + } + }; + + if (layeredOnions) + for (auto& sample : *layeredOnions) + if (auto sampleTime = sample_time_for_item(layerAnimation, sample)) + { + auto sampleTransform = transform_for_time(*sampleTime); + draw_layer(*sampleTime, sampleTransform, sample.colorOffset, sample.alphaOffset, true); + } + + draw_layer(time, transform, {}, 0.0f, false); + }); + + entries_draw(animation->nulls, NULL_, + [&](const model::Track& nullAnimation, const model::TrackGroup* group) + { + if (!nullAnimation.isVisible || isOnlyShowLayers) return; + + auto id = nullAnimation.id; + auto nullInfo = model::item_get(sampleModel.content.nulls, id); + if (!nullInfo) return; + auto isShowRect = nullInfo->isShowRect; + + auto draw_null = [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, + float sampleAlpha, bool isOnion) + { + auto frame = model::frame_generate(nullAnimation, sampleTime); + if (!frame.isVisible) return; + + auto icon = isShowRect ? icon::POINT : isAltIcons ? icon::TARGET_ALT : icon::TARGET; + + auto& size = isShowRect ? POINT_SIZE : TARGET_SIZE; + auto color = + isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) + : isActiveDocument && id == reference.itemID && referenceItemType == ItemType::NULL_ + ? color::RED + : NULL_COLOR; + + auto nullModel = + math::quad_model_get(size, frame.position, size * 0.5f, math::percent_to_unit(frame.scale), + frame.rotation, math::percent_to_unit(frame.shear)); + auto itemTransform = group_transform_for_time(group, sampleTime, sampleTransform); + auto nullTransform = itemTransform * nullModel; + + texture_render(shaderTexture, resources.icon_id_get(icon), nullTransform, color); + + if (isShowRect) + { + auto rectModel = + math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), + frame.rotation, math::percent_to_unit(frame.shear)); + auto rectTransform = itemTransform * rectModel; + + rect_render(shaderLine, rectTransform, rectModel, color); + } + }; + + if (layeredOnions) + for (auto& sample : *layeredOnions) + if (auto sampleTime = sample_time_for_item(nullAnimation, sample)) + { + auto sampleTransform = transform_for_time(*sampleTime); + draw_null(*sampleTime, sampleTransform, sample.colorOffset, sample.alphaOffset, true); + } + + draw_null(time, transform, {}, 0.0f, false); + }); }; if (animation) @@ -1130,7 +1084,7 @@ namespace anm2ed::imgui auto overlay_render = [&]() { if (auto overlayDocument = overlay_animation_document_get(manager, document)) - if (auto overlayAnimation = overlayDocument->anm2.element_get(ElementType::ANIMATION, overlayIndex)) + if (auto overlayAnimation = overlayDocument->model.animation_get(overlayIndex)) render(*overlayDocument, overlayAnimation, frameTime, {}, 1.0f - math::percent_to_unit(overlayTransparency), layeredOnions, settings.onionskinMode == (int)OnionskinMode::INDEX); @@ -1206,10 +1160,10 @@ namespace anm2ed::imgui isPreviewHovered = ImGui::IsItemHovered(); - auto triggers = animation ? animation_item_get(*animation, ItemType::TRIGGER) : nullptr; - if (animation && triggers && triggers->isVisible && !isOnlyShowLayers && !manager.isRecording) + if (animation && animation->triggers.isVisible && !isOnlyShowLayers && !manager.isRecording) { - if (auto trigger = frame_generate(*triggers, frameTime); trigger.isVisible && trigger.eventId > -1) + if (auto trigger = model::frame_generate(animation->triggers, frameTime); + trigger.isVisible && trigger.eventId > -1) { auto clipMin = ImGui::GetItemRectMin(); auto clipMax = ImGui::GetItemRectMax(); @@ -1219,9 +1173,8 @@ namespace anm2ed::imgui drawList->PushClipRect(clipMin, clipMax); ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE_LARGE); auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK; - auto events = anm2.element_get(ElementType::EVENTS); - auto event = events ? child_id_get(*events, ElementType::EVENT_ELEMENT, trigger.eventId) : nullptr; - if (event) drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), event->name.c_str()); + if (auto event = model::item_get(model.content.events, trigger.eventId)) + drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), event->name.c_str()); ImGui::PopFont(); drawList->PopClipRect(); } @@ -1279,16 +1232,12 @@ namespace anm2ed::imgui editItemType = static_cast(editReference.itemType); } - auto frame = anm2.element_get(editReference); - auto editItemReference = editReference; - editItemReference.frameIndex = -1; - auto item = anm2.element_get(editItemReference); - auto nulls = anm2.element_get(ElementType::NULLS); - auto selectedNull = editItemType == ItemType::NULL_ && nulls - ? child_id_get(*nulls, ElementType::NULL_ELEMENT, editReference.itemID) - : nullptr; + auto frame = model.frame_get(editReference); + auto item = model.track_get(editReference); + auto selectedNull = + editItemType == ItemType::NULL_ ? model::item_get(model.content.nulls, editReference.itemID) : nullptr; bool isSelectedNullRect = selectedNull && selectedNull->isShowRect; - auto null_rect_top_left = [](const Element& frame) { return frame.position - (frame.scale * 0.5f); }; + auto null_rect_top_left = [](const model::Frame& frame) { return frame.position - (frame.scale * 0.5f); }; if (isMouseMiddleDown) useTool = tool::PAN; if (tool == tool::MOVE && isMouseRightDown) useTool = tool::SCALE; @@ -1330,9 +1279,8 @@ namespace anm2ed::imgui for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference); - if (!item) continue; - frames_change(*item, frameChange, itemType, changeType, itemFrames); + if (auto item = document.model.track_edit(itemReference)) + model::frames_change(*item, frameChange, itemType, changeType, itemFrames); } }}); }; diff --git a/src/imgui/window/animations.cpp b/src/imgui/window/animations.cpp index e0bd289..66d09ed 100644 --- a/src/imgui/window/animations.cpp +++ b/src/imgui/window/animations.cpp @@ -50,19 +50,31 @@ namespace anm2ed::imgui bool isDeleteAnimationsAfter{}; }; - int animation_group_child_insert_index_get(const Element& animations, int groupId, AnimationDropZone dropZone) + // Calls back for each top-level entry: (animation index, animation) for loose animations, (index, group) for groups. + template void animation_entries_each(const model::Model& model, Callback&& callback) { - auto group = std::ranges::find_if(animations.children, [&](const Element& item) - { return item.type == ElementType::GROUP && item.id == groupId; }); - if (group == animations.children.end()) return (int)animations.children.size(); - auto groupChildIndex = (int)(group - animations.children.begin()); - if (dropZone != AnimationDropZone::INSIDE) return groupChildIndex + (dropZone == AnimationDropZone::AFTER); + int index{}; + for (const auto& entry : model.animations.entries) + if (auto animation = std::get_if>(&entry)) + callback(index++, animation->get(), (const model::AnimationGroup*)nullptr); + else + { + auto& group = std::get(entry); + callback(index, (const model::Animation*)nullptr, &group); + index += (int)group.animations.size(); + } + } - auto insertIndex = groupChildIndex + 1; - for (int i = 0; i < (int)animations.children.size(); ++i) - if (animations.children[i].type == ElementType::ANIMATION && animations.children[i].groupId == groupId) - insertIndex = i + 1; - return insertIndex; + // The flat index of a group's first animation. + int animation_group_first_index_get(const model::Model& model, int groupId) + { + int first{-1}; + animation_entries_each(model, + [&](int index, auto*, const model::AnimationGroup* group) + { + if (group && group->id == groupId) first = index; + }); + return first; } // The list draws from Storage/Window mirrors of the document Selection: loaded each frame, written back on change. @@ -72,9 +84,9 @@ namespace anm2ed::imgui document.animations_selected_set(indices); auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; groupUids.clear(); - if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) - for (const auto& item : animations->children) - if (item.type == ElementType::GROUP && groupIds.contains(item.id)) groupUids.insert(item.uid); + for (const auto& entry : document.model.animations.entries) + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) + groupUids.insert(group->uid); document.animation.selection = indices; window.selection = groupIds; } @@ -84,53 +96,40 @@ namespace anm2ed::imgui document.animation.selection = document.animations_selected_get(); window.selection.clear(); auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; - if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) - for (const auto& item : animations->children) - if (item.type == ElementType::GROUP && groupUids.contains(item.uid)) window.selection.insert(item.id); - } - - bool is_animation_grouped(const std::set& groupIds, const Element& animation) - { - return animation.groupId != -1 && groupIds.contains(animation.groupId); + for (const auto& entry : document.model.animations.entries) + if (auto group = std::get_if(&entry); group && groupUids.contains(group->uid)) + window.selection.insert(group->id); } std::set animation_selected_indices_get(Document& document, const Window& window) { std::set result(document.animation.selection.begin(), document.animation.selection.end()); - if (auto animations = document.anm2.element_get(ElementType::ANIMATIONS)) - for (auto groupId : window.selection) - result.merge(edit::animation_group_indices_get(*animations, groupId)); + for (auto groupId : window.selection) + result.merge(edit::animation_group_indices_get(document.model, groupId)); return result; } std::vector animation_groupable_indices_get(Document& document) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); auto& selection = document.animation.selection; - if (!animations || selection.empty()) return {}; - - auto groupIds = edit::animation_group_ids_get(*animations); + if (selection.empty()) return {}; std::vector result{}; - int index{}; - for (const auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) - { - if (selection.contains(index) && is_animation_grouped(groupIds, animation)) return {}; - if (selection.contains(index)) result.push_back(index); - ++index; - } - return result.size() == selection.size() ? result : std::vector{}; + for (auto index : selection) + { + if (!document.model.animation_get(index) || document.model.animation_group_id_get(index) != -1) return {}; + result.push_back(index); + } + return result; } std::set animation_merge_indices_get(Document& document, const std::set& keys, int reference) { std::set result{}; - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); for (auto key : keys) if (!is_window_group_key(key)) result.insert(key); - else if (animations) - result.merge(edit::animation_group_indices_get(*animations, window_group_id_from_key_get(key))); + else + result.merge(edit::animation_group_indices_get(document.model, window_group_id_from_key_get(key))); result.erase(reference); return result; } @@ -147,7 +146,7 @@ namespace anm2ed::imgui StringType label) { document.edit_apply(label, - [&](Anm2& anm2) + [&](model::Model& anm2) { animation_overlay_reset(document, indices); animations_selection_set(window, document, {}, {}); @@ -166,17 +165,15 @@ namespace anm2ed::imgui std::string animation_clipboard_text_get(Document& document, const Window& window) { std::string clipboardText{}; - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return clipboardText; - int animationIndex{}; - for (const auto& item : animations->children) + auto& model = document.model; + for (const auto& entry : model.animations.entries) + if (auto group = std::get_if(&entry); group && window.selection.contains(group->id)) + clipboardText += model::animation_group_to_string(*group); + for (int i = 0; i < model.animations_count_get(); ++i) { - if (item.type == ElementType::GROUP && window.selection.contains(item.id)) - clipboardText += element_to_string(item); - if (item.type != ElementType::ANIMATION) continue; - if (document.animation.selection.contains(animationIndex) || window.selection.contains(item.groupId)) - clipboardText += element_to_string(item); - ++animationIndex; + auto groupId = model.animation_group_id_get(i); + if (document.animation.selection.contains(i) || window.selection.contains(groupId)) + clipboardText += model::animation_to_string(*model.animation_get(i), groupId); } return clipboardText; } @@ -188,7 +185,7 @@ namespace anm2ed::imgui std::string errorString{}; auto uids = document.edit_apply( edit, - [&](Anm2& anm2) + [&](model::Model& anm2) { auto uids = edit::animations_paste(anm2, text, start, targetGroupId, groupIds, &errorString); if (uids.empty()) return uids; @@ -219,8 +216,7 @@ namespace anm2ed::imgui if (options.selection.empty()) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto count = animations ? animations_count_get(*animations) : 0; + auto count = document.model.animations_count_get(); if (sources.empty()) return -1; if (sources.size() == 1 && ungroupIds.empty() && *sources.begin() != count - 1) sources.insert(*sources.begin() + 1); @@ -232,7 +228,7 @@ namespace anm2ed::imgui int merged{-1}; document.edit_apply(EDIT_MERGE_ANIMATIONS, - [&](Anm2& anm2) + [&](model::Model& anm2) { animation_overlay_reset(document, sources); auto uids = edit::animations_merge(anm2, target, sources, type, isDeleteAfter, ungroupIds); @@ -255,34 +251,26 @@ namespace anm2ed::imgui return AnimationDropZone::INSIDE; } - void animation_items_move(Window& window, Document& document, Anm2& anm2, - const std::vector& items, int targetChildIndex, int targetGroupId) - { - std::set indices{}; - std::set groupIds{}; - for (auto item : items) - (item.type == AnimationDragDropType::GROUP ? groupIds : indices).insert(item.id); - auto uids = edit::animations_move(anm2, indices, groupIds, targetChildIndex, targetGroupId); - if (uids.empty() && groupIds.empty()) return; - animations_selection_set(window, document, animation_indices_get(document, uids), groupIds); - } - void animation_move_command_push(Window& window, Manager& manager, std::vector items, - int targetGroupId, std::function target_child_index_get) + edit::AnimationTarget target) { if (items.empty()) return; - manager.command_push( - {manager.selected, [&window, items, targetGroupId, target_child_index_get](Manager&, Document& document) - { - auto animations = window_container_get(window, document); - if (!animations) return; - document.edit_apply(EDIT_MOVE_ANIMATIONS, - [&](Anm2& anm2) - { - animation_items_move(window, document, anm2, items, - target_child_index_get(*animations), targetGroupId); - }); - }}); + manager.command_push({manager.selected, [&window, items, target](Manager&, Document& document) + { + std::set indices{}; + std::set groupIds{}; + for (auto item : items) + (item.type == AnimationDragDropType::GROUP ? groupIds : indices).insert(item.id); + document.edit_apply(EDIT_MOVE_ANIMATIONS, + [&](model::Model& model) + { + auto uids = edit::animations_move(model, indices, groupIds, target); + if (uids.empty() && groupIds.empty()) return; + animations_selection_set(window, document, + animation_indices_get(document, uids), + groupIds); + }); + }}); } void animation_drag_drop_source_update(Document& document, const Window& window, AnimationDragDropItem fallback) @@ -291,17 +279,16 @@ namespace anm2ed::imgui static std::vector items{}; items.clear(); - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); auto isFallbackSelected = fallback.type == AnimationDragDropType::GROUP ? window.selection.contains(fallback.id) : document.animation.selection.contains(fallback.id); - if (animations && isFallbackSelected) + if (isFallbackSelected) { - auto groupIds = edit::animation_group_ids_get(*animations); + auto groupIds = edit::animation_group_ids_get(document.model); for (auto groupId : window.selection) if (groupIds.contains(groupId)) items.push_back({AnimationDragDropType::GROUP, groupId}); for (auto animationIndex : document.animation.selection) - if (animations_child_index_get(*animations, animationIndex) != -1) + if (document.model.animation_get(animationIndex)) items.push_back({AnimationDragDropType::ANIMATION, animationIndex}); } if (items.empty() && fallback.id >= 0) items.push_back(fallback); @@ -336,20 +323,15 @@ namespace anm2ed::imgui isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); if (isDelivered) - { - auto targetDropZone = - dropZone == AnimationDropZone::INSIDE && !isDropIntoGroup ? AnimationDropZone::AFTER : dropZone; animation_move_command_push( - window, manager, items, isDropIntoGroup ? groupId : -1, [groupId, targetDropZone](const Element& animations) - { return animation_group_child_insert_index_get(animations, groupId, targetDropZone); }); - } + window, manager, items, + {.groupId = groupId, .isAfter = dropZone != AnimationDropZone::BEFORE, .isInto = isDropIntoGroup}); } ImGui::EndDragDropTarget(); return isDelivered; } - bool animation_row_drag_drop_update(Window& window, Manager& manager, Document& document, const Element& animation, - int index) + bool animation_row_drag_drop_update(Window& window, Manager& manager, Document& document, int index, int) { animation_drag_drop_source_update(document, window, {AnimationDragDropType::ANIMATION, index}); if (!ImGui::BeginDragDropTarget()) return false; @@ -364,9 +346,7 @@ namespace anm2ed::imgui drop_line_draw(ImGui::GetWindowDrawList(), itemMin, itemMax, isDropAfter); isDelivered = ImGui::GetDragDropPayload()->IsDelivery(); if (isDelivered) - animation_move_command_push(window, manager, items, animation.groupId, - [targetIndex = index + (isDropAfter ? 1 : 0)](const Element& animations) - { return animations_child_insert_index_get(animations, targetIndex); }); + animation_move_command_push(window, manager, items, {.animationIndex = index, .isAfter = isDropAfter}); } ImGui::EndDragDropTarget(); return isDelivered; @@ -377,25 +357,25 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [groupId, edit, name, isExpanded](Manager&, Document& document) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto group = animations ? child_id_get(*animations, ElementType::GROUP, groupId) : nullptr; + auto first = animation_group_first_index_get(document.model, groupId); + auto group = document.model.animation_group_get(first); if (!group || (name.value_or(group->name) == group->name && isExpanded.value_or(group->isExpanded) == group->isExpanded)) return; document.edit_apply(edit, - [&](Anm2&) + [&](model::Model& model) { + auto group = model.animation_group_edit(first); group->name = name.value_or(group->name); group->isExpanded = isExpanded.value_or(group->isExpanded); }); }}); } - void animation_group_draw(Window& window, Manager& manager, Resources& resources, Document& document, Element& group, - int arrowSelectionId, bool& isRowsDone) + void animation_group_draw(Window& window, Manager& manager, Resources& resources, Document& document, + const model::AnimationGroup& group, int firstIndex, int arrowSelectionId, bool& isRowsDone) { auto& groupSelection = window.selection; - auto container = window_container_get(window, document); auto renameKey = window_group_key_get(group.id); auto isRenaming = window.renameId == renameKey; if (window.renameQueued == renameKey) @@ -407,10 +387,11 @@ namespace anm2ed::imgui ImGui::PushID("Animation Group"); ImGui::PushID(group.id); ImGui::SetNextItemOpen(group.isExpanded, ImGuiCond_Always); + auto groupName = group.name; auto tree = tree_node_input_text(group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name, std::format("###Document #{} Animation Group #{}", manager.selected, group.id), - isRenaming ? window.renameText : group.name, groupSelection.contains(group.id), + isRenaming ? window.renameText : groupName, groupSelection.contains(group.id), ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth, window.renameState); auto itemMin = ImGui::GetItemRectMin(); auto itemMax = ImGui::GetItemRectMax(); @@ -455,15 +436,9 @@ namespace anm2ed::imgui if (tree.isOpen) { - int animationIndex{}; - for (auto& animation : container->children) - if (animation.type == ElementType::ANIMATION && !isRowsDone) - { - if (animation.groupId == group.id) - isRowsDone = window_row_draw(window, manager, resources, document, animation, animationIndex, - animationIndex, arrowSelectionId); - ++animationIndex; - } + for (int i = 0; i < (int)group.animations.size() && !isRowsDone; ++i) + isRowsDone = + window_row_draw(window, manager, resources, document, firstIndex + i, firstIndex + i, arrowSelectionId); ImGui::TreePop(); } ImGui::PopID(); @@ -475,7 +450,6 @@ namespace anm2ed::imgui Window window{}; window.title = LABEL_ANIMATIONS_WINDOW; window.isOpen = &Settings::windowIsAnimations; - window.containerType = ElementType::ANIMATIONS; window.elementType = ElementType::ANIMATION; window.childLabel = "##Animations Child"; window.renameEdit = SNAPSHOT_RENAME_ANIMATION; @@ -493,12 +467,22 @@ namespace anm2ed::imgui {WINDOW_GROUP, [](Window&, Document& document) { return !animation_groupable_indices_get(document).empty(); }}}; window.popup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); window.storage_get = [](Document& document) -> Storage& { return document.animation; }; - window.element_get = [](Anm2& anm2, int index) { return anm2.element_get(ElementType::ANIMATION, index); }; - window.element_key_get = [](const Element&, int index) { return index; }; - window.row_font_get = [](Document& document, const Element& animation, int index) + window.name_get = [](Document& document, int index) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto isDefault = animations && animations->defaultAnimation == animation.name; + auto animation = document.model.animation_get(index); + return animation ? animation->name : std::string{}; + }; + window.rename_apply = [](Document&, model::Model& model, int index, const std::string& name) + { + auto animation = model.animation_edit(index); + if (!animation) return; + if (model.animations_count_get() == 1) model.animations.defaultAnimation = name; + animation->name = name; + }; + window.row_font_get = [](Document& document, int index) + { + auto animation = document.model.animation_get(index); + auto isDefault = animation && document.model.animations.defaultAnimation == animation->name; auto isReferenced = document.reference_get().animationIndex == index; return isDefault && isReferenced ? font::BOLD_ITALICS : isDefault ? font::BOLD @@ -512,16 +496,11 @@ namespace anm2ed::imgui document.reference_set({index}); document.frame_references_clear(); }; - window.rename_finish = [](Document& document, Element& animation, int, int count) + window.tooltip_draw = [](Document& document, Resources& resources, int index) { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - if (animations && count == 1) animations->defaultAnimation = animation.name; - }; - window.tooltip_draw = [](Document& document, Resources& resources, const Element& animation) - { - auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto& animation = *document.model.animation_get(index); window_tooltip_name_draw(resources, animation.name); - if (animations && animations->defaultAnimation == animation.name) + if (document.model.animations.defaultAnimation == animation.name) { ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); @@ -536,22 +515,22 @@ namespace anm2ed::imgui window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard, Document& document) { - auto container = window_container_get(window, document); - if (!container) return; - auto groupIds = edit::animation_group_ids_get(*container); + auto& model = document.model; + auto groupIds = edit::animation_group_ids_get(model); animations_selection_load(window, document); std::vector visibleIds{}; window.order.clear(); - int animationIndex{}; - for (auto& item : container->children) - { - if (item.type == ElementType::GROUP && item.isExpanded) - visibleIds.insert_range(visibleIds.end(), edit::animation_group_indices_get(*container, item.id)); - if (item.type != ElementType::ANIMATION) continue; - if (!is_animation_grouped(groupIds, item)) visibleIds.push_back(animationIndex); - window.order.push_back(animationIndex++); - } + for (int i = 0; i < model.animations_count_get(); ++i) + window.order.push_back(i); + animation_entries_each(model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (animation) visibleIds.push_back(index); + if (group && group->isExpanded) + for (int i = 0; i < (int)group->animations.size(); ++i) + visibleIds.push_back(index + i); + }); auto arrowSelectionId = window_selection_start(window, document, visibleIds); if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) @@ -561,18 +540,16 @@ namespace anm2ed::imgui } auto isRowsDone = false; - animationIndex = 0; - for (auto& item : container->children) - { - if (isRowsDone) break; - if (item.type == ElementType::GROUP) - animation_group_draw(window, manager, resources, document, item, arrowSelectionId, isRowsDone); - if (item.type != ElementType::ANIMATION) continue; - if (!is_animation_grouped(groupIds, item)) - isRowsDone = window_row_draw(window, manager, resources, document, item, animationIndex, animationIndex, - arrowSelectionId); - ++animationIndex; - } + animation_entries_each( + model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (isRowsDone) return; + if (group) + animation_group_draw(window, manager, resources, document, *group, index, arrowSelectionId, isRowsDone); + else if (animation) + isRowsDone = window_row_draw(window, manager, resources, document, index, index, arrowSelectionId); + }); window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); animations_selection_set(window, document, {document.animation.selection.begin(), document.animation.selection.end()}, @@ -581,26 +558,20 @@ namespace anm2ed::imgui window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& selection = document.animation.selection; - auto animations = window_container_get(window, document); - if (!animations) return; - - auto groupIds = edit::animation_group_ids_get(*animations); + auto& model = document.model; + auto groupIds = edit::animation_group_ids_get(model); auto targetGroupId = window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() : -1; - auto count = animations_count_get(*animations); + auto count = model.animations_count_get(); auto groupIndices = - targetGroupId != -1 ? edit::animation_group_indices_get(*animations, targetGroupId) : std::set{}; + targetGroupId != -1 ? edit::animation_group_indices_get(model, targetGroupId) : std::set{}; auto index = !selection.empty() ? std::min(*selection.rbegin() + 1, count) : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) : count; - auto selected = - selection.empty() ? nullptr : document.anm2.element_get(ElementType::ANIMATION, *selection.rbegin()); - auto groupId = selection.empty() ? targetGroupId - : selected && groupIds.contains(selected->groupId) ? selected->groupId - : -1; + auto groupId = selection.empty() ? targetGroupId : model.animation_group_id_get(*selection.rbegin()); document.edit_apply(EDIT_ADD_ANIMATION, - [&](Anm2& anm2) + [&](model::Model& anm2) { auto uids = edit::animation_add(anm2, index, groupId, document.reference_get().animationIndex, @@ -632,28 +603,26 @@ namespace anm2ed::imgui }; window.duplicate = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto animations = window_container_get(window, document); auto text = animation_clipboard_text_get(document, window); - if (!animations || text.empty()) return; + if (text.empty()) return; auto selectedIndices = animation_selected_indices_get(document, window); - auto count = animations_count_get(*animations); + auto count = document.model.animations_count_get(); animations_insert(window, document, text, selectedIndices.empty() ? count : std::min(*selectedIndices.rbegin() + 1, count), -1, EDIT_DUPLICATE_ANIMATIONS); }; window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { - auto animations = window_container_get(window, document); - if (clipboard.is_empty() || !animations) return; + if (clipboard.is_empty()) return; auto& selection = document.animation.selection; - auto count = animations_count_get(*animations); - auto groupIds = edit::animation_group_ids_get(*animations); + auto count = document.model.animations_count_get(); + auto groupIds = edit::animation_group_ids_get(document.model); auto targetGroupId = selection.empty() && window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() : -1; auto groupIndices = - targetGroupId != -1 ? edit::animation_group_indices_get(*animations, targetGroupId) : std::set{}; + targetGroupId != -1 ? edit::animation_group_indices_get(document.model, targetGroupId) : std::set{}; auto start = !selection.empty() ? *selection.rbegin() + 1 : !groupIndices.empty() ? std::min(*groupIndices.rbegin() + 1, count) : count; @@ -687,13 +656,13 @@ namespace anm2ed::imgui window.group = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto targetIndices = animation_groupable_indices_get(document); - auto animations = window_container_get(window, document); - if (targetIndices.empty() || !animations) return; + if (targetIndices.empty()) return; std::set targetSet(targetIndices.begin(), targetIndices.end()); - auto groupId = element_child_next_id_get(*animations, ElementType::GROUP); + auto groupIds = edit::animation_group_ids_get(document.model); + auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; document.edit_apply(EDIT_GROUP_ITEMS, - [&](Anm2& anm2) + [&](model::Model& anm2) { auto uids = edit::animations_group(anm2, targetSet, localize.get(TEXT_NEW_GROUP)); animations_selection_set(window, document, targetSet, {groupId}); @@ -702,12 +671,13 @@ namespace anm2ed::imgui return uids; }); }; - window.default_set = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.default_set = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { - auto animations = window_container_get(window, document); - auto animation = document.anm2.element_get(ElementType::ANIMATION, *document.animation.selection.begin()); - if (!animations || !animation) return; - document.edit_apply(EDIT_DEFAULT_ANIMATION, [&](Anm2&) { animations->defaultAnimation = animation->name; }); + auto animation = document.model.animation_get(*document.animation.selection.begin()); + if (!animation) return; + auto name = animation->name; + document.edit_apply(EDIT_DEFAULT_ANIMATION, + [&](model::Model& model) { model.animations.defaultAnimation = name; }); }; window.body_update = [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) @@ -724,37 +694,24 @@ namespace anm2ed::imgui std::string label{}; }; std::vector candidates{}; - auto animations = window_container_get(window, document); - auto groupIds = animations ? edit::animation_group_ids_get(*animations) : std::set{}; - static const Element EMPTY{}; - auto candidate_animation_push = [&](const Element& animation, int animationIndex, bool isGrouped) + auto candidate_animation_push = [&](const model::Animation& animation, int animationIndex, bool isGrouped) { if (animationIndex != mergeReference) candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); }; - int animationIndex{}; - for (const auto& item : (animations ? *animations : EMPTY).children) - { - if (item.type == ElementType::GROUP) - { - auto groupIndices = edit::animation_group_indices_get(*animations, item.id); - groupIndices.erase(mergeReference); - if (groupIndices.empty()) continue; - candidates.push_back({window_group_key_get(item.id), - item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name}); - int groupAnimationIndex{}; - for (const auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) - { - if (animation.groupId == item.id) candidate_animation_push(animation, groupAnimationIndex, true); - ++groupAnimationIndex; - } - } - if (item.type != ElementType::ANIMATION) continue; - if (!is_animation_grouped(groupIds, item)) candidate_animation_push(item, animationIndex, false); - ++animationIndex; - } + animation_entries_each(document.model, + [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + { + if (animation) return candidate_animation_push(*animation, index, false); + auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; + if (group->animations.empty() || isReferenceOnly) return; + candidates.push_back( + {window_group_key_get(group->id), + group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name}); + for (int i = 0; i < (int)group->animations.size(); ++i) + candidate_animation_push(*group->animations[i], index + i, true); + }); auto footerSize = footer_size_get(); auto optionsSize = child_size_get(MERGE_OPTIONS_ROWS); @@ -827,8 +784,7 @@ namespace anm2ed::imgui { auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], shortcut::GLOBAL); auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], shortcut::GLOBAL); - auto animations = window_container_get(window, document); - auto count = animations ? animations_count_get(*animations) : 0; + auto count = document.model.animations_count_get(); if ((!isPrevious && !isNext) || count <= 0) return; auto reference = document.reference_get(); diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 8bc009a..a2d4c41 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -6,6 +6,7 @@ #include #include "math.hpp" +#include "model/frames.hpp" #include "strings.hpp" #include "types.hpp" #include "util/imgui/input.hpp" @@ -22,17 +23,17 @@ namespace anm2ed::imgui StringType label; StringType tooltip; StringType edit; - vec2 Element::* member; + vec2 model::Frame::* member; bool isRegionField; }; constexpr Vec2Field VEC2_FIELDS[] = { - {BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &Element::crop, true}, - {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &Element::size, true}, - {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &Element::position, false}, - {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &Element::pivot, true}, - {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &Element::scale, false}, - {BASIC_SHEAR, TOOLTIP_SHEAR, EDIT_FRAME_SHEAR, &Element::shear, false}}; + {BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &model::Frame::crop, true}, + {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &model::Frame::size, true}, + {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &model::Frame::position, false}, + {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &model::Frame::pivot, true}, + {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &model::Frame::scale, false}, + {BASIC_SHEAR, TOOLTIP_SHEAR, EDIT_FRAME_SHEAR, &model::Frame::shear, false}}; struct FlipButton { @@ -59,26 +60,23 @@ namespace anm2ed::imgui if (ImGui::Begin(windowLabel.c_str(), &settings.windowIsFrameProperties)) { - auto& anm2 = document.anm2; + auto& model = document.model; auto reference = document.reference_get(); auto& type = reference.itemType; - auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; + auto frame = model.frame_get(reference); auto frame_edit = [&](edit_state::Type state, StringType message, auto behavior) { if (state == edit_state::NONE) return; - manager.command_push( - {manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable - { - auto frame = queuedReference.frameIndex < 0 ? nullptr : document.anm2.element_get(queuedReference); - if (!frame) return; - auto item = document.anm2.element_get(Reference{queuedReference.animationIndex, queuedReference.itemType, - queuedReference.itemID, -1, queuedReference.groupType, - queuedReference.groupId}); - if (state == edit_state::START || state == edit_state::COMPLETE) document.edit_begin(message); - behavior(document, *frame, item, queuedReference); - if (state == edit_state::END || state == edit_state::COMPLETE) document.change(); - }}); + manager.command_push({manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable + { + if (!document.model.frame_get(queuedReference)) return; + if (state == edit_state::START || state == edit_state::COMPLETE) + document.edit_begin(message); + auto item = document.model.track_edit(queuedReference); + behavior(document, item->frames[queuedReference.frameIndex], item, queuedReference); + if (state == edit_state::END || state == edit_state::COMPLETE) document.change(); + }}); }; auto regions = document.layer_regions_get(type == LAYER ? reference.itemID : -1); @@ -107,9 +105,9 @@ namespace anm2ed::imgui } else if (!isMultiFrameSelection) { - auto useFrame = frame ? *frame : Element(); + auto useFrame = frame ? *frame : model::Frame(); auto displayFrame = frame && type == LAYER && reference.itemID != -1 - ? anm2.frame_effective(reference.itemID, *frame) + ? model.frame_effective(reference.itemID, *frame) : useFrame; ImGui::BeginDisabled(!frame); @@ -122,7 +120,8 @@ namespace anm2ed::imgui { auto eventId = useFrame.eventId; frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_EVENT, - [eventId](Document&, Element& frame, Element*, const Reference&) { frame.eventId = eventId; }); + [eventId](Document&, model::Frame& frame, model::Track*, const Reference&) + { frame.eventId = eventId; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_EVENT)); @@ -133,13 +132,13 @@ namespace anm2ed::imgui { auto atFrame = useFrame.atFrame; frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_AT_FRAME, - [atFrame](Document& document, Element& frame, Element* item, const Reference&) + [atFrame](Document& document, model::Frame& frame, model::Track* item, const Reference&) { frame.atFrame = atFrame; if (!item) return; - frames_sort_by_at_frame(*item); + model::frames_sort_by_at_frame(*item); auto reference = document.reference_get(); - reference.frameIndex = frame_index_from_at_frame_get(*item, atFrame); + reference.frameIndex = model::frame_index_from_at_frame_get(*item, atFrame); document.reference_set(reference); document.frame_references_set({reference}); }); @@ -151,7 +150,7 @@ namespace anm2ed::imgui { auto isVisible = useFrame.isVisible; frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_VISIBILITY, - [isVisible](Document&, Element& frame, Element*, const Reference&) + [isVisible](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_VISIBILITY)); @@ -174,7 +173,7 @@ namespace anm2ed::imgui auto soundIndex = (std::size_t)i; auto soundId = id; frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_SOUND, - [soundIndex, soundId](Document&, Element& frame, Element*, const Reference&) + [soundIndex, soundId](Document&, model::Frame& frame, model::Track*, const Reference&) { if (soundIndex < frame.soundIds.size()) frame.soundIds[soundIndex] = soundId; }); @@ -190,7 +189,8 @@ namespace anm2ed::imgui if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && frame) frame_edit(edit_state::COMPLETE, EDIT_ADD_TRIGGER_SOUND, - [](Document&, Element& frame, Element*, const Reference&) { frame.soundIds.push_back(-1); }); + [](Document&, model::Frame& frame, model::Track*, const Reference&) + { frame.soundIds.push_back(-1); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_TRIGGER_SOUND)); ImGui::SameLine(); @@ -198,7 +198,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(useFrame.soundIds.empty()); if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize) && frame) frame_edit(edit_state::COMPLETE, EDIT_REMOVE_TRIGGER_SOUND, - [](Document&, Element& frame, Element*, const Reference&) + [](Document&, model::Frame& frame, model::Track*, const Reference&) { if (!frame.soundIds.empty()) frame.soundIds.pop_back(); }); @@ -218,7 +218,7 @@ namespace anm2ed::imgui drag_float2_persistent(localize.get(field.label), frame ? &value : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? vec2_format_get(source.*field.member) : ""); frame_edit(state, field.edit, - [value, member = field.member](Document&, Element& frame, Element*, const Reference&) + [value, member = field.member](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.*member = value; }); ImGui::SetItemTooltip("%s", localize.get(field.tooltip)); ImGui::EndDisabled(); @@ -228,7 +228,7 @@ namespace anm2ed::imgui drag_float_persistent(localize.get(BASIC_ROTATION), frame ? &useFrame.rotation : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? float_format_get(frame->rotation) : ""); frame_edit(rotationEdit, EDIT_FRAME_ROTATION, - [rotation = useFrame.rotation](Document&, Element& frame, Element*, const Reference&) + [rotation = useFrame.rotation](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.rotation = rotation; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROTATION)); @@ -239,7 +239,7 @@ namespace anm2ed::imgui { auto duration = useFrame.duration; frame_edit(edit_state::COMPLETE, EDIT_FRAME_DURATION, - [duration](Document&, Element& frame, Element*, const Reference&) + [duration](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.duration = duration; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DURATION)); @@ -247,15 +247,15 @@ namespace anm2ed::imgui auto tintEdit = color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value()); frame_edit(tintEdit, EDIT_FRAME_TINT, - [tint = useFrame.tint](Document&, Element& frame, Element*, const Reference&) + [tint = useFrame.tint](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.tint = tint; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TINT)); auto colorOffsetEdit = color_edit3_persistent(localize.get(BASIC_COLOR_OFFSET), frame ? &useFrame.colorOffset : &dummy_value()); frame_edit(colorOffsetEdit, EDIT_FRAME_COLOR_OFFSET, - [colorOffset = useFrame.colorOffset](Document&, Element& frame, Element*, const Reference&) - { frame.colorOffset = colorOffset; }); + [colorOffset = useFrame.colorOffset](Document&, model::Frame& frame, model::Track*, + const Reference&) { frame.colorOffset = colorOffset; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); ImGui::BeginDisabled(type != LAYER); @@ -265,10 +265,10 @@ namespace anm2ed::imgui { auto regionId = useFrame.regionId; frame_edit(edit_state::COMPLETE, EDIT_SET_REGION_PROPERTIES, - [regionId](Document& document, Element& frame, Element*, const Reference& reference) + [regionId](Document& document, model::Frame& frame, model::Track*, const Reference& reference) { frame.regionId = regionId; - auto effectiveFrame = document.anm2.frame_effective(reference.itemID, frame); + auto effectiveFrame = document.model.frame_effective(reference.itemID, frame); frame.crop = effectiveFrame.crop; frame.size = effectiveFrame.size; frame.pivot = effectiveFrame.pivot; @@ -282,7 +282,7 @@ namespace anm2ed::imgui (int)interpolationLabels.size()) && frame) frame_edit(edit_state::COMPLETE, EDIT_FRAME_INTERPOLATION, - [interpolationValue](Document&, Element& frame, Element*, const Reference&) + [interpolationValue](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.interpolation = static_cast(interpolationValue); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); @@ -293,7 +293,7 @@ namespace anm2ed::imgui { auto shaderId = useFrame.shaderId; frame_edit(edit_state::COMPLETE, EDIT_FRAME_SHADER, - [shaderId](Document&, Element& frame, Element*, const Reference&) + [shaderId](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.shaderId = shaderId; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_SHADER)); @@ -304,7 +304,7 @@ namespace anm2ed::imgui { auto isVisible = useFrame.isVisible; frame_edit(edit_state::COMPLETE, EDIT_FRAME_VISIBILITY, - [isVisible](Document&, Element& frame, Element*, const Reference&) + [isVisible](Document&, model::Frame& frame, model::Track*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); @@ -316,8 +316,8 @@ namespace anm2ed::imgui if (axis > 0) ImGui::SameLine(); if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) frame_edit(edit_state::COMPLETE, FLIP_BUTTONS[axis].edit, - [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, Element& frame, - Element*, const Reference&) + [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, model::Frame& frame, + model::Track*, const Reference&) { frame.scale[axis] = -frame.scale[axis]; if (isPositionFlipped) frame.position[axis] = -frame.position[axis]; diff --git a/src/imgui/window/items.cpp b/src/imgui/window/items.cpp index 841ae15..79ff1db 100644 --- a/src/imgui/window/items.cpp +++ b/src/imgui/window/items.cpp @@ -11,16 +11,27 @@ namespace anm2ed::imgui { constexpr int ITEM_PROPERTIES_ROWS = 2; - void item_tooltip_draw(Resources& resources, const Element& element) + std::vector* layers_get(Document&, model::Model& model) { return &model.content.layers; } + std::vector* nulls_get(Document&, model::Model& model) { return &model.content.nulls; } + + void item_tooltip_draw(Resources& resources, const std::string& name, int id) { - window_tooltip_name_draw(resources, element.name); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(element.id)).c_str()); + window_tooltip_name_draw(resources, name); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); } - void item_properties_popup_update(Window& window, Manager& manager, Document& document, StringType nameTooltip, - const std::function& fields_draw) + void item_tooltip_set(Window& window) { - auto& popup = manager.itemPropertiesPopups[track_container_get(window.elementType) - TRACK_CONTAINERS]; + window.tooltip_draw = [name_get = window.name_get](Document& document, Resources& resources, int id) + { item_tooltip_draw(resources, name_get(document, id), id); }; + } + + template + void item_properties_popup_update(Window& window, Manager& manager, Document& document, StringType nameTooltip, + std::function*(Document&, model::Model&)> items_get, + const std::function& fields_draw) + { + auto& popup = manager.itemPropertiesPopups[window.elementType == ElementType::LAYER_ELEMENT ? 0 : 1]; auto reference = window.storage_get(document).reference; popup.trigger(); @@ -36,7 +47,13 @@ namespace anm2ed::imgui ImGui::EndChild(); auto result = window_popup_buttons_draw(manager, localize.get(reference == -1 ? BASIC_ADD : BASIC_CONFIRM)); - if (result == PopupButton::CONFIRM) window_element_apply_push(window, manager, manager.itemEdit, reference); + if (result == PopupButton::CONFIRM) + { + Item item{.name = manager.itemEdit.name}; + if constexpr (requires { item.spritesheetId; }) item.spritesheetId = manager.itemEdit.spritesheetId; + if constexpr (requires { item.isShowRect; }) item.isShowRect = manager.itemEdit.isShowRect; + window_item_apply_push(window, manager, item, reference, items_get); + } if (result != PopupButton::NONE) popup.close(); ImGui::EndPopup(); } @@ -49,14 +66,11 @@ namespace anm2ed::imgui Window window{}; window.title = title; window.isOpen = isOpen; - window.containerType = ELEMENT_CONTAINERS[(int)elementType]; window.elementType = elementType; window.childLabel = childLabel; window.tooltips = {{WINDOW_ADD, addTooltip}, {WINDOW_REMOVE_UNUSED, removeUnusedTooltip}}; window.footer = {{WINDOW_ADD, WINDOW_REMOVE_UNUSED}}; window.flags = WINDOW_ADD | WINDOW_REMOVE_UNUSED | WINDOW_COPY | WINDOW_PASTE; - window.tooltip_draw = [](Document&, Resources& resources, const Element& element) - { item_tooltip_draw(resources, element); }; window.properties_open = [elementType](Manager& manager, int id) { manager.item_properties_open(elementType, id); }; return window; } @@ -72,25 +86,30 @@ namespace anm2ed::imgui window.deserializeFailedToast = TOAST_DESERIALIZE_LAYERS_FAILED; window.flags |= WINDOW_PROPERTIES; window.storage_get = [](Document& document) -> Storage& { return document.layer; }; - window.row_label_get = [](Document&, const Element& layer) + window_items_bind(window, layers_get); + window.row_label_get = [](Document& document, int id) { - return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(layer.id, layer.name, layer.spritesheetId)); + auto layer = model::item_get(document.model.content.layers, id); + return std::vformat(localize.get(FORMAT_LAYER), + std::make_format_args(layer->id, layer->name, layer->spritesheetId)); }; - window.tooltip_draw = [](Document&, Resources& resources, const Element& layer) + window.tooltip_draw = [](Document& document, Resources& resources, int id) { - item_tooltip_draw(resources, layer); + auto layer = model::item_get(document.model.content.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()); + std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)).c_str()); }; window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) { - item_properties_popup_update(window, manager, document, TOOLTIP_ITEM_NAME, - [&](Element& layer) - { - combo_id_mapped(localize.get(LABEL_SPRITESHEET), &layer.spritesheetId, - document.spritesheet.ids, document.spritesheet.labels); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); - }); + item_properties_popup_update(window, manager, document, TOOLTIP_ITEM_NAME, layers_get, + [&](Manager::ItemEdit& layer) + { + combo_id_mapped(localize.get(LABEL_SPRITESHEET), + &layer.spritesheetId, document.spritesheet.ids, + document.spritesheet.labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LAYER_SPRITESHEET)); + }); }; return window; } @@ -106,16 +125,21 @@ namespace anm2ed::imgui window.deserializeFailedToast = TOAST_DESERIALIZE_NULLS_FAILED; window.flags |= WINDOW_PROPERTIES | WINDOW_REFERENCE_ITALIC; window.storage_get = [](Document& document) -> Storage& { return document.null; }; - window.row_label_get = [](Document&, const Element& null) - { return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(null.id, null.name)); }; + window_items_bind(window, nulls_get); + item_tooltip_set(window); + window.row_label_get = [name_get = window.name_get](Document& document, int id) + { + auto name = name_get(document, id); + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); + }; window.popup_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) { - item_properties_popup_update(window, manager, document, TOOLTIP_NULL_NAME, - [](Element& null) - { - ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); - }); + item_properties_popup_update(window, manager, document, TOOLTIP_NULL_NAME, nulls_get, + [](Manager::ItemEdit& null) + { + ImGui::Checkbox(localize.get(LABEL_RECT), &null.isShowRect); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NULL_RECT)); + }); }; return window; } @@ -132,17 +156,16 @@ namespace anm2ed::imgui window.flags |= WINDOW_RENAME; window.properties_open = {}; window.storage_get = [](Document& document) -> Storage& { return document.event; }; + window_items_bind(window, [](Document&, model::Model& model) { return &model.content.events; }); + item_tooltip_set(window); window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto event = element_make(ElementType::EVENT_ELEMENT); - event.name = localize.get(TEXT_NEW_EVENT); - auto events = window_container_get(window, document); - if (!events) return; document.edit_apply(window.addEdit, - [&](Anm2&) + [&](model::Model& model) { - event.id = element_child_next_id_get(*events, ElementType::EVENT_ELEMENT); - events->children.push_back(event); + auto& events = model.content.events; + auto& event = events.emplace_back(model::Event{.id = model::item_next_id_get(events), + .name = localize.get(TEXT_NEW_EVENT)}); auto& storage = window.storage_get(document); storage.selection = {event.id}; storage.reference = event.id; diff --git a/src/imgui/window/regions.cpp b/src/imgui/window/regions.cpp index 0b191fd..dc1bd10 100644 --- a/src/imgui/window/regions.cpp +++ b/src/imgui/window/regions.cpp @@ -39,34 +39,45 @@ namespace anm2ed::imgui bool isRemoveCurrent{}; }; - void region_pivot_apply(Element& region) + void region_pivot_apply(model::Region& region) { if (region.origin == Origin::TOP_LEFT) region.pivot = {}; if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; } - Element* region_spritesheet_get(Document& document) + std::vector* regions_get(Document& document, model::Model& model) { - return document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); + auto spritesheet = model::item_get(model.content.spritesheets, document.spritesheet.reference); + return spritesheet ? &spritesheet->regions : nullptr; + } + + const model::Spritesheet* region_spritesheet_get(Document& document) + { + return model::item_get(document.model.content.spritesheets, document.spritesheet.reference); + } + + const model::Region* region_get(Document& document, int id) + { + auto spritesheet = region_spritesheet_get(document); + return spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; } int region_insert_index_get(Document& document) { auto spritesheet = region_spritesheet_get(document); auto& storage = document.region; - int index = spritesheet ? (int)spritesheet->children.size() : 0; - for (int i = 0; spritesheet && i < (int)spritesheet->children.size(); i++) + int index = spritesheet ? (int)spritesheet->regions.size() : 0; + for (int i = 0; spritesheet && i < (int)spritesheet->regions.size(); i++) { - const auto& child = spritesheet->children[i]; - if (child.type == ElementType::REGION && - (storage.selection.contains(child.id) || (storage.selection.empty() && storage.reference == child.id))) - index = i + 1; + auto id = spritesheet->regions[i].id; + if (storage.selection.contains(id) || (storage.selection.empty() && storage.reference == id)) index = i + 1; } return index; } - WindowCardImage region_image_get(Document& document, Resources& resources, const Element& region) + WindowCardImage region_image_get(Document& document, Resources& resources, int id) { + auto& region = *region_get(document, id); auto texture = document.texture_get(document.spritesheet.reference); auto isValid = texture && texture->is_valid(); if (!isValid) return {.texture = &resources.icons[icon::NONE], .size = region.size}; @@ -77,7 +88,7 @@ namespace anm2ed::imgui .isValid = true}; } - bool region_pixels_get(const Element& region, const Image& texture, std::vector& pixels, ivec2& size) + bool region_pixels_get(const model::Region& region, const Image& texture, std::vector& pixels, ivec2& size) { auto minPoint = ivec2(glm::min(region.crop, region.crop + region.size)); size = ivec2(glm::max(region.crop, region.crop + region.size)) - minPoint; @@ -105,8 +116,8 @@ namespace anm2ed::imgui return false; } - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId); - auto region = spritesheet ? child_id_get(*spritesheet, ElementType::REGION, options.regionId) : nullptr; + auto spritesheet = model::item_get(document.model.content.spritesheets, options.spritesheetId); + auto region = spritesheet ? model::item_get(spritesheet->regions, options.regionId) : nullptr; auto texture = document.texture_get(options.spritesheetId); std::vector pixels{}; ivec2 exportSize{}; @@ -137,18 +148,17 @@ namespace anm2ed::imgui if (options.isMakeSpritesheet) { - auto spritesheets = document.anm2.element_get(ElementType::SPRITESHEETS); - auto exported = element_make(ElementType::SPRITESHEET); - exported.id = element_child_next_id_get(*spritesheets, ElementType::SPRITESHEET); - exported.path = outputPath; + auto& spritesheets = document.model.content.spritesheets; + model::Spritesheet exported{.id = model::item_next_id_get(spritesheets), .path = outputPath}; auto exportedRegion = sourceRegion; + exportedRegion.uid = util::uid_next(); exportedRegion.id = 0; exportedRegion.crop = {}; exportedRegion.size = vec2(exportSize); region_pivot_apply(exportedRegion); - exported.children.push_back(exportedRegion); - spritesheets->children.push_back(exported); + exported.regions.push_back(exportedRegion); + spritesheets.push_back(exported); document.texture_set(exported.id, Image(pixels.data(), exportSize)); document.texturePaths[exported.id] = exported.path; @@ -164,9 +174,9 @@ namespace anm2ed::imgui if (options.isRemoveCurrent) { - if (auto source = document.anm2.element_get(ElementType::SPRITESHEET, options.spritesheetId)) - element_child_id_erase(*source, ElementType::REGION, options.regionId); - document.anm2.region_frames_sync(true); + if (auto source = model::item_get(document.model.content.spritesheets, options.spritesheetId)) + std::erase_if(source->regions, [&](const model::Region& region) { return region.id == options.regionId; }); + edit::region_frames_sync(document.model); if (!options.isMakeSpritesheet) { document.region.reference = -1; @@ -180,13 +190,13 @@ namespace anm2ed::imgui return true; } - bool region_drag_drop_update(Window& window, Manager& manager, Document& document, const Element& region, int index) + bool region_drag_drop_update(Window& window, Manager& manager, Document& document, int id, int index) { auto& selection = document.region.selection; if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { - window.dragSelection = selection.contains(region.id) ? std::vector(selection.begin(), selection.end()) - : std::vector{region.id}; + window.dragSelection = + selection.contains(id) ? std::vector(selection.begin(), selection.end()) : std::vector{id}; ImGui::SetDragDropPayload(REGION_DRAG_DROP, window.dragSelection.data(), window.dragSelection.size() * sizeof(int)); ImGui::EndDragDropSource(); @@ -216,12 +226,12 @@ namespace anm2ed::imgui [&window, indices, movedIds = window.dragSelection, targetIndex = index + (isAfter ? 1 : 0), spritesheetId = document.spritesheet.reference](Manager&, Document& document) mutable { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) return; + if (!model::item_get(document.model.content.spritesheets, spritesheetId)) return; document.edit_apply(EDIT_MOVE_REGIONS, - [&](Anm2&) + [&](model::Model& model) { - vector::move_indices_to_position(spritesheet->children, indices, targetIndex); + auto spritesheet = model::item_get(model.content.spritesheets, spritesheetId); + vector::move_indices_to_position(spritesheet->regions, indices, targetIndex); document.region.selection = std::set(movedIds.begin(), movedIds.end()); }); }}); @@ -255,8 +265,7 @@ namespace anm2ed::imgui if (ImGui::BeginTooltip()) { for (auto regionId : window.dragSelection) - if (auto region = child_id_get(*spritesheet, ElementType::REGION, regionId)) - ImGui::TextUnformatted(region->name.c_str()); + if (auto region = model::item_get(spritesheet->regions, regionId)) ImGui::TextUnformatted(region->name.c_str()); ImGui::EndTooltip(); } ImGui::PopStyleVar(2); @@ -266,7 +275,7 @@ namespace anm2ed::imgui { auto& reference = document.region.reference; auto spritesheet = region_spritesheet_get(document); - auto target = spritesheet && reference != -1 ? child_id_get(*spritesheet, ElementType::REGION, reference) : nullptr; + auto target = spritesheet && reference != -1 ? model::item_get(spritesheet->regions, reference) : nullptr; window.popup.trigger(); if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) @@ -274,9 +283,9 @@ namespace anm2ed::imgui if (!spritesheet || (reference != -1 && !target)) window.popup.close(); if (window.popup.isJustOpened && !window.isPreserveEditElementOnOpen) - window.editElement = target ? *target : element_make(ElementType::REGION); + window.editRegion = target ? *target : model::Region{}; if (window.popup.isJustOpened) window.isPreserveEditElementOnOpen = false; - auto& region = window.editElement; + auto& region = window.editRegion; if (ImGui::BeginChild("##Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { @@ -305,7 +314,9 @@ namespace anm2ed::imgui ImGui::EndChild(); auto result = window_popup_buttons_draw(manager, localize.get(reference == -1 ? BASIC_ADD : BASIC_CONFIRM)); - if (result == PopupButton::CONFIRM) window_element_apply_push(window, manager, region, reference); + if (result == PopupButton::CONFIRM) + window_item_apply_push(window, manager, region, reference, regions_get, + region_insert_index_get(document)); if (result != PopupButton::NONE) window.popup.close(); ImGui::EndPopup(); } @@ -317,7 +328,7 @@ namespace anm2ed::imgui { auto spritesheet = region_spritesheet_get(document); auto regionId = window.editId != -1 ? window.editId : document.region.reference; - auto region = spritesheet && regionId != -1 ? child_id_get(*spritesheet, ElementType::REGION, regionId) : nullptr; + auto region = spritesheet && regionId != -1 ? model::item_get(spritesheet->regions, regionId) : nullptr; window.popup2.trigger(); if (ImGui::BeginPopupModal(window.popup2.label(), &window.popup2.isOpen, ImGuiWindowFlags_NoResize)) @@ -396,12 +407,10 @@ namespace anm2ed::imgui window.tooltips = {{WINDOW_ADD, TOOLTIP_ADD_REGION}, {WINDOW_REMOVE_UNUSED, TOOLTIP_REMOVE_UNUSED_REGIONS}, {WINDOW_TRIM, TOOLTIP_TRIM_REGIONS}}; - window.editElement = element_make(ElementType::REGION); window.popup = PopupHelper(LABEL_REGION_PROPERTIES, POPUP_SMALL_NO_HEIGHT); window.popup2 = PopupHelper(LABEL_EXPORT_REGION, POPUP_SMALL_NO_HEIGHT); window.storage_get = [](Document& document) -> Storage& { return document.region; }; - window.container_get = region_spritesheet_get; - window.insert_index_get = region_insert_index_get; + window_items_bind(window, regions_get); window.is_available = [](Window&, Document& document) { return region_spritesheet_get(document) != nullptr; }; window.card_image_get = region_image_get; window.row_drag_drop_update = region_drag_drop_update; @@ -411,10 +420,11 @@ namespace anm2ed::imgui document.reference_set({document.reference_get().animationIndex}); document.frame_references_clear(); }; - window.tooltip_draw = [](Document& document, Resources& resources, const Element& region) + window.tooltip_draw = [](Document& document, Resources& resources, int id) { + auto& region = *region_get(document, id); window_tooltip_image_draw( - region_image_get(document, resources, region), + region_image_get(document, resources, id), [&]() { window_tooltip_name_draw(resources, region.name); @@ -433,13 +443,13 @@ namespace anm2ed::imgui window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { document.region.reference = -1; - window.editElement = element_make(ElementType::REGION); + window.editRegion = {}; window.popup.open(); }; window.properties = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& selection = document.region.selection; - if (selection.size() != 1 || !window_element_get(window, document, *selection.begin())) return; + if (selection.size() != 1 || !region_get(document, *selection.begin())) return; document.region.reference = *selection.begin(); window.popup.open(); }; @@ -448,16 +458,16 @@ namespace anm2ed::imgui window.editId = *document.region.selection.begin(); window.popup2.open(); }; - window.remove_unused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.remove_unused = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { - document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, [&](Anm2& anm2) - { return edit::regions_remove_unused(anm2, document.spritesheet.reference); }); + document.edit_apply(EDIT_REMOVE_UNUSED_REGIONS, [&](model::Model& model) + { return edit::regions_remove_unused(model, document.spritesheet.reference); }); }; - window.trim = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.trim = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { auto& region = document.region; document.edit_apply(EDIT_TRIM_REGIONS, - [&](Anm2&) + [&](model::Model&) { if (!document.regions_trim(document.spritesheet.reference, region.selection)) return; if (region.reference != -1 && !region.selection.contains(region.reference)) @@ -470,15 +480,15 @@ namespace anm2ed::imgui { auto spritesheet = region_spritesheet_get(document); if (!spritesheet || clipboard.is_empty()) return; - auto maxIdBefore = element_child_max_id_get(*spritesheet, ElementType::REGION); + auto maxIdBefore = model::item_next_id_get(spritesheet->regions) - 1; std::string errorString{}; document.edit_apply(EDIT_PASTE_REGIONS, - [&](Anm2& anm2) + [&](model::Model& model) { - edit::regions_paste(anm2, document.spritesheet.reference, clipboard.get(), + edit::regions_paste(model, document.spritesheet.reference, clipboard.get(), region_insert_index_get(document), &errorString); auto target = region_spritesheet_get(document); - auto maxIdAfter = target ? element_child_max_id_get(*target, ElementType::REGION) : -1; + auto maxIdAfter = target ? model::item_next_id_get(target->regions) - 1 : -1; if (maxIdAfter <= maxIdBefore) return; window.newElementId = maxIdAfter; document.region.selection = {maxIdAfter}; @@ -489,7 +499,7 @@ namespace anm2ed::imgui window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard, Document& document) { - window_cards_draw(window, manager, settings, resources, clipboard, document, region_spritesheet_get(document)); + window_cards_draw(window, manager, settings, resources, clipboard, document); region_drag_tooltip_update(window, document); }; window.popup_update = @@ -499,7 +509,7 @@ namespace anm2ed::imgui { document.spritesheet.reference = manager.makeRegionSpritesheetId; document.region.reference = -1; - window.editElement = manager.makeRegion; + window.editRegion = manager.makeRegion; window.isPreserveEditElementOnOpen = true; window.popup.open(); manager.isMakeRegionRequested = false; diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index a3abf6c..ac5e4bc 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -42,7 +42,7 @@ namespace anm2ed::imgui return document.directory_get() / loadPath; } - bool is_shader_reload_needed(Document& document, Element* shader) + bool is_shader_reload_needed(Document& document, model::Shader* shader) { if (!shader || shader->fragment.empty()) return false; if (!document.shader_get(shader->id)) return true; @@ -52,10 +52,9 @@ namespace anm2ed::imgui document.shaderFragmentPaths.at(shader->id) != shader->fragment; } - Element* shader_element_get(Document& document, int id) + model::Shader* shader_element_get(Document& document, int id) { - auto shaders = document.anm2.element_get(ElementType::SHADERS); - return shaders ? child_id_get(*shaders, ElementType::SHADER, id) : nullptr; + return model::item_get(document.model.content.shaders, id); } std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) @@ -64,7 +63,7 @@ namespace anm2ed::imgui return path::backslash_replace(path::make_relative(loadPath, document.directory_get())); } - void shader_path_edit(Document& document, int shaderId, std::filesystem::path Element::* member, + void shader_path_edit(Document& document, int shaderId, std::filesystem::path model::Shader::* member, const std::filesystem::path& value) { auto shader = shader_element_get(document, shaderId); @@ -76,7 +75,7 @@ namespace anm2ed::imgui } void shader_dialog_update(ShadersWindow& window, Manager& manager, Dialog& dialog, Dialog::Type type, - std::filesystem::path Element::* member) + std::filesystem::path model::Shader::* member) { if (!dialog.is_selected(type)) return; @@ -90,8 +89,8 @@ namespace anm2ed::imgui } void shader_path_row_update(ShadersWindow& window, Document& document, Resources& resources, Dialog& dialog, - Element* shader, std::filesystem::path Element::* member, Dialog::Type dialogType, - StringType label) + model::Shader* shader, std::filesystem::path model::Shader::* member, + Dialog::Type dialogType, StringType label) { auto shaderPath = shader ? shader->*member : std::filesystem::path{}; auto isDefault = shaderPath.empty(); @@ -122,7 +121,8 @@ namespace anm2ed::imgui ImGui::TextUnformatted(localize.get(label)); } - void shader_uniform_config_save(Document& document, Element& shaderElement, const resource::shader::Uniform& uniform) + void shader_uniform_config_save(Document& document, model::Shader& shaderElement, + const resource::shader::Uniform& uniform) { resource::shader::uniform_config_save(shaderElement, uniform); document.change(); @@ -212,7 +212,8 @@ namespace anm2ed::imgui return isChanged; } - void shader_uniforms_update(Document& document, Element* shaderElement, resource::Shader* runtime, ImVec2 tableSize) + void shader_uniforms_update(Document& document, model::Shader* shaderElement, resource::Shader* runtime, + ImVec2 tableSize) { if (!shaderElement) return; @@ -291,31 +292,27 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { auto document = manager.get(); - auto shaders = document ? document->anm2.element_get(ElementType::SHADERS) : nullptr; - if (!shaders) + if (!document) { ImGui::End(); return; } + auto shaders = &document->model.content.shaders; - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &Element::vertex); - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &Element::fragment); + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &model::Shader::vertex); + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &model::Shader::fragment); auto shader_add = [&]() { manager.command_push({manager.selected, [this](Manager&, Document& document) { - auto shaders = document.anm2.element_get(ElementType::SHADERS); - if (!shaders) return; - - auto shader = element_make(ElementType::SHADER); - shader.id = element_child_next_id_get(*shaders, ElementType::SHADER); - shader.name = localize.get(TEXT_NEW_SHADER); - document.edit_apply(EDIT_ADD_SHADER, - [&](Anm2&) + [&](model::Model& model) { - shaders->children.push_back(shader); + auto& shaders = model.content.shaders; + auto& shader = shaders.emplace_back( + model::Shader{.id = model::item_next_id_get(shaders), + .name = localize.get(TEXT_NEW_SHADER)}); document.shader.selection = {shader.id}; document.shader.reference = shader.id; newElementId = shader.id; @@ -327,17 +324,17 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [this](Manager&, Document& document) { - auto shaders = document.anm2.element_get(ElementType::SHADERS); - if (!shaders) return; - auto unused = document.anm2.element_unused(ElementType::SHADER); + auto unused = document.model.unused_get(ElementType::SHADER); if (unused.empty()) return; document.edit_apply(EDIT_REMOVE_UNUSED_SHADERS, - [&](Anm2&) + [&](model::Model& model) { + std::erase_if(model.content.shaders, + [&](const model::Shader& shader) + { return unused.contains(shader.id); }); for (auto id : unused) { - element_child_id_erase(*shaders, ElementType::SHADER, id); document.shader.selection.erase(id); if (document.shader.reference == id) document.shader.reference = -1; @@ -350,13 +347,13 @@ namespace anm2ed::imgui auto& selection = document->shader.selection; auto& reference = document->shader.reference; std::vector ids{}; - for (auto& shader : shaders->children) - if (shader.type == ElementType::SHADER) ids.push_back(shader.id); + for (auto& shader : *shaders) + ids.push_back(shader.id); - if (reference != -1 && !child_id_get(*shaders, ElementType::SHADER, reference)) reference = -1; + if (reference != -1 && !model::item_get(*shaders, reference)) reference = -1; for (auto it = selection.begin(); it != selection.end();) { - if (!child_id_get(*shaders, ElementType::SHADER, *it)) + if (!model::item_get(*shaders, *it)) it = selection.erase(it); else ++it; @@ -386,9 +383,8 @@ namespace anm2ed::imgui reference = -1; } - for (auto& shader : shaders->children) + for (auto& shader : *shaders) { - if (shader.type != ElementType::SHADER) continue; auto id = shader.id; auto isNewShader = newElementId == id; ImGui::PushID(id); @@ -510,9 +506,9 @@ namespace anm2ed::imgui ImGui::SeparatorText(localize.get(LABEL_FILES)); - shader_path_row_update(*this, *document, resources, dialog, shader, &Element::vertex, + shader_path_row_update(*this, *document, resources, dialog, shader, &model::Shader::vertex, Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); - shader_path_row_update(*this, *document, resources, dialog, shader, &Element::fragment, + shader_path_row_update(*this, *document, resources, dialog, shader, &model::Shader::fragment, Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); if (is_shader_reload_needed(*document, shader)) diff --git a/src/imgui/window/sounds.cpp b/src/imgui/window/sounds.cpp index 3b5324f..e67602d 100644 --- a/src/imgui/window/sounds.cpp +++ b/src/imgui/window/sounds.cpp @@ -13,12 +13,13 @@ namespace anm2ed::imgui { constexpr int SOUND_CARD_LINES = 2; + std::vector* sounds_get(Document&, model::Model& model) { return &model.content.sounds; } + Window sounds_window_register() { Window window{}; window.title = LABEL_SOUNDS_WINDOW; window.isOpen = &Settings::windowIsSounds; - window.containerType = ElementType::SOUNDS; window.elementType = ElementType::SOUND_ELEMENT; window.childLabel = "##Sounds Child"; window.cardLines = SOUND_CARD_LINES; @@ -33,28 +34,29 @@ namespace anm2ed::imgui {WINDOW_RELOAD, TOOLTIP_RELOAD_SOUNDS}, {WINDOW_REPLACE, TOOLTIP_REPLACE_SOUND}}; window.storage_get = [](Document& document) -> Storage& { return document.sound; }; - window.row_label_get = [](Document&, const Element& sound) + window_items_bind(window, sounds_get); + window.row_label_get = [](Document& document, int id) { - auto pathString = path::to_utf8(sound.path); - return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(sound.id, pathString)); + auto pathString = path::to_utf8(model::item_get(document.model.content.sounds, id)->path); + return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); }; window.row_select = [](Window&, Document& document, int id) { if (auto audio = document.sound_get(id); audio && ImGui::IsItemClicked(ImGuiMouseButton_Left)) resource::audio::play(*audio); }; - window.card_image_get = [](Document& document, Resources& resources, const Element& sound) + window.card_image_get = [](Document& document, Resources& resources, int id) { - auto audio = document.sound_get(sound.id); + auto audio = document.sound_get(id); auto isValid = audio && audio->is_valid(); auto& texture = resources.icons[isValid ? icon::SOUND : icon::NONE]; return WindowCardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; }; - window.tooltip_draw = [](Document& document, Resources& resources, const Element& sound) + window.tooltip_draw = [](Document& document, Resources& resources, int id) { - auto audio = document.sound_get(sound.id); - window_tooltip_name_draw(resources, path::to_utf8(sound.path)); - ImGui::Text("%s: %d", localize.get(BASIC_ID), sound.id); + auto audio = document.sound_get(id); + window_tooltip_name_draw(resources, path::to_utf8(model::item_get(document.model.content.sounds, id)->path)); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); if (audio && audio->is_valid()) ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); else @@ -77,16 +79,16 @@ namespace anm2ed::imgui }; window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto sound = window_element_get(window, document, document.sound.reference); + auto sound = model::item_get(document.model.content.sounds, document.sound.reference); if (sound && window.dialog) window_directory_open(*window.dialog, document, sound->path); }; - window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.reload = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { document.edit_apply(EDIT_RELOAD_SOUNDS, - [&](Anm2&) + [&](model::Model& model) { for (auto id : document.sound.selection) - if (auto sound = window_element_get(window, document, id)) + if (auto sound = model::item_get(model.content.sounds, id)) { document.sound_reload(id); toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, path::to_utf8(sound->path)); @@ -112,11 +114,11 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [&window, id = *document.sound.selection.begin(), dialogPath = window.dialog->path](Manager&, Document& document) { - auto sound = window_element_get(window, document, id); - if (!sound) return; + if (!model::item_get(document.model.content.sounds, id)) return; document.edit_apply(EDIT_REPLACE_SOUND, - [&](Anm2&) + [&](model::Model& model) { + auto sound = model::item_get(model.content.sounds, id); sound->path = window_asset_path_get(document, dialogPath); document.sound_reload(id); toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 396545b..6ed479d 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -8,6 +8,7 @@ #include "actions.hpp" #include "imgui_internal.h" #include "math.hpp" +#include "model/frames.hpp" #include "strings.hpp" #include "tool.hpp" #include "types.hpp" @@ -29,7 +30,7 @@ namespace anm2ed::imgui isFocused = false; auto& document = *manager.get(); - auto& anm2 = document.anm2; + auto& model = document.model; auto reference = document.reference_get(); auto& referenceSpritesheet = document.spritesheet.reference; auto& pan = document.editorPan; @@ -48,18 +49,17 @@ namespace anm2ed::imgui for (auto frameReference : document.frame_references_get()) { if (frameReference.itemType != LAYER) continue; - if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, frameReference.itemID)) - return layer->spritesheetId; + if (auto layer = model::item_get(model.content.layers, frameReference.itemID)) return layer->spritesheetId; } if (reference.frameIndex >= 0 && reference.itemType == LAYER) - if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID)) return layer->spritesheetId; + if (auto layer = model::item_get(model.content.layers, reference.itemID)) return layer->spritesheetId; return -1; }; if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get(); selectedLayerSpritesheet != -1 && document.editTarget != Document::EditTarget::REGION && document.editTarget != Document::EditTarget::SPRITESHEET) referenceSpritesheet = selectedLayerSpritesheet; - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, referenceSpritesheet); + auto spritesheet = model::item_get(model.content.spritesheets, referenceSpritesheet); auto baseTexture = document.texture_get(referenceSpritesheet); auto texture = baseTexture; auto& tool = settings.tool; @@ -79,8 +79,7 @@ namespace anm2ed::imgui set_to_rect(zoom, pan, {0, 0, (float)fitTexture->size.x, (float)fitTexture->size.y}); }; - auto region_get = [&](int id) - { return spritesheet ? child_id_get(*spritesheet, ElementType::REGION, id) : nullptr; }; + auto region_get = [&](int id) { return spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; }; if (ImGui::Begin(localize.get(LABEL_SPRITESHEET_EDITOR_WINDOW), &settings.windowIsSpritesheetEditor)) { @@ -158,7 +157,7 @@ namespace anm2ed::imgui viewport_set(); clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); - auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; + auto frame = model.frame_get(reference); auto viewTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; @@ -188,7 +187,7 @@ namespace anm2ed::imgui } } - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID); + auto layer = model::item_get(model.content.layers, reference.itemID); bool isReferenceLayerOnSpritesheet = frame && reference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; @@ -206,7 +205,7 @@ namespace anm2ed::imgui highlightedRegionId = regionReference; } - auto draw_region_rect = [&](Element& region, vec4 regionColor) + auto draw_region_rect = [&](const model::Region& region, vec4 regionColor) { auto cropModel = math::quad_model_get(region.size, region.crop); auto cropTransform = transform * cropModel; @@ -214,9 +213,8 @@ namespace anm2ed::imgui BORDER_DASH_OFFSET); }; - for (auto& region : spritesheet->children) + for (auto& region : spritesheet->regions) { - if (region.type != ElementType::REGION) continue; auto id = region.id; if (id == highlightedRegionId) continue; draw_region_rect(region, color::WHITE); @@ -310,11 +308,9 @@ namespace anm2ed::imgui auto editReference = reference; if (!selectedFrameReferences.contains(reference) && !selectedFrameReferences.empty()) editReference = *selectedFrameReferences.begin(); - auto frame = editReference.frameIndex >= 0 ? anm2.element_get(editReference) : nullptr; - auto itemReference = editReference; - itemReference.frameIndex = -1; - auto item = anm2.element_get(itemReference); - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, editReference.itemID); + auto frame = model.frame_get(editReference); + auto item = model.track_get(editReference); + auto layer = model::item_get(model.content.layers, editReference.itemID); bool isReferenceLayerOnSpritesheet = frame && editReference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; if (selectedFrameReferences.empty() && isReferenceLayerOnSpritesheet) @@ -383,9 +379,8 @@ namespace anm2ed::imgui for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference); - if (!item) continue; - frames_change(*item, frameChange, itemType, changeType, itemFrames); + if (auto item = document.model.track_edit(itemReference)) + model::frames_change(*item, frameChange, itemType, changeType, itemFrames); } }}); }; @@ -398,9 +393,9 @@ namespace anm2ed::imgui auto queuedFrameReferences = frameReferences; manager.command_push({manager.selected, [=](Manager&, Document& document) { - if (queuedReference.frameIndex < 0) return; - auto frame = document.anm2.element_get(queuedReference); - if (!frame) return; + auto framePointer = document.model.frame_get(queuedReference); + if (!framePointer) return; + auto frame = *framePointer; std::map> groupedFrames{}; for (auto frameReference : queuedFrameReferences) @@ -413,9 +408,9 @@ namespace anm2ed::imgui for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference); - if (!item) continue; - frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames); + if (auto item = document.model.track_edit(itemReference)) + model::frames_change(*item, frameChangeGet(frame), itemType, changeType, + itemFrames); } }}); }; @@ -424,7 +419,7 @@ namespace anm2ed::imgui { frame_change_from_current_apply_to( frameReferences, - [=](const Element& frame) + [=](const model::Frame& frame) { auto minPoint = glm::min(frame.crop, frame.crop + frame.size); auto maxPoint = glm::max(frame.crop, frame.crop + frame.size); @@ -460,11 +455,9 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [=](Manager&, Document& document) { auto spritesheet = - document.anm2.element_get(ElementType::SPRITESHEET, queuedSpritesheet); + model::item_get(document.model.content.spritesheets, queuedSpritesheet); if (!spritesheet) return; - auto region = child_id_get(*spritesheet, ElementType::REGION, id); - if (!region) return; - update(*region); + if (auto region = model::item_get(spritesheet->regions, id)) update(*region); }}); }; auto region_update_all = [&](auto update) @@ -474,13 +467,11 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [=](Manager&, Document& document) { auto spritesheet = - document.anm2.element_get(ElementType::SPRITESHEET, queuedSpritesheet); + model::item_get(document.model.content.spritesheets, queuedSpritesheet); if (!spritesheet) return; for (auto id : queuedSelection) { - auto region = child_id_get(*spritesheet, ElementType::REGION, id); - if (!region) continue; - update(*region); + if (auto region = model::item_get(spritesheet->regions, id)) update(*region); } }}); }; @@ -489,7 +480,7 @@ namespace anm2ed::imgui auto queuedCrop = clamp_vec2_to_int(crop); auto queuedSize = clamp_vec2_to_int(size); region_update_all( - [=](Element& region) + [=](model::Region& region) { region.crop = queuedCrop; region.size = queuedSize; @@ -498,7 +489,7 @@ namespace anm2ed::imgui auto region_offset_all = [&](const vec2& delta) { region_update_all( - [=](Element& region) + [=](model::Region& region) { region.crop = clamp_vec2_to_int(region.crop + delta); region.size = clamp_vec2_to_int(region.size); @@ -507,7 +498,7 @@ namespace anm2ed::imgui auto region_crop_normalize_all = [&](bool isSnap, ivec2 snapGridSize, ivec2 snapGridOffset) { region_update_all( - [=](Element& region) + [=](model::Region& region) { auto minPoint = glm::min(region.crop, region.crop + region.size); auto maxPoint = glm::max(region.crop, region.crop + region.size); @@ -566,7 +557,7 @@ namespace anm2ed::imgui { auto queuedPivot = pivot; region_update(id, - [=](Element& region) + [=](model::Region& region) { region.origin = Origin::CUSTOM; region.pivot = queuedPivot; @@ -575,7 +566,7 @@ namespace anm2ed::imgui auto region_pivot_offset = [&](int id, vec2 delta) { region_update(id, - [=](Element& region) + [=](model::Region& region) { region.origin = Origin::CUSTOM; region.pivot += delta; @@ -593,9 +584,8 @@ namespace anm2ed::imgui if (useTool == tool::PAN && spritesheet && texture && texture->is_valid() && isMouseOverCanvas) { - for (auto& region : spritesheet->children) + for (auto& region : spritesheet->regions) { - if (region.type != ElementType::REGION) continue; auto minPoint = glm::min(region.crop, region.crop + region.size); auto maxPoint = glm::max(region.crop, region.crop + region.size); if (hoverMousePos.x >= minPoint.x && hoverMousePos.x <= maxPoint.x && hoverMousePos.y >= minPoint.y && diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index 7f06af6..5d7d2f6 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -18,17 +18,27 @@ namespace anm2ed::imgui constexpr int MERGE_OPTIONS_ROWS = 6; constexpr int PADDING_MAX = 100; + std::vector* spritesheets_get(Document&, model::Model& model) + { + return &model.content.spritesheets; + } + + const model::Spritesheet* spritesheet_get(Document& document, int id) + { + return model::item_get(document.model.content.spritesheets, id); + } + bool is_spritesheet_regions(Document& document, int id) { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); - return spritesheet && child_first_get(*spritesheet, ElementType::REGION); + auto spritesheet = spritesheet_get(document, id); + return spritesheet && !spritesheet->regions.empty(); } void spritesheets_save(Document& document, const std::set& ids) { for (auto id : ids) { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); + auto spritesheet = spritesheet_get(document, id); auto texture = document.texture_get(id); if (!spritesheet || !texture) continue; auto pathString = path::to_utf8(spritesheet->path); @@ -46,13 +56,13 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [&window, id, dialogPath, edit, isWritten](Manager&, Document& document) { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, id); auto texture = document.texture_get(id); - if (!spritesheet || (isWritten && !texture)) return; + if (!spritesheet_get(document, id) || (isWritten && !texture)) return; document.edit_apply( edit, - [&](Anm2&) + [&](model::Model& model) { + auto spritesheet = model::item_get(model.content.spritesheets, id); auto newPath = window_asset_path_get(document, dialogPath); auto pathString = path::to_utf8(newPath); if (isWritten) @@ -91,7 +101,6 @@ namespace anm2ed::imgui Window window{}; window.title = LABEL_SPRITESHEETS_WINDOW; window.isOpen = &Settings::windowIsSpritesheets; - window.containerType = ElementType::SPRITESHEETS; window.elementType = ElementType::SPRITESHEET; window.childLabel = "##Spritesheets Child"; window.cardLines = SPRITESHEET_CARD_LINES; @@ -113,11 +122,12 @@ namespace anm2ed::imgui window.popup2 = PopupHelper(LABEL_SPRITESHEETS_PACK_POPUP, POPUP_SMALL_NO_HEIGHT); window.popup3 = PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT); window.storage_get = [](Document& document) -> Storage& { return document.spritesheet; }; - window.row_label_get = [](Document& document, const Element& spritesheet) + window_items_bind(window, spritesheets_get); + window.row_label_get = [](Document& document, int id) { - auto pathString = path::to_utf8(spritesheet.path); - auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(spritesheet.id, pathString)); - return document.spritesheet_is_dirty(spritesheet.id) + auto pathString = path::to_utf8(spritesheet_get(document, id)->path); + auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); + return document.spritesheet_is_dirty(id) ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) : label; }; @@ -127,16 +137,17 @@ namespace anm2ed::imgui document.region.reference = -1; document.region.selection.clear(); }; - window.card_image_get = [](Document& document, Resources& resources, const Element& spritesheet) + window.card_image_get = [](Document& document, Resources& resources, int id) { - auto texture = document.texture_get(spritesheet.id); + auto texture = document.texture_get(id); auto isValid = texture && texture->is_valid(); auto& image = isValid ? *texture : resources.icons[icon::NONE]; return WindowCardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; }; - window.tooltip_draw = [](Document& document, Resources& resources, const Element& spritesheet) + window.tooltip_draw = [](Document& document, Resources& resources, int id) { - auto texture = document.texture_get(spritesheet.id); + auto& spritesheet = *spritesheet_get(document, id); + auto texture = document.texture_get(id); auto isValid = texture && texture->is_valid(); auto& image = isValid ? *texture : resources.icons[icon::NONE]; window_tooltip_image_draw( @@ -169,36 +180,37 @@ namespace anm2ed::imgui }; window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto spritesheet = window_element_get(window, document, document.spritesheet.reference); + auto spritesheet = spritesheet_get(document, document.spritesheet.reference); if (spritesheet && window.dialog) window_directory_open(*window.dialog, document, spritesheet->path); }; - window.remove_unused = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.remove_unused = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { - auto unused = document.anm2.element_unused(ElementType::SPRITESHEET); - auto spritesheets = window_container_get(window, document); - if (unused.empty() || !spritesheets) return; + auto unused = document.model.unused_get(ElementType::SPRITESHEET); + if (unused.empty()) return; document.edit_apply(EDIT_REMOVE_UNUSED_SPRITESHEETS, - [&](Anm2&) + [&](model::Model& model) { - for (auto id : unused) - if (auto spritesheet = window_element_get(window, document, id)) - { - toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, path::to_utf8(spritesheet->path)); - element_child_id_erase(*spritesheets, ElementType::SPRITESHEET, id); - } + std::erase_if(model.content.spritesheets, + [&](const model::Spritesheet& spritesheet) + { + if (!unused.contains(spritesheet.id)) return false; + toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, spritesheet.id, + path::to_utf8(spritesheet.path)); + return true; + }); }); }; - window.reload = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + window.reload = [](Window&, Manager&, Settings&, Document& document, Clipboard&) { auto selected = document.spritesheet.selection; document.edit_apply(EDIT_RELOAD_SPRITESHEETS, - [&](Anm2&) + [&](model::Model&) { for (auto id : selected) document.texture_reload(id); }); for (auto id : selected) - if (auto spritesheet = window_element_get(window, document, id)) + if (auto spritesheet = spritesheet_get(document, id)) { document.spritesheet_hash_set_saved(id); toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path::to_utf8(spritesheet->path)); diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index f20dba7..ca2da65 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -23,6 +23,7 @@ #include "util/imgui/shortcut.hpp" #include "util/imgui/tooltip.hpp" +#include "model/frames.hpp" #include "vector.hpp" #include "window/window.hpp" @@ -160,11 +161,11 @@ namespace anm2ed::imgui Resources& resources; Clipboard& clipboard; Document& document; - Anm2& anm2; + model::Model& model; Playback& playback; Reference reference; Storage& region; - Element* animation{}; + const model::Animation* animation{}; float rowFrameChildHeight{}; bool isLightTheme{}; bool isTextPushed{}; @@ -196,15 +197,13 @@ namespace anm2ed::imgui ImVec2 frameBoxClipMax{}; bool isFrameBoxClipSet{}; - Element* item_get(int type, int id = -1, int groupType = NONE, int groupId = -1); - Element* frame_get(); - Element* selected_item_get(); - Element* track_container_get(int type); - Element* track_group_get(int type, int groupId); + const model::Track* item_get(int type, int id = -1, int groupType = NONE, int groupId = -1); + const model::Frame* frame_get(); + const model::Track* selected_item_get(); + const model::TrackGroup* track_group_get(int type, int groupId); bool is_track_group_visible(int type, int groupId); - Element* row_group_get(const TimelineItemRow& row); - int group_items_count_get(int type, int groupId); - Element* command_item_reference_get(Document& document, Reference itemReference); + const model::TrackGroup* row_group_get(const TimelineItemRow& row); + const model::Track* command_item_reference_get(Document& document, Reference itemReference); glm::vec4 color_get(TimelineColor, int); std::set drag_frame_references_get(const Reference&); // Queues an edit on the document; its result is selected (frames by default). @@ -221,7 +220,7 @@ namespace anm2ed::imgui void edit_begin_push(StringType); void reference_set(Reference); void frames_select_for(Document&, const edit::Uids&); - Element* command_frame_get(Document& document, const Reference& targetReference); + const model::Frame* command_frame_get(Document& document, const Reference& targetReference); Reference item_reference_get(int type, int id, int groupType = NONE, int groupId = -1); Reference item_reference_from_frame_get(Reference frameReference); bool is_same_item(const Reference& left, const Reference& right); @@ -250,7 +249,7 @@ namespace anm2ed::imgui void frames_bake(); std::set selected_root_frame_references_get(); std::set item_references_for_bake_into_other_frames_get(const Document& targetDocument, - const Element& targetAnimation, + const model::Animation& targetAnimation, BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls); bool is_bake_into_other_frames_ready(); @@ -288,7 +287,7 @@ namespace anm2ed::imgui void context_menu(); void item_base_properties_open(int type, int id); void group_properties_close(); - void group_properties_open(const TimelineItemRow& row, const Element& group); + void group_properties_open(const TimelineItemRow& row, const model::TrackGroup& group); void group_properties_update(); void item_context_menu(); diff --git a/src/imgui/window/timeline/edit.cpp b/src/imgui/window/timeline/edit.cpp index 7abc327..fdbb8b5 100644 --- a/src/imgui/window/timeline/edit.cpp +++ b/src/imgui/window/timeline/edit.cpp @@ -7,7 +7,7 @@ namespace anm2ed::imgui auto targetReference = reference; auto time = (int)document.frameTime; if (!animation || !command_item_reference_get(document, targetReference)) return; - edit_push(EDIT_INSERT_FRAME, [=](Anm2& anm2) { return edit::frame_insert(anm2, targetReference, time); }); + edit_push(EDIT_INSERT_FRAME, [=](model::Model& model) { return edit::frame_insert(model, targetReference, time); }); } void TimelineContext::frames_delete_action() @@ -15,7 +15,7 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.empty()) return; edit_push( - EDIT_DELETE_FRAMES, [=](Anm2& anm2) { return edit::frames_delete(anm2, selectedFrames); }, + EDIT_DELETE_FRAMES, [=](model::Model& model) { return edit::frames_delete(model, selectedFrames); }, [this](Document& document, const edit::Uids&) { frames_selection_set_reference_for(document); }); } @@ -24,8 +24,8 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; - edit_push(EDIT_DUPLICATE_FRAMES, - [=, focus = reference](Anm2& anm2) { return edit::frames_duplicate(anm2, selectedFrames, focus); }); + edit_push(EDIT_DUPLICATE_FRAMES, [=, focus = reference](model::Model& model) + { return edit::frames_duplicate(model, selectedFrames, focus); }); } bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) @@ -45,7 +45,7 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (!is_frames_reverse_available(selectedFrames)) return; - edit_push(EDIT_REVERSE_FRAMES, [=](Anm2& anm2) { return edit::frames_reverse(anm2, selectedFrames); }); + edit_push(EDIT_REVERSE_FRAMES, [=](model::Model& model) { return edit::frames_reverse(model, selectedFrames); }); } void TimelineContext::frames_bake() @@ -54,8 +54,8 @@ namespace anm2ed::imgui std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; edit_push(EDIT_BAKE_FRAMES, [=, interval = settings.bakeInterval, isRoundScale = settings.bakeIsRoundScale, - isRoundRotation = settings.bakeIsRoundRotation](Anm2& anm2) - { return edit::frames_bake(anm2, selectedFrames, interval, isRoundScale, isRoundRotation); }); + isRoundRotation = settings.bakeIsRoundRotation](model::Model& model) + { return edit::frames_bake(model, selectedFrames, interval, isRoundScale, isRoundRotation); }); } std::set TimelineContext::selected_root_frame_references_get() @@ -65,10 +65,9 @@ namespace anm2ed::imgui return selectedFrames; } - std::set TimelineContext::item_references_for_bake_into_other_frames_get(const Document& targetDocument, - const Element& targetAnimation, - BakeIntoOtherFramesTarget target, - bool isLayers, bool isNulls) + std::set TimelineContext::item_references_for_bake_into_other_frames_get( + const Document& targetDocument, const model::Animation& targetAnimation, BakeIntoOtherFramesTarget target, + bool isLayers, bool isNulls) { std::set result{}; auto animationIndex = targetDocument.reference_get().animationIndex; @@ -79,17 +78,15 @@ namespace anm2ed::imgui return result; } - for (const auto& row : TRACK_CONTAINERS) + for (auto itemType : {LAYER, NULL_}) { - auto container = child_first_get(targetAnimation, row.container); - if (!container || !(row.itemType == ItemType::LAYER ? isLayers : isNulls)) continue; - tracks_each(*container, row.track, - [&](const Element& track) - { - auto itemType = (int)row.itemType; - result.insert(Reference{animationIndex, itemType, anm2ed::track_id_get(track), -1, - track.groupId == -1 ? NONE : itemType, track.groupId}); - }); + if (!(itemType == LAYER ? isLayers : isNulls)) continue; + model::tracks_each(model::animation_entries_get(targetAnimation, itemType), + [&](const model::Track& track, const model::TrackGroup* group) + { + result.insert(Reference{animationIndex, itemType, track.id, -1, group ? itemType : NONE, + group ? group->id : -1}); + }); } return result; } @@ -111,8 +108,8 @@ namespace anm2ed::imgui document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); edit::RootBakeOptions options{settings.bakeIsRoundScale, settings.bakeIsRoundRotation, settings.bakeIsMatchRootInterpolation, settings.bakeIsUseRootPivot}; - edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, - [=](Anm2& anm2) { return edit::root_bake_into(anm2, selectedRootFrames, targetItems, options); }); + edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, [=](model::Model& model) + { return edit::root_bake_into(model, selectedRootFrames, targetItems, options); }); } void TimelineContext::frame_split() @@ -121,7 +118,7 @@ namespace anm2ed::imgui if (selectedFrames.size() != 1) return; auto targetReference = *selectedFrames.begin(); auto time = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); - edit_push(EDIT_SPLIT_FRAME, [=](Anm2& anm2) { return edit::frame_split(anm2, targetReference, time); }); + edit_push(EDIT_SPLIT_FRAME, [=](model::Model& model) { return edit::frame_split(model, targetReference, time); }); } void TimelineContext::item_remove() @@ -132,8 +129,8 @@ namespace anm2ed::imgui if (row.type == LAYER || row.type == NULL_) (row.isGroup ? groupIds : ids)[row.type].insert(row.id); if (!animation || (ids.empty() && groupIds.empty())) return; edit_push( - EDIT_REMOVE_ITEMS, [=, animationIndex = reference.animationIndex](Anm2& anm2) - { return edit::items_remove(anm2, animationIndex, ids, groupIds); }, + EDIT_REMOVE_ITEMS, [=, animationIndex = reference.animationIndex](model::Model& model) + { return edit::items_remove(model, animationIndex, ids, groupIds); }, [this](Document& document, const edit::Uids&) { reference_clear_for(document); @@ -174,8 +171,8 @@ namespace anm2ed::imgui edit_push( EDIT_GROUP_ITEMS, [=, animationIndex = reference.animationIndex, type = targetReferences.front().itemType, - name = std::string(localize.get(TEXT_NEW_GROUP))](Anm2& anm2) - { return edit::items_group(anm2, animationIndex, type, ids, name); }, + name = std::string(localize.get(TEXT_NEW_GROUP))](model::Model& model) + { return edit::items_group(model, animationIndex, type, ids, name); }, [=, this](Document& document, const edit::Uids& uids) { if (uids.empty()) return; @@ -209,15 +206,15 @@ namespace anm2ed::imgui (row.isGroup ? groups : tracks) .insert(row.isGroup ? Reference{row.animationIndex, row.type, row.id} : row_item_reference_get(row)); Selection moved{}; - selection_references_set(moved, anm2, SelectionKind::TRACKS, tracks); - selection_references_set(moved, anm2, SelectionKind::GROUPS, groups); - if (!tracks.empty()) selection_focus_set(moved, anm2, *tracks.begin()); + selection_references_set(moved, model, SelectionKind::TRACKS, tracks); + selection_references_set(moved, model, SelectionKind::GROUPS, groups); + if (!tracks.empty()) selection_focus_set(moved, model, *tracks.begin()); edit_push( EDIT_MOVE_ITEMS, - [=](Anm2& anm2) + [=](model::Model& model) { - return edit::items_move(anm2, animationIndex, targetType, ids, groupIds, target, isDropAfter, + return edit::items_move(model, animationIndex, targetType, ids, groupIds, target, isDropAfter, isDropIntoGroup); }, [=, this](Document& document, const edit::Uids&) @@ -235,8 +232,8 @@ namespace anm2ed::imgui void TimelineContext::fit_animation_length() { if (!animation) return; - edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](Anm2& anm2) - { return edit::animation_length_fit(anm2, animationIndex); }); + edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](model::Model& model) + { return edit::animation_length_fit(model, animationIndex); }); } void TimelineContext::frame_references_copy(const std::set& selectedFrames) @@ -246,12 +243,9 @@ namespace anm2ed::imgui std::string clipboardString{}; for (auto frameReference : selectedFrames) { - auto item = - item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; + auto frame = model.frame_get(frameReference); if (!frame) continue; - auto parentType = TYPE_TRACKS[frameReference.itemType]; - clipboardString += element_to_string(*frame, parentType); + clipboardString += model::frame_to_string(*frame, (ItemType)frameReference.itemType); } if (!clipboardString.empty()) clipboard.set(clipboardString); } @@ -270,7 +264,7 @@ namespace anm2ed::imgui if (selectedFrames.empty()) return; frame_references_copy(selectedFrames); edit_push( - EDIT_CUT_FRAMES, [=](Anm2& anm2) { return edit::frames_delete(anm2, selectedFrames); }, + EDIT_CUT_FRAMES, [=](model::Model& model) { return edit::frames_delete(model, selectedFrames); }, [this](Document& document, const edit::Uids&) { frames_selection_set_reference_for(document); }); } @@ -289,8 +283,8 @@ namespace anm2ed::imgui EDIT_PASTE_FRAMES, [=, targetReference = reference, selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE), - time = hoveredTime](Anm2& anm2) - { return edit::frames_paste(anm2, targetReference, selectedFrames, text, time, errorString.get()); }, + time = hoveredTime](model::Model& model) + { return edit::frames_paste(model, targetReference, selectedFrames, text, time, errorString.get()); }, [=, this](Document& document, const edit::Uids& uids) { if (errorString->empty()) return frames_select_for(document, uids); diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index 3948d9c..e2cee50 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -32,13 +32,13 @@ namespace anm2ed::imgui Reference target{drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}; edit_push( EDIT_MOVE_FRAMES, - [frames = std::set(drag.references.begin(), drag.references.end()), target, insertIndex](Anm2& anm2) - { return edit::frames_move(anm2, frames, target, insertIndex); }, + [frames = std::set(drag.references.begin(), drag.references.end()), target, + insertIndex](model::Model& model) { return edit::frames_move(model, frames, target, insertIndex); }, [=, this](Document& document, const edit::Uids& uids) { frames_select_for(document, uids); if (targetType == LAYER) - if (auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetID)) + if (auto layer = model::item_get(document.model.content.layers, targetID)) document.spritesheet.reference = layer->spritesheetId; }); } @@ -166,11 +166,9 @@ namespace anm2ed::imgui auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; auto rowMaxY = rowMinY + childSize.y; float selectionFrameTime{}; - auto frameType = track_frame_type_get(*item); int frameIndex{}; - for (const auto& frame : item->children) + for (const auto& frame : item->frames) { - if (frame.type != frameType) continue; auto frameReference = row_reference_make(frameIndex); auto frameStart = type == TRIGGER ? frame.atFrame : selectionFrameTime; auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; @@ -321,15 +319,13 @@ namespace anm2ed::imgui { auto mouseX = mousePos.x - cursorScreenPos.x; auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = track_frames_count_get(*item); + int dropIndex = (int)item->frames.size(); float dropFrameTime{}; float frameTime{}; - auto frameType = track_frame_type_get(*item); int frameIndex{}; - for (const auto& frame : item->children) + for (const auto& frame : item->frames) { - if (frame.type != frameType) continue; auto frameStart = frameTime; auto frameEnd = frameStart + frame.duration; if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) @@ -368,14 +364,11 @@ namespace anm2ed::imgui } } - auto frameType = track_frame_type_get(*item); auto& selectedFrames = document.selection.uids[SelectionKind::FRAMES]; - int frameIndex{}; - for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) + for (int frameIndex = 0; frameIndex < (int)item->frames.size(); ++frameIndex) { - auto& frame = item->children[childIndex]; - if (frame.type != frameType) continue; - ImGui::PushID(childIndex); + auto& frame = item->frames[frameIndex]; + ImGui::PushID(frameIndex); auto frameReference = row_reference_make(frameIndex); auto isFrameVisible = isVisible && frame.isVisible; @@ -391,7 +384,6 @@ namespace anm2ed::imgui { if (type != TRIGGER) frameTime += frame.duration; ImGui::PopID(); - ++frameIndex; continue; } auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); @@ -416,7 +408,7 @@ namespace anm2ed::imgui if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) { if (type == LAYER) - if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id)) + if (auto layer = model::item_get(model.content.layers, id)) document.spritesheet.reference = layer->spritesheetId; if (type != TRIGGER) @@ -425,9 +417,9 @@ namespace anm2ed::imgui { auto targetReference = frameReference; edit_push(EDIT_FRAME_INTERPOLATION, - [=](Anm2& anm2) + [=](model::Model& model) { - if (auto frame = anm2.element_get(targetReference)) + if (auto frame = model.frame_edit(targetReference)) frame->interpolation = frame->interpolation == Interpolation::NONE ? Interpolation::LINEAR : Interpolation::NONE; }); @@ -535,7 +527,6 @@ namespace anm2ed::imgui if (type != TRIGGER) frameTime += frame.duration; ImGui::PopID(); - ++frameIndex; } if (isFrameMovePreview) @@ -581,7 +572,7 @@ namespace anm2ed::imgui auto atFrame = glm::clamp( hoveredTime, 0, settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1); command_push([=](Manager&, Document& document) - { edit::trigger_at_frame_set(document.anm2, targetReference, atFrame); }); + { edit::trigger_at_frame_set(document.model, targetReference, atFrame); }); } else { @@ -590,7 +581,7 @@ namespace anm2ed::imgui durations[targetReference] = draggedFrameStartDuration + durationDelta; for (auto frameDuration : draggedFrameStartDurations) durations[frameDuration.reference] = frameDuration.duration + durationDelta; - command_push([=](Manager&, Document& document) { edit::frame_durations_set(document.anm2, durations); }); + command_push([=](Manager&, Document& document) { edit::frame_durations_set(document.model, durations); }); } } @@ -601,8 +592,8 @@ namespace anm2ed::imgui command_push( [=, this](Manager&, Document& document) { - auto item = command_item_reference_get(document, targetReference); - if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); + auto item = document.model.track_edit(targetReference); + if (targetType == TRIGGER && item) model::frames_sort_by_at_frame(*item); document.change(); }); isDraggedFrameActive = false; @@ -644,9 +635,8 @@ namespace anm2ed::imgui auto animationsLength = [&]() { int length{}; - if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) - for (auto& item : animations->children) - if (item.type == ElementType::ANIMATION) length = std::max(length, animation_length_get(item)); + for (auto [index, item] : model.animations_get()) + length = std::max(length, model::animation_length_get(*item)); return length; }(); auto childWidth = animationsLength * ImGui::GetTextLineHeight(); @@ -865,11 +855,9 @@ namespace anm2ed::imgui { auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; edit_push(EDIT_ANIMATION_LENGTH, - [=](Anm2& anm2) + [=](model::Model& model) { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - animation->frameNum = frameNum; + if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = frameNum; }); } if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; @@ -883,11 +871,9 @@ namespace anm2ed::imgui { auto animationIndex = reference.animationIndex; edit_push(EDIT_LOOP, - [=](Anm2& anm2) + [=](model::Model& model) { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) return; - animation->isLoop = isLoop; + if (auto animation = model.animation_edit(animationIndex)) animation->isLoop = isLoop; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); @@ -896,43 +882,21 @@ namespace anm2ed::imgui ImGui::SameLine(); - auto info = element_first_get(anm2.root, ElementType::INFO); - auto fps = info ? info->fps : 30; + auto fps = model.info.fps; ImGui::SetNextItemWidth(widgetSize.x); if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) { - edit_push(EDIT_FPS, - [=](Anm2& anm2) - { - auto info = element_first_get(anm2.root, ElementType::INFO); - if (!info) - { - anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &anm2.root.children.back(); - } - info->fps = fps; - }); + edit_push(EDIT_FPS, [=](model::Model& model) { model.info.fps = fps; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); ImGui::SameLine(); - info = element_first_get(anm2.root, ElementType::INFO); - auto createdBy = info ? info->createdBy : std::string{}; + auto createdBy = model.info.createdBy; ImGui::SetNextItemWidth(widgetSize.x); if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) { - edit_push(EDIT_AUTHOR, - [=](Anm2& anm2) - { - auto info = element_first_get(anm2.root, ElementType::INFO); - if (!info) - { - anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &anm2.root.children.back(); - } - info->createdBy = createdBy; - }); + edit_push(EDIT_AUTHOR, [=](model::Model& model) { model.info.createdBy = createdBy; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index f065b36..629284f 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -54,11 +54,11 @@ namespace anm2ed::imgui auto frame = frame_get(); if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; if (frame->regionId != -1) return; - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); + auto layer = model::item_get(model.content.layers, targetReference.itemID); if (!layer) return; auto spritesheetID = layer->spritesheetId; - if (!anm2.element_get(ElementType::SPRITESHEET, spritesheetID)) return; + if (!model::item_get(model.content.spritesheets, spritesheetID)) return; auto settingsPtr = &settings; command_push( @@ -66,17 +66,13 @@ namespace anm2ed::imgui { auto frame = command_frame_get(document, targetReference); if (!frame || frame->regionId != -1) return; - auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); + auto layer = model::item_get(document.model.content.layers, targetReference.itemID); if (!layer) return; auto spritesheetID = layer->spritesheetId; - if (!document.anm2.element_get(ElementType::SPRITESHEET, spritesheetID)) return; + if (!model::item_get(document.model.content.spritesheets, spritesheetID)) return; - auto region = element_make(ElementType::REGION); - region.crop = frame->crop; - region.size = frame->size; - region.pivot = frame->pivot; - region.origin = Origin::CUSTOM; + model::Region region{.crop = frame->crop, .size = frame->size, .pivot = frame->pivot}; document.spritesheet.reference = spritesheetID; settingsPtr->windowIsRegions = true; @@ -96,9 +92,9 @@ namespace anm2ed::imgui { if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return false; auto frame = command_frame_get(document, frameReference); - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); + auto layer = model::item_get(model.content.layers, frameReference.itemID); return frame && frame->regionId == -1 && layer && - anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId); + model::item_get(model.content.spritesheets, layer->spritesheetId); }; auto selectedRegionFrames = selectedFrames; std::erase_if(selectedRegionFrames, @@ -132,10 +128,11 @@ namespace anm2ed::imgui .shortcut = -1, .isEnabled = [=, this]() { return !selectedRootFrames.empty(); }, .run = [&]() { bakeIntoOtherFramesPopup.open(); }}); - actions.add({.label = LABEL_FIT_ANIMATION_LENGTH, - .shortcut = SHORTCUT_FIT, - .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, - .run = [&]() { fit_animation_length(); }}); + actions.add( + {.label = LABEL_FIT_ANIMATION_LENGTH, + .shortcut = SHORTCUT_FIT, + .isEnabled = [&]() { return animation && animation->frameNum != model::animation_length_get(*animation); }, + .run = [&]() { fit_animation_length(); }}); actions.separator(); actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, .shortcut = -1, @@ -163,7 +160,7 @@ namespace anm2ed::imgui void TimelineContext::item_base_properties_open(int type, int id) { - if (auto row = anm2ed::track_container_get((ItemType)type)) manager.item_properties_open(row->element, id); + manager.item_properties_open(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, id); } void TimelineContext::group_properties_close() @@ -175,7 +172,7 @@ namespace anm2ed::imgui groupPropertiesPopup.close(); } - void TimelineContext::group_properties_open(const TimelineItemRow& row, const Element& group) + void TimelineContext::group_properties_open(const TimelineItemRow& row, const model::TrackGroup& group) { groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; groupAnimationIndex = reference.animationIndex; @@ -207,13 +204,10 @@ namespace anm2ed::imgui auto targetType = groupType; auto targetId = groupId; edit_push(EDIT_RENAME_GROUP, - [=](Anm2& anm2) + [=](model::Model& model) { - auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; - if (!group) return; - group->name = targetName; + if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetId)) + group->name = targetName; }); } if (result != PopupButton::NONE) group_properties_close(); @@ -236,7 +230,7 @@ namespace anm2ed::imgui auto selectedGroupableItems = item_references_groupable_get(); auto copyFrames = copy_frame_references_get(); TimelineItemRow selectedGroupRow{}; - Element* selectedGroup{}; + const model::TrackGroup* selectedGroup{}; if (selectedRows.size() == 1 && selectedRows.front().isGroup) { auto row = selectedRows.front(); diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp index 952d2cc..0c3777d 100644 --- a/src/imgui/window/timeline/popups.cpp +++ b/src/imgui/window/timeline/popups.cpp @@ -35,8 +35,9 @@ namespace anm2ed::imgui if (result == PopupButton::CONFIRM) edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, - mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE]( - Anm2& anm2) { anm2.regions_generate({}, targetFrames, format, mapping); }); + mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET + : RegionFrameMapping::PRESERVE](model::Model& model) + { return edit::regions_generate(model, {}, targetFrames, format, mapping); }); if (result != PopupButton::NONE) makeManyRegionsPopup.close(); ImGui::EndPopup(); @@ -180,7 +181,7 @@ namespace anm2ed::imgui [=, this](Manager&, Document& document) { for (auto frameReference : selectedFrames) - if (auto frame = command_frame_get(document, frameReference)) + if (auto frame = document.model.frame_edit(frameReference)) frame->duration = std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); document.change(); @@ -195,14 +196,14 @@ namespace anm2ed::imgui auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL); if (isPreviousFrame || isNextFrame) - if (auto item = selected_item_get(); item && !item->children.empty()) + if (auto item = selected_item_get(); item && !item->frames.empty()) { auto frameReference = reference; frameReference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, - (int)item->children.size() - 1); + (int)item->frames.size() - 1); reference_set(frameReference); frames_selection_set_reference_for(document); - document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); + document.frameTime = model::frame_time_from_index_get(*item, reference.frameIndex); } if (isPreviousItem) reference_set_adjacent_item(-1); diff --git a/src/imgui/window/timeline/selection.cpp b/src/imgui/window/timeline/selection.cpp index 7d4cb5f..13117be 100644 --- a/src/imgui/window/timeline/selection.cpp +++ b/src/imgui/window/timeline/selection.cpp @@ -2,20 +2,14 @@ namespace anm2ed::imgui { - Element* TimelineContext::item_get(int type, int id, int groupType, int groupId) + const model::Track* TimelineContext::item_get(int type, int id, int groupType, int groupId) { - return animation ? animation_item_get(*animation, (ItemType)(type), id, groupType, groupId) : nullptr; + return animation ? model::animation_track_get(*animation, type, id, groupType, groupId) : nullptr; } - Element* TimelineContext::track_container_get(int type) + const model::TrackGroup* TimelineContext::track_group_get(int type, int groupId) { - return animation ? child_first_get(*animation, TYPE_CONTAINERS[type]) : nullptr; - } - - Element* TimelineContext::track_group_get(int type, int groupId) - { - auto container = track_container_get(type); - return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; + return animation ? model::animation_track_group_get(*animation, type, groupId) : nullptr; } bool TimelineContext::is_track_group_visible(int type, int groupId) @@ -25,36 +19,24 @@ namespace anm2ed::imgui return !group || group->isVisible; } - Element* TimelineContext::row_group_get(const TimelineItemRow& row) + const model::TrackGroup* TimelineContext::row_group_get(const TimelineItemRow& row) { return row.isGroup ? track_group_get(row.type, row.id) : nullptr; } - int TimelineContext::group_items_count_get(int type, int groupId) + const model::Track* TimelineContext::command_item_reference_get(Document& document, Reference itemReference) { - auto container = track_container_get(type); - auto trackType = TYPE_TRACKS[type]; - int count{}; - if (!container) return count; - for (auto& item : container->children) - if (item.type == trackType && item.groupId == groupId) ++count; - return count; + return document.model.track_get(itemReference); } - Element* TimelineContext::command_item_reference_get(Document& document, Reference itemReference) + const model::Frame* TimelineContext::command_frame_get(Document& document, const Reference& targetReference) { - itemReference.frameIndex = -1; - return document.anm2.element_get(itemReference); + return document.model.frame_get(targetReference); } - Element* TimelineContext::command_frame_get(Document& document, const Reference& targetReference) - { - return targetReference.frameIndex < 0 ? nullptr : document.anm2.element_get(targetReference); - } + const model::Frame* TimelineContext::frame_get() { return command_frame_get(document, reference); } - Element* TimelineContext::frame_get() { return command_frame_get(document, reference); } - - Element* TimelineContext::selected_item_get() { return command_item_reference_get(document, reference); } + const model::Track* TimelineContext::selected_item_get() { return command_item_reference_get(document, reference); } glm::vec4 TimelineContext::color_get(TimelineColor color, int type) { @@ -90,7 +72,7 @@ namespace anm2ed::imgui targetDocument.frame_references_set({references.begin(), references.end()}); targetDocument.reference_set(focus); if (auto item = command_item_reference_get(targetDocument, focus); item && focus.itemType != TRIGGER) - targetDocument.frameTime = frame_time_from_index_get(*item, focus.frameIndex); + targetDocument.frameTime = model::frame_time_from_index_get(*item, focus.frameIndex); } Reference TimelineContext::item_reference_get(int type, int id, int groupType, int groupId) @@ -158,7 +140,7 @@ namespace anm2ed::imgui return false; auto item = command_item_reference_get(targetDocument, lastReference); - if (!item || std::max(firstReference.frameIndex, lastReference.frameIndex) >= track_frames_count_get(*item)) + if (!item || std::max(firstReference.frameIndex, lastReference.frameIndex) >= model::track_frames_count_get(*item)) return false; auto [firstIndex, lastIndex] = std::minmax(firstReference.frameIndex, lastReference.frameIndex); @@ -232,7 +214,7 @@ namespace anm2ed::imgui void TimelineContext::reference_set_timeline_item_reference_for(Document& targetDocument, Reference itemReference) { if (itemReference.itemType == LAYER) - if (auto layer = targetDocument.anm2.element_get(ElementType::LAYER_ELEMENT, itemReference.itemID)) + if (auto layer = model::item_get(targetDocument.model.content.layers, itemReference.itemID)) targetDocument.spritesheet.reference = layer->spritesheetId; reference_set_item_reference_for(targetDocument, itemReference); } @@ -260,58 +242,42 @@ namespace anm2ed::imgui std::vector rows{}; if (!animation) return rows; - auto track_row_push = [&](const Element& item, int type, int index, int depth = 0) + auto is_track_shown = [&](const model::Track& track) + { return settings.timelineIsShowUnused || !track.frames.empty(); }; + // Layers are listed top-down in reverse file order; nulls in file order. + auto order_get = [](int count, bool isReversed) { - auto rootGroupType = item.groupId == -1 ? NONE : type; - rows.push_back({.type = type, - .id = anm2ed::track_id_get(item), - .index = index, - .groupId = item.groupId, - .rootGroupType = rootGroupType, - .rootGroupId = item.groupId, - .depth = depth}); - }; - auto group_row_push = [&](const Element& group, int type, int index) - { rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); }; - auto group_root_row_push = [&](const Element& group, int type) - { rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); }; - auto group_ids_get = [](const Element& container) - { - std::set result{}; - for (const auto& item : container.children) - if (item.type == ElementType::GROUP) result.insert(item.id); - return result; + std::vector order(count); + for (int i = 0; i < count; ++i) + order[i] = isReversed ? count - 1 - i : i; + return order; }; rows.push_back({.type = ROOT}); - - for (const auto& containerRow : TRACK_CONTAINERS) + for (auto type : {LAYER, NULL_}) { - auto container = child_first_get(*animation, containerRow.container); - if (!container) continue; - auto type = (int)containerRow.itemType; - auto isReversed = containerRow.itemType == ItemType::LAYER; - auto count = (int)container->children.size(); - auto index_get = [&](int i) { return isReversed ? count - 1 - i : i; }; - auto groupIds = group_ids_get(*container); - auto is_track_shown = [&](const Element& item) - { return item.type == containerRow.track && (settings.timelineIsShowUnused || !item.children.empty()); }; - - for (int i = 0; i < count; ++i) + auto& entries = model::animation_entries_get(*animation, type); + auto isReversed = type == LAYER; + for (auto index : order_get((int)entries.size(), isReversed)) { - auto index = index_get(i); - auto& item = container->children[index]; - if (item.type == ElementType::GROUP) + if (auto track = std::get_if(&entries[index])) { - group_row_push(item, type, index); - if (!item.isExpanded) continue; - group_root_row_push(item, type); - for (int j = 0; j < count; ++j) - if (auto& child = container->children[index_get(j)]; is_track_shown(child) && child.groupId == item.id) - track_row_push(child, type, index_get(j), 1); + if (is_track_shown(*track)) rows.push_back({.type = type, .id = track->id, .index = index}); + continue; } - else if (is_track_shown(item) && !groupIds.contains(item.groupId)) - track_row_push(item, type, index); + auto& group = std::get(entries[index]); + rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); + if (!group.isExpanded) continue; + rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); + for (auto trackIndex : order_get((int)group.tracks.size(), isReversed)) + if (auto& track = group.tracks[trackIndex]; is_track_shown(track)) + rows.push_back({.type = type, + .id = track.id, + .index = trackIndex, + .groupId = group.id, + .rootGroupType = type, + .rootGroupId = group.id, + .depth = 1}); } } @@ -425,7 +391,7 @@ namespace anm2ed::imgui else { if (row.type == LAYER) - if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, row.id)) + if (auto layer = model::item_get(model.content.layers, row.id)) document.spritesheet.reference = layer->spritesheetId; reference_set(row_item_reference_get(rowReference)); } diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp index 5c170ef..d00d2d9 100644 --- a/src/imgui/window/timeline/timeline.cpp +++ b/src/imgui/window/timeline/timeline.cpp @@ -8,14 +8,14 @@ namespace anm2ed::imgui TimelineContext::TimelineContext(TimelineState&& state, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) : TimelineState(std::move(state)), manager(manager), settings(settings), resources(resources), - clipboard(clipboard), document(*manager.get()), anm2(document.anm2), playback(document.playback), + clipboard(clipboard), document(*manager.get()), model(document.model), playback(document.playback), reference(document.reference_get()), region(document.region) { } void TimelineContext::update() { - animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); + animation = model.animation_get(reference.animationIndex); rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f; style = ImGui::GetStyle(); diff --git a/src/imgui/window/timeline/tracks.cpp b/src/imgui/window/timeline/tracks.cpp index cfb0865..a25ef2b 100644 --- a/src/imgui/window/timeline/tracks.cpp +++ b/src/imgui/window/timeline/tracks.cpp @@ -41,14 +41,10 @@ namespace anm2ed::imgui auto targetRow = row; auto targetAnimationIndex = reference.animationIndex; edit_push(EDIT_TOGGLE_GROUP_EXPANDED, - [=](Anm2& anm2) + [=](model::Model& model) { - auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, TYPE_CONTAINERS[targetRow.type]) : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, targetRow.id) : nullptr; - if (!group) return; - group->isExpanded = !group->isExpanded; + if (auto group = model.track_group_edit(targetAnimationIndex, targetRow.type, targetRow.id)) + group->isExpanded = !group->isExpanded; }); }; @@ -140,14 +136,10 @@ namespace anm2ed::imgui auto targetGroupId = group->id; auto targetVisible = !isGroupVisible; edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](Anm2& anm2) + [=](model::Model& model) { - auto animation = anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); - auto container = animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; - if (!container) return; - auto group = child_id_get(*container, ElementType::GROUP, targetGroupId); - if (!group) return; - group->isVisible = targetVisible; + if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetGroupId)) + group->isVisible = targetVisible; }); } auto visibleButtonMin = ImGui::GetItemRectMin(); @@ -167,7 +159,7 @@ namespace anm2ed::imgui ImGui::TextUnformatted(label.c_str()); ImGui::PopFont(); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); - auto groupItemsCount = group_items_count_get(type, group->id); + auto groupItemsCount = (int)group->tracks.size(); ImGui::TextUnformatted( std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); ImGui::EndTooltip(); @@ -209,13 +201,13 @@ namespace anm2ed::imgui { if (type == LAYER) { - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id); + auto layer = model::item_get(model.content.layers, id); if (!layer) return localize.get(TYPE_STRINGS[type]); return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(id, layer->name, layer->spritesheetId)); } if (type == NULL_) { - auto null = anm2.element_get(ElementType::NULL_ELEMENT, id); + auto null = model::item_get(model.content.nulls, id); if (!null) return localize.get(TYPE_STRINGS[type]); return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); } @@ -320,7 +312,7 @@ namespace anm2ed::imgui } case LAYER: { - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id); + auto layer = model::item_get(model.content.layers, id); if (!layer) break; ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); ImGui::TextUnformatted(layer->name.c_str()); @@ -338,7 +330,7 @@ namespace anm2ed::imgui } case NULL_: { - auto nullInfo = anm2.element_get(ElementType::NULL_ELEMENT, id); + auto nullInfo = model::item_get(model.content.nulls, id); if (!nullInfo) break; ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); ImGui::TextUnformatted(nullInfo->name.c_str()); @@ -404,9 +396,9 @@ namespace anm2ed::imgui auto targetGroupType = row.rootGroupType; auto targetGroupId = row.rootGroupId; edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](Anm2& anm2) + [=](model::Model& model) { - if (auto item = anm2.element_get( + if (auto item = model.track_edit( Reference{animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId})) item->isVisible = !item->isVisible; }); @@ -417,7 +409,7 @@ namespace anm2ed::imgui if (type == NULL_) { - if (auto null = anm2.element_get(ElementType::NULL_ELEMENT, id)) + if (auto null = model::item_get(model.content.nulls, id)) { auto& isShowRect = null->isShowRect; auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; @@ -428,12 +420,10 @@ namespace anm2ed::imgui { auto nullID = id; edit_push(EDIT_TOGGLE_NULL_RECT, - [=](Anm2& anm2) + [=](model::Model& model) { - auto nulls = anm2.element_get(ElementType::NULLS); - auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) : nullptr; - if (!null) return; - null->isShowRect = !null->isShowRect; + if (auto null = model::item_get(model.content.nulls, nullID)) + null->isShowRect = !null->isShowRect; }); } overlay_icon(resources.icon_id_get(rectIcon), iconTintCurrent, false); diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 4e2f8ed..a340502 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -38,53 +38,6 @@ namespace anm2ed::imgui bool is_drag_drop_active() { return ImGui::GetDragDropPayload() != nullptr; } - Element* window_container_get(const Window& window, Document& document) - { - return window.container_get ? window.container_get(document) : document.anm2.element_get(window.containerType); - } - - Element* window_element_get(const Window& window, Document& document, int key) - { - if (window.element_get) return window.element_get(document.anm2, key); - auto container = window_container_get(window, document); - return container ? child_id_get(*container, window.elementType, key) : nullptr; - } - - void window_element_apply_push(Window& window, Manager& manager, const Element& edited, int reference) - { - manager.command_push( - {manager.selected, [&window, edited, reference](Manager&, Document& document) - { - auto container = window_container_get(window, document); - auto target = - reference == -1 || !container ? nullptr : child_id_get(*container, window.elementType, reference); - if (!container || (reference != -1 && !target)) return; - document.edit_apply(reference == -1 ? window.addEdit : window.propertiesEdit, - [&](Anm2&) - { - auto changed = edited; - changed.type = window.elementType; - changed.tag = element_make(window.elementType).tag; - changed.id = reference == -1 - ? element_child_next_id_get(*container, window.elementType) - : reference; - if (target) - *target = changed; - else - { - auto insertIndex = window.insert_index_get ? window.insert_index_get(document) - : (int)container->children.size(); - container->children.insert(container->children.begin() + insertIndex, changed); - window.newElementId = changed.id; - } - auto& storage = window.storage_get(document); - storage.selection = {changed.id}; - storage.reference = changed.id; - if (window.row_select) window.row_select(window, document, changed.id); - }); - }}); - } - void window_command_push(Window& window, Manager& manager, Settings& settings, Clipboard& clipboard, const Window::Command& command) { @@ -94,19 +47,13 @@ namespace anm2ed::imgui { command(window, manager, settings, document, clipboard); }}); } - void window_rename_finish(Window& window, Manager& manager, int key, int count, const std::string& name) + void window_rename_finish(Window& window, Manager& manager, int key, const std::string& name) { - manager.command_push({manager.selected, [&window, key, count, name](Manager&, Document& document) + manager.command_push({manager.selected, [&window, key, name](Manager&, Document& document) { - auto element = window_element_get(window, document, key); - if (!element || element->name == name) return; - document.edit_apply(window.renameEdit, - [&](Anm2&) - { - element->name = name; - if (window.rename_finish) - window.rename_finish(document, *element, key, count); - }); + if (!window.rename_apply || window.name_get(document, key) == name) return; + document.edit_apply(window.renameEdit, [&](model::Model& model) + { window.rename_apply(document, model, key, name); }); }}); } @@ -114,50 +61,33 @@ namespace anm2ed::imgui { std::string clipboardText{}; for (auto key : window.storage_get(document).selection) - if (auto element = window_element_get(window, document, key)) clipboardText += element_to_string(*element); + clipboardText += window.copy_get(document, key); if (!clipboardText.empty()) clipboard.set(clipboardText); } void window_paste(Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { - if (clipboard.is_empty()) return; - auto& storage = window.storage_get(document); - auto container = window_container_get(window, document); - auto maxIdBefore = container ? element_child_max_id_get(*container, window.elementType) : -1; - auto pasted = document.anm2; + if (clipboard.is_empty() || !window.paste_apply) return; std::string errorString{}; - - if (!pasted.deserialize(window.elementType, clipboard.get(), true, &errorString, document.directory_get())) + auto key = -1; + document.edit_apply(window.pasteEdit, [&](model::Model& model) + { key = window.paste_apply(document, model, clipboard.get(), &errorString); }); + if (key == -1) { - toast_log(Level::ERROR, window.deserializeFailedToast, errorString); + if (!errorString.empty()) toast_log(Level::ERROR, window.deserializeFailedToast, errorString); return; } - - document.edit_apply(window.pasteEdit, - [&](Anm2&) - { - document.anm2 = std::move(pasted); - container = window_container_get(window, document); - auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; - if (maxIdAfter <= maxIdBefore) return; - window.newElementId = maxIdAfter; - storage.selection = {maxIdAfter}; - storage.reference = maxIdAfter; - if (window.row_select) window.row_select(window, document, maxIdAfter); - }); + auto& storage = window.storage_get(document); + window.newElementId = key; + storage.selection = {key}; + storage.reference = key; + if (window.row_select) window.row_select(window, document, key); } void window_remove_unused(Window& window, Manager&, Settings&, Document& document, Clipboard&) { - auto unused = document.anm2.element_unused(window.elementType); - auto container = window_container_get(window, document); - if (unused.empty() || !container) return; - document.edit_apply(window.removeUnusedEdit, - [&](Anm2&) - { - for (auto id : unused) - element_child_id_erase(*container, window.elementType, id); - }); + if (!window.unused_remove) return; + document.edit_apply(window.removeUnusedEdit, [&](model::Model& model) { window.unused_remove(document, model); }); } bool is_window_group_selected(const Window& window) @@ -358,31 +288,32 @@ namespace anm2ed::imgui if (window.scrollQueued == key) window.scrollQueued = -1; } - void window_tooltip_update(Window& window, Resources& resources, Document& document, const Element& element) + void window_tooltip_update(Window& window, Resources& resources, Document& document, int key) { if (!window.tooltip_draw) return; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); if (ImGui::BeginItemTooltip()) { - window.tooltip_draw(document, resources, element); + window.tooltip_draw(document, resources, key); ImGui::EndTooltip(); } ImGui::PopStyleVar(2); } - bool window_row_draw(Window& window, Manager& manager, Resources& resources, Document& document, Element& element, - int key, int index, int arrowSelectionId) + bool window_row_draw(Window& window, Manager& manager, Resources& resources, Document& document, int key, int index, + int arrowSelectionId) { auto& storage = window.storage_get(document); auto isSelected = storage.selection.contains(key) || arrowSelectionId == key; auto isReferenced = window_flag_has(window.flags, WINDOW_REFERENCE_ITALIC) && (storage.reference == key || arrowSelectionId == key); - auto font = window.row_font_get ? window.row_font_get(document, element, key) + auto font = window.row_font_get ? window.row_font_get(document, key) : isReferenced ? resource::font::ITALICS : resource::font::REGULAR; auto isFontPushed = font != resource::font::REGULAR; - auto label = window.row_label_get ? window.row_label_get(document, element) : element.name; + auto name = window.name_get ? window.name_get(document, key) : std::string{}; + auto label = window.row_label_get ? window.row_label_get(document, key) : name; ImGui::PushID(key); ImGui::SetNextItemSelectionUserData(index); @@ -401,16 +332,16 @@ namespace anm2ed::imgui auto isRenaming = window.renameId == key; auto renameLabel = std::format("###Document #{} Window #{} Element #{}", manager.selected, (int)window.elementType, key); - isActivated = selectable_input_text(label, renameLabel, isRenaming ? window.renameText : element.name, isSelected, + isActivated = selectable_input_text(label, renameLabel, isRenaming ? window.renameText : name, isSelected, ImGuiSelectableFlags_None, window.renameState); if (isActivated && window.renameState == RENAME_BEGIN) { window.renameId = key; - window.renameText = element.name; + window.renameText = name; } else if (isActivated && window.renameState == RENAME_FINISHED) { - if (isRenaming) window_rename_finish(window, manager, key, (int)window.order.size(), window.renameText); + if (isRenaming) window_rename_finish(window, manager, key, window.renameText); window.renameId = -1; window.renameText.clear(); } @@ -427,8 +358,8 @@ namespace anm2ed::imgui ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.properties_open) window.properties_open(manager, key); - auto isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, element, key); - window_tooltip_update(window, resources, document, element); + auto isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, key, index); + window_tooltip_update(window, resources, document, key); ImGui::PopID(); return isBreak; } @@ -463,16 +394,13 @@ namespace anm2ed::imgui } void window_cards_draw(Window& window, Manager& manager, Settings& settings, Resources& resources, - Clipboard& clipboard, Document& document, Element* container) + Clipboard& clipboard, Document& document) { auto& storage = window.storage_get(document); auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * window.cardLines); auto style = ImGui::GetStyle(); - window.order.clear(); - if (container) - for (auto& element : container->children) - if (element.type == window.elementType) window.order.push_back(element.id); + window.order = window.keys_get(document); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); auto arrowSelectionId = window_selection_start(window, document, window.order); @@ -480,8 +408,6 @@ namespace anm2ed::imgui for (int i = 0; i < (int)window.order.size(); i++) { auto id = window.order[i]; - auto element = child_id_get(*container, window.elementType, id); - if (!element) continue; ImGui::PushID(id); if (arrowSelectionId == id) @@ -500,9 +426,9 @@ namespace anm2ed::imgui auto cursorPos = ImGui::GetCursorPos(); auto isSelected = storage.selection.contains(id) || arrowSelectionId == id; auto isReferenced = id == storage.reference || arrowSelectionId == id; - auto image = window.card_image_get(document, resources, *element); + auto image = window.card_image_get(document, resources, id); auto tint = image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID; - auto label = window.row_label_get ? window.row_label_get(document, *element) : element->name; + auto label = window.row_label_get ? window.row_label_get(document, id) : window.name_get(document, id); ImGui::SetNextItemSelectionUserData(i); ImGui::SetNextItemStorageID(id); @@ -521,10 +447,10 @@ namespace anm2ed::imgui window.tooltipWindowPadding.x * TOOLTIP_PADDING_MULTIPLIER, 0), ImGuiCond_Appearing); - window_tooltip_update(window, resources, document, *element); + window_tooltip_update(window, resources, document, id); } - isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, *element, i); + isBreak = window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, id, i); auto aspectRatio = image.size.y != 0.0f ? image.size.x / image.size.y : 1.0f; auto imageSize = ImVec2(cardSize.y, cardSize.y); @@ -556,21 +482,10 @@ namespace anm2ed::imgui void window_list_draw(Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard, Document& document) { - std::vector elements{}; - window.order.clear(); - if (auto container = window_container_get(window, document)) - for (auto& element : container->children) - if (element.type == window.elementType) - { - window.order.push_back(window.element_key_get ? window.element_key_get(element, (int)elements.size()) - : element.id); - elements.push_back(&element); - } - + window.order = window.keys_get(document); auto arrowSelectionId = window_selection_start(window, document, window.order); - for (int i = 0; i < (int)elements.size(); ++i) - if (window_row_draw(window, manager, resources, document, *elements[i], window.order[i], i, arrowSelectionId)) - break; + for (int i = 0; i < (int)window.order.size(); ++i) + if (window_row_draw(window, manager, resources, document, window.order[i], i, arrowSelectionId)) break; window_selection_finish(window, manager, settings, clipboard, document, arrowSelectionId); } @@ -635,8 +550,7 @@ namespace anm2ed::imgui if (window.rows_update) window.rows_update(window, manager, settings, resources, clipboard, *document); else if (isCards) - window_cards_draw(window, manager, settings, resources, clipboard, *document, - window_container_get(window, *document)); + window_cards_draw(window, manager, settings, resources, clipboard, *document); else window_list_draw(window, manager, settings, resources, clipboard, *document); diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp index 58a3052..926c76d 100644 --- a/src/imgui/window/window.hpp +++ b/src/imgui/window/window.hpp @@ -9,6 +9,7 @@ #include "clipboard.hpp" #include "dialog.hpp" #include "manager.hpp" +#include "model/xml.hpp" #include "resources.hpp" #include "settings.hpp" #include "storage.hpp" @@ -78,17 +79,16 @@ namespace anm2ed::imgui struct Window { using StorageGet = std::function; - using ContainerGet = std::function; - using IndexGet = std::function; - using ElementGet = std::function; - using ElementKeyGet = std::function; - using RowLabelGet = std::function; - using RowFontGet = std::function; + using KeysGet = std::function(Document&)>; + using NameGet = std::function; + using RowFontGet = std::function; using RowSelect = std::function; - using RenameFinish = std::function; - using TooltipDraw = std::function; - using RowDragDropUpdate = std::function; - using CardImageGet = std::function; + using RenameApply = std::function; + using PasteApply = std::function; + using UnusedRemove = std::function; + using TooltipDraw = std::function; + using RowDragDropUpdate = std::function; + using CardImageGet = std::function; using PropertiesOpen = std::function; using Command = std::function; using IsEnabled = std::function; @@ -96,7 +96,6 @@ namespace anm2ed::imgui StringType title{}; bool Settings::* isOpen{}; - ElementType containerType{ElementType::UNKNOWN}; ElementType elementType{ElementType::UNKNOWN}; const char* childLabel{"##Window Child"}; std::map tooltips{}; @@ -123,21 +122,22 @@ namespace anm2ed::imgui std::set selection2{}; std::vector dragSelection{}; std::vector order{}; - Element editElement{}; + model::Region editRegion{}; Dialog* dialog{}; WindowFlags flags{WINDOW_COPY | WINDOW_PASTE}; bool isPreserveEditElementOnOpen{}; ImVec2 tooltipWindowPadding{}; ImVec2 tooltipItemSpacing{}; StorageGet storage_get{}; - ContainerGet container_get{}; - IndexGet insert_index_get{}; - ElementGet element_get{}; - ElementKeyGet element_key_get{}; - RowLabelGet row_label_get{}; + KeysGet keys_get{}; + NameGet name_get{}; + NameGet row_label_get{}; + NameGet copy_get{}; RowFontGet row_font_get{}; RowSelect row_select{}; - RenameFinish rename_finish{}; + RenameApply rename_apply{}; + PasteApply paste_apply{}; + UnusedRemove unused_remove{}; TooltipDraw tooltip_draw{}; RowDragDropUpdate row_drag_drop_update{}; CardImageGet card_image_get{}; @@ -176,17 +176,107 @@ namespace anm2ed::imgui inline constexpr ImVec4 CARD_TINT_VALID = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); bool is_drag_drop_active(); - Element* window_container_get(const Window&, Document&); - Element* window_element_get(const Window&, Document&, int); - void window_element_apply_push(Window&, Manager&, const Element&, int); void window_command_push(Window&, Manager&, Settings&, Clipboard&, const Window::Command&); int window_selection_start(Window&, Document&, const std::vector&); void window_selection_finish(Window&, Manager&, Settings&, Clipboard&, Document&, int); - bool window_row_draw(Window&, Manager&, Resources&, Document&, Element&, int, int, int); - void window_cards_draw(Window&, Manager&, Settings&, Resources&, Clipboard&, Document&, Element*); + bool window_row_draw(Window&, Manager&, Resources&, Document&, int, int, int); + void window_cards_draw(Window&, Manager&, Settings&, Resources&, Clipboard&, Document&); void window_tooltip_name_draw(Resources&, const std::string&); void window_tooltip_image_draw(const WindowCardImage&, const std::function&); void window_directory_open(Dialog&, Document&, const std::filesystem::path&); std::filesystem::path window_asset_path_get(Document&, const std::filesystem::path&); PopupButton window_popup_buttons_draw(Manager&, const char*, bool = true, StringType = BASIC_CANCEL); + + // Binds a window's generic list behavior (keys, names, copy/paste, remove unused) to a list of content items. + template + void window_items_bind(Window& window, std::function*(Document&, model::Model&)> items_get) + { + auto items_const_get = [items_get](Document& document) { return items_get(document, document.model); }; + window.keys_get = [items_const_get](Document& document) + { + std::vector keys{}; + if (auto items = items_const_get(document)) + for (const auto& item : *items) + keys.push_back(item.id); + return keys; + }; + window.copy_get = [items_const_get](Document& document, int key) + { + auto items = items_const_get(document); + auto item = items ? model::item_get(*items, key) : nullptr; + return item ? model::item_to_string(*item) : std::string{}; + }; + window.paste_apply = + [items_get](Document& document, model::Model& model, const std::string& text, std::string* errorString) + { + auto items = items_get(document, model); + auto pasted = model::items_from_string(text, errorString); + if (!items || pasted.empty()) return -1; + for (auto& item : pasted) + { + item.id = model::item_next_id_get(*items); + items->push_back(std::move(item)); + } + return items->back().id; + }; + if constexpr (requires(Item item) { item.name; }) + { + window.name_get = [items_const_get](Document& document, int key) + { + auto items = items_const_get(document); + auto item = items ? model::item_get(*items, key) : nullptr; + return item ? item->name : std::string{}; + }; + window.rename_apply = [items_get](Document& document, model::Model& model, int key, const std::string& name) + { + auto items = items_get(document, model); + if (auto item = items ? model::item_get(*items, key) : nullptr) item->name = name; + }; + } + window.unused_remove = [items_get, type = window.elementType](Document& document, model::Model& model) + { + auto unused = model.unused_get(type); + if (auto items = items_get(document, model)) + std::erase_if(*items, [&](const Item& item) { return unused.contains(item.id); }); + }; + } + + // Adds `edited` as a new item (reference -1) or replaces the item with that id, then selects it. + template + void window_item_apply_push(Window& window, Manager& manager, Item edited, int reference, + std::function*(Document&, model::Model&)> items_get, + int insertIndex = -1) + { + manager.command_push( + {manager.selected, [&window, edited, reference, items_get, insertIndex](Manager&, Document& document) + { + document.edit_apply(reference == -1 ? window.addEdit : window.propertiesEdit, + [&](model::Model& model) + { + auto items = items_get(document, model); + if (!items) return; + auto target = reference == -1 ? nullptr : model::item_get(*items, reference); + if (reference != -1 && !target) return; + auto changed = edited; + changed.id = reference == -1 ? model::item_next_id_get(*items) : reference; + if (target) + { + changed.uid = target->uid; + *target = changed; + } + else + { + changed.uid = util::uid_next(); + auto position = + insertIndex < 0 ? (int)items->size() : std::min(insertIndex, (int)items->size()); + items->insert(items->begin() + position, changed); + window.newElementId = changed.id; + } + auto& storage = window.storage_get(document); + storage.selection = {changed.id}; + storage.reference = changed.id; + if (window.row_select) window.row_select(window, document, changed.id); + }); + }}); + } } diff --git a/src/imgui/wizard/about.cpp b/src/imgui/wizard/about.cpp index 0006f04..b3bf8f6 100644 --- a/src/imgui/wizard/about.cpp +++ b/src/imgui/wizard/about.cpp @@ -9,6 +9,8 @@ #include "log.hpp" #include "math.hpp" +#include "model/frames.hpp" +#include "model/xml.hpp" #include "strings.hpp" #include "util/imgui/draw.hpp" @@ -114,26 +116,19 @@ namespace anm2ed::imgui::wizard }; static constexpr auto CREDIT_COUNT = (int)(sizeof(CREDITS) / sizeof(About::Credit)); - const Element* friend_animation_get(const About::FriendState& state) + const model::Animation* friend_animation_get(const About::FriendState& state) { - auto animations = state.anm2.element_get(ElementType::ANIMATIONS); - if (!animations) return nullptr; - - if (!animations->defaultAnimation.empty()) - for (const auto& child : animations->children) - if (child.type == ElementType::ANIMATION && child.name == animations->defaultAnimation) return &child; - - for (const auto& child : animations->children) - if (child.type == ElementType::ANIMATION) return &child; - - return nullptr; + auto animations = state.model.animations_get(); + for (auto [index, animation] : animations) + if (animation->name == state.model.animations.defaultAnimation) return animation; + return animations.empty() ? nullptr : animations.front().second; } void friend_state_load(About::FriendState& state, const resource::friends::Info& info) { if (!state.canvas) state.canvas = std::make_unique(vec2(1.0f, 1.0f)); - state.anm2 = Anm2{}; + state.model = model::Model{}; state.textures.clear(); state.rect = vec4(-1.0f); state.time = 0.0f; @@ -141,19 +136,16 @@ namespace anm2ed::imgui::wizard state.isLoaded = false; std::string errorString{}; - if (!state.anm2.load_string(info.anm2, &errorString)) + if (!model::model_load_string(state.model, info.anm2, &errorString)) { logger.error(std::format("Unable to load friend animation {}: {}", info.name, errorString)); return; } - if (auto anm2Info = state.anm2.element_get(ElementType::INFO)) - if (anm2Info->fps > 0) state.fps = (float)anm2Info->fps; + if (state.model.info.fps > 0) state.fps = (float)state.model.info.fps; - if (auto spritesheets = state.anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) - state.textures[spritesheet.id] = resource::Image(info.png, info.pngSize); + for (auto& spritesheet : state.model.content.spritesheets) + state.textures[spritesheet.id] = resource::Image(info.png, info.pngSize); auto animation = friend_animation_get(state); if (!animation) @@ -162,7 +154,7 @@ namespace anm2ed::imgui::wizard return; } - state.rect = state.anm2.animation_rect(*animation, true); + state.rect = model::animation_rect(state.model, *animation, true); state.isLoaded = state.rect != vec4(-1.0f) && !state.textures.empty(); } @@ -185,24 +177,17 @@ namespace anm2ed::imgui::wizard } void friend_layer_draw(About::FriendState& state, Resources& resources, const mat4& baseTransform, - const Element& layerAnimation, const Element& rootFrame) + const model::Track& layerAnimation, const model::Frame& rootFrame) { - if (layerAnimation.type == ElementType::GROUP) - { - for (auto& child : layerAnimation.children) - friend_layer_draw(state, resources, baseTransform, child, rootFrame); - return; - } + if (!layerAnimation.isVisible) return; - if (layerAnimation.type != ElementType::LAYER_ANIMATION || !layerAnimation.isVisible) return; - - auto layer = state.anm2.element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); + auto layer = model::item_get(state.model.content.layers, layerAnimation.id); if (!layer) return; auto textureIt = state.textures.find(layer->spritesheetId); if (textureIt == state.textures.end() || !textureIt->second.is_valid()) return; - auto frame = state.anm2.frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, state.time)); + auto frame = state.model.frame_effective(layerAnimation.id, model::frame_generate(layerAnimation, state.time)); if (!frame.isVisible || frame.size == vec2()) return; auto& texture = textureIt->second; @@ -248,17 +233,12 @@ namespace anm2ed::imgui::wizard state.canvas->set_to_rect(zoom, pan, rect); auto transform = state.canvas->transform_get(zoom, pan); - Element rootFrame{}; - if (auto root = animation_item_get(*animation, ItemType::ROOT)) - { - rootFrame = frame_generate(*root, state.time); - transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), - rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); - } + auto rootFrame = model::frame_generate(animation->root, state.time); + transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); - if (auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) - for (auto& layerAnimation : layerAnimations->children) - friend_layer_draw(state, resources, transform, layerAnimation, rootFrame); + model::tracks_each(animation->layers, [&](const model::Track& layerAnimation, auto*) + { friend_layer_draw(state, resources, transform, layerAnimation, rootFrame); }); state.canvas->unbind(); } diff --git a/src/imgui/wizard/about.hpp b/src/imgui/wizard/about.hpp index b477387..2022f2f 100644 --- a/src/imgui/wizard/about.hpp +++ b/src/imgui/wizard/about.hpp @@ -5,8 +5,8 @@ #include #include -#include "../../anm2/anm2.hpp" #include "../../canvas.hpp" +#include "../../model/model.hpp" #include "../../resource/friends.hpp" #include "../../resources.hpp" @@ -36,7 +36,7 @@ namespace anm2ed::imgui::wizard struct FriendState { - Anm2 anm2{}; + model::Model model{}; std::unique_ptr canvas{}; std::unordered_map textures{}; glm::vec4 rect{-1.0f}; diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index aeff3ef..c20dc26 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -257,8 +257,8 @@ namespace anm2ed::imgui::wizard targets.references = {selectedItemReferences.begin(), selectedItemReferences.end()}; else targets.animations = queuedAnimations; - document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](Anm2& anm2) - { return edit::frames_change_apply(anm2, targets, frameChange, changeType); }); + document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](model::Model& model) + { return edit::frames_change_apply(model, targets, frameChange, changeType); }); }}); isChanged = true; }; diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index 685435f..ed0c492 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -1,6 +1,7 @@ #include "generate_animation_from_grid.hpp" #include "math.hpp" +#include "model/frames.hpp" #include "types.hpp" #include "util/imgui/draw.hpp" #include "util/imgui/input.hpp" @@ -20,7 +21,7 @@ namespace anm2ed::imgui::wizard { isEnd = false; - auto& anm2 = document.anm2; + auto& model = document.model; auto reference = document.reference_get(); auto& startPosition = settings.generateStartPosition; auto& size = settings.generateSize; @@ -86,16 +87,16 @@ namespace anm2ed::imgui::wizard if (!layerReferences.empty()) { - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, previewReference.itemID); + auto layer = model::item_get(model.content.layers, previewReference.itemID); auto sourceTexture = layer ? document.texture_get(layer->spritesheetId) : nullptr; if (sourceTexture && sourceTexture->is_valid()) { - auto previewTrack = element_make(ElementType::LAYER_ANIMATION); - frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); + model::Track previewTrack{}; + model::frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); - auto length = std::max(track_length_get(previewTrack), FRAME_DURATION_MIN); + auto length = std::max(model::track_length_get(previewTrack), FRAME_DURATION_MIN); auto sampleTime = std::min(time * (float)length, (float)length - 0.001f); - auto frame = frame_generate(previewTrack, sampleTime); + auto frame = model::frame_generate(previewTrack, sampleTime); auto textureSize = vec2(sourceTexture->size); if (textureSize.x > 0.0f && textureSize.y > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) @@ -150,8 +151,8 @@ namespace anm2ed::imgui::wizard { edit::GridOptions options{queuedStartPosition, queuedSize, queuedPivot, queuedColumns, queuedCount, queuedDelay, queuedIsMakeRegions, queuedRegionNameFormat}; - document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](Anm2& anm2) - { return edit::animation_grid_generate(anm2, queuedLayerReferences, options); }); + document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](model::Model& model) + { return edit::animation_grid_generate(model, queuedLayerReferences, options); }); }}); isEnd = true; } diff --git a/src/imgui/wizard/render_animation.cpp b/src/imgui/wizard/render_animation.cpp index 1409fcb..56f10b6 100644 --- a/src/imgui/wizard/render_animation.cpp +++ b/src/imgui/wizard/render_animation.cpp @@ -21,7 +21,7 @@ namespace anm2ed::imgui::wizard { void RenderAnimation::range_to_animation_set(Manager& manager, Document& document) { - if (auto animation = document.anm2.element_get(ElementType::ANIMATION, document.reference_get().animationIndex)) + if (auto animation = document.model.animation_get(document.reference_get().animationIndex)) { manager.recordingStart = 0; manager.recordingEnd = animation->frameNum - 1; @@ -42,15 +42,12 @@ namespace anm2ed::imgui::wizard }); if (!frameReferences.empty()) { - auto itemReference = reference; - itemReference.frameIndex = -1; - if (auto item = document.anm2.element_get(itemReference)) + if (auto item = document.model.track_get(reference)) { int duration{}; int frameIndex{}; - for (auto& frame : item->children) + for (auto& frame : item->frames) { - if (frame.type != ElementType::FRAME && frame.type != ElementType::TRIGGER) continue; if (frameIndex == frameReferences.begin()->frameIndex) manager.recordingStart = duration; if (frameIndex == frameReferences.rbegin()->frameIndex) manager.recordingEnd = duration + frame.duration - 1; @@ -72,7 +69,7 @@ namespace anm2ed::imgui::wizard { isEnd = false; - auto animation = document.anm2.element_get(ElementType::ANIMATION, document.reference_get().animationIndex); + auto animation = document.model.animation_get(document.reference_get().animationIndex); if (!animation) return; auto& ffmpegPath = settings.renderFFmpegPath; @@ -94,8 +91,7 @@ namespace anm2ed::imgui::wizard auto frameMax = animationFrameNum - 1; start = std::clamp(start, 0, frameMax); end = std::clamp(end, start, frameMax); - auto info = element_first_get(document.anm2.root, ElementType::INFO); - auto animationFps = std::max(info ? info->fps : 30, 1); + auto animationFps = std::max(document.model.info.fps, 1); if (renderFpsMode < render::FPS_ANIMATION || renderFpsMode >= render::FPS_COUNT) renderFpsMode = render::FPS_ANIMATION; auto renderFps = render::fps_get(renderFpsMode, animationFps, settings.playbackTickRate); diff --git a/src/manager.cpp b/src/manager.cpp index 7db84f3..d735c19 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -256,12 +256,17 @@ namespace anm2ed void Manager::item_properties_open(ElementType type, int id) { auto document = get(); - auto row = track_container_get(type); - auto element = id == -1 || !document ? nullptr : document->anm2.element_get(type, id); - if (!document || !row || (id != -1 && !element)) return; - itemEdit = element ? *element : element_make(type); - (type == ElementType::LAYER_ELEMENT ? document->layer : document->null).reference = id; - itemPropertiesPopups[row - TRACK_CONTAINERS].open(); + if (!document || (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT)) return; + auto isLayer = type == ElementType::LAYER_ELEMENT; + auto& content = document->model.content; + auto layer = isLayer ? model::item_get(content.layers, id) : nullptr; + auto null = isLayer ? nullptr : model::item_get(content.nulls, id); + if (id != -1 && !layer && !null) return; + itemEdit = layer ? ItemEdit{layer->name, layer->spritesheetId, false} + : null ? ItemEdit{null->name, 0, null->isShowRect} + : ItemEdit{}; + (isLayer ? document->layer : document->null).reference = id; + itemPropertiesPopups[isLayer ? 0 : 1].open(); } void Manager::recent_files_trim() diff --git a/src/manager.hpp b/src/manager.hpp index f00fb21..9106061 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -62,12 +62,17 @@ namespace anm2ed std::filesystem::path spritesheetDragDropPath{}; bool isSpritesheetDragDrop{}; - Element itemEdit{}; - imgui::PopupHelper itemPropertiesPopups[std::size(TRACK_CONTAINERS)]{ + struct ItemEdit + { + std::string name{}; + int spritesheetId{}; + bool isShowRect{}; + } itemEdit{}; + imgui::PopupHelper itemPropertiesPopups[2]{ imgui::PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT), imgui::PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT)}; - Element makeRegion{element_make(ElementType::REGION)}; + model::Region makeRegion{}; int makeRegionSpritesheetId{-1}; bool isMakeRegionRequested{}; diff --git a/src/model/common.hpp b/src/model/common.hpp new file mode 100644 index 0000000..631d883 --- /dev/null +++ b/src/model/common.hpp @@ -0,0 +1,314 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include "icon.hpp" +#include "strings.hpp" +#include "types.hpp" + +#define ANM2_ELEMENT_TYPES \ + X(UNKNOWN, "", UNKNOWN) \ + X(ANIMATED_ACTOR, "AnimatedActor", UNKNOWN) \ + X(INFO, "Info", UNKNOWN) \ + X(CONTENT, "Content", UNKNOWN) \ + X(SPRITESHEETS, "Spritesheets", UNKNOWN) \ + X(SPRITESHEET, "Spritesheet", SPRITESHEETS) \ + X(SHADERS, "Shaders", UNKNOWN) \ + X(SHADER, "Shader", SHADERS) \ + X(UNIFORM, "Uniform", UNKNOWN) \ + X(COMPONENT, "Component", UNKNOWN) \ + X(REGION, "Region", UNKNOWN) \ + X(LAYERS, "Layers", UNKNOWN) \ + X(LAYER_ELEMENT, "Layer", LAYERS) \ + X(NULLS, "Nulls", UNKNOWN) \ + X(NULL_ELEMENT, "Null", NULLS) \ + X(EVENTS, "Events", UNKNOWN) \ + X(EVENT_ELEMENT, "Event", EVENTS) \ + X(SOUNDS, "Sounds", UNKNOWN) \ + X(SOUND_ELEMENT, "Sound", SOUNDS) \ + X(ANIMATIONS, "Animations", UNKNOWN) \ + X(ANIMATION, "Animation", ANIMATIONS) \ + X(ROOT_ANIMATION, "RootAnimation", UNKNOWN) \ + X(LAYER_ANIMATIONS, "LayerAnimations", UNKNOWN) \ + X(LAYER_ANIMATION_GROUPS, "LayerAnimationGroups", UNKNOWN) \ + X(LAYER_ANIMATION, "LayerAnimation", UNKNOWN) \ + X(NULL_ANIMATIONS, "NullAnimations", UNKNOWN) \ + X(NULL_ANIMATION_GROUPS, "NullAnimationGroups", UNKNOWN) \ + X(NULL_ANIMATION, "NullAnimation", UNKNOWN) \ + X(GROUP, "Group", UNKNOWN) \ + X(TRIGGERS, "Triggers", UNKNOWN) \ + X(FRAME, "Frame", UNKNOWN) \ + X(TRIGGER, "Trigger", UNKNOWN) + +namespace anm2ed +{ + enum class ElementType + { +#define X(symbol, tag, container) symbol, + ANM2_ELEMENT_TYPES +#undef X + COUNT + }; + + inline constexpr ElementType ELEMENT_CONTAINERS[] = { +#define X(symbol, tag, container) ElementType::container, + ANM2_ELEMENT_TYPES +#undef X + }; + + enum class Interpolation + { + NONE, + LINEAR, + EASE_IN, + EASE_OUT, + EASE_IN_OUT, + COUNT + }; + + enum class Origin + { + CUSTOM, + TOP_LEFT, + CENTER, + COUNT + }; + + enum class ItemType + { + NONE, + ROOT, + LAYER, + NULL_, + TRIGGER, + COUNT + }; + + inline constexpr int NONE = (int)ItemType::NONE; + inline constexpr int ROOT = (int)ItemType::ROOT; + inline constexpr int LAYER = (int)ItemType::LAYER; + inline constexpr int NULL_ = (int)ItemType::NULL_; + inline constexpr int TRIGGER = (int)ItemType::TRIGGER; + + inline constexpr int FRAME_DURATION_MIN = 1; + inline constexpr int FRAME_DURATION_MAX = 1000000; + inline constexpr int FRAME_NUM_MIN = 1; + inline constexpr int FRAME_NUM_MAX = FRAME_DURATION_MAX; + inline constexpr int FPS_MIN = 1; + inline constexpr int FPS_MAX = 120; + + enum class SpritesheetMergeOrigin + { + APPEND_RIGHT, + APPEND_BOTTOM, + COUNT + }; + + inline constexpr int APPEND_RIGHT = (int)SpritesheetMergeOrigin::APPEND_RIGHT; + inline constexpr int APPEND_BOTTOM = (int)SpritesheetMergeOrigin::APPEND_BOTTOM; + + inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); + inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); + inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); + + inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); + inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); + inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); + + inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); + inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); + inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); + + inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); + inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); + inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); + +#define ANM2_ITEM_TYPES \ + X(NONE, STRING_UNDEFINED, "", resource::icon::NONE, glm::vec4(), glm::vec4(), glm::vec4(), UNKNOWN, UNKNOWN) \ + X(ROOT, BASIC_ROOT, "RootAnimation", resource::icon::ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED, \ + ROOT_ANIMATION, UNKNOWN) \ + X(LAYER, BASIC_LAYER_ANIMATION, "LayerAnimation", resource::icon::LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, \ + LAYER_COLOR_HOVERED, LAYER_ANIMATION, LAYER_ANIMATIONS) \ + X(NULL_, BASIC_NULL_ANIMATION, "NullAnimation", resource::icon::NULL_, NULL_COLOR, NULL_COLOR_ACTIVE, \ + NULL_COLOR_HOVERED, NULL_ANIMATION, NULL_ANIMATIONS) \ + X(TRIGGER, BASIC_TRIGGERS, "Triggers", resource::icon::TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, \ + TRIGGER_COLOR_HOVERED, TRIGGERS, UNKNOWN) + + constexpr StringType TYPE_STRINGS[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) string, + ANM2_ITEM_TYPES +#undef X + }; + + constexpr const char* TYPE_ITEM_STRINGS[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) itemString, + ANM2_ITEM_TYPES +#undef X + }; + + constexpr resource::icon::Type TYPE_ICONS[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) icon, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) color, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) colorActive, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR_HOVERED[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) colorHovered, + ANM2_ITEM_TYPES +#undef X + }; + + inline constexpr ElementType TYPE_TRACKS[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) ElementType::track, + ANM2_ITEM_TYPES +#undef X + }; + + inline constexpr ElementType TYPE_CONTAINERS[] = { +#define X(symbol, string, itemString, icon, color, colorActive, colorHovered, track, container) ElementType::container, + ANM2_ITEM_TYPES +#undef X + }; + + enum class RegionFrameMapping + { + PRESERVE, + SET + }; + + enum FileMergePreset + { + FILE_MERGE_PRESET_MERGE_BY_NAME, + FILE_MERGE_PRESET_APPEND_AS_NEW, + FILE_MERGE_PRESET_REPLACE_MATCHING, + FILE_MERGE_PRESET_COUNT + }; + + enum class ChangeType + { + ADJUST, + ADD, + SUBTRACT, + MULTIPLY, + DIVIDE + }; + + enum Flag + { + SERIALIZE_GROUPS = 1 << 0, + SERIALIZE_REGIONS = 1 << 1, + SERIALIZE_SOUNDS = 1 << 2, + SERIALIZE_REDUNDANT_FRAME_REGION_VALUES = 1 << 3, + SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES = 1 << 4, + SERIALIZE_BAKE_GROUP_FRAMES = 1 << 5, + SERIALIZE_NESTED_GROUPS = 1 << 6, + SERIALIZE_EXTENSIONS = 1 << 7, + SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES = 1 << 8 + }; + + using Flags = int; + + constexpr bool has_flag(Flags flags, Flag flag) { return (flags & flag) != 0; } + constexpr Flags SERIALIZE_EDITOR_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | + SERIALIZE_REDUNDANT_FRAME_REGION_VALUES | SERIALIZE_EXTENSIONS; + constexpr Flags SERIALIZE_DEFAULT = + SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES | SERIALIZE_BAKE_GROUP_FRAMES; + constexpr Flags SERIALIZE_ISAAC_DEFAULT = SERIALIZE_BAKE_GROUP_FRAMES | SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES; + constexpr Flags SERIALIZE_ANM2ED_DEFAULT = + SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; + + struct Options + { + Flags flags{SERIALIZE_DEFAULT}; + bool isExtendedFormat{}; + }; + +#define FRAME_CHANGE_SCALARS \ + X(cropX, crop.x, true, false, changeIsCropX, changeCrop.x) \ + X(cropY, crop.y, true, false, changeIsCropY, changeCrop.y) \ + X(sizeX, size.x, true, false, changeIsSizeX, changeSize.x) \ + X(sizeY, size.y, true, false, changeIsSizeY, changeSize.y) \ + X(pivotX, pivot.x, true, false, changeIsPivotX, changePivot.x) \ + X(pivotY, pivot.y, true, false, changeIsPivotY, changePivot.y) \ + X(positionX, position.x, false, false, changeIsPositionX, changePosition.x) \ + X(positionY, position.y, false, false, changeIsPositionY, changePosition.y) \ + X(scaleX, scale.x, false, false, changeIsScaleX, changeScale.x) \ + X(scaleY, scale.y, false, false, changeIsScaleY, changeScale.y) \ + X(shearX, shear.x, false, false, changeIsShearX, changeShear.x) \ + X(shearY, shear.y, false, false, changeIsShearY, changeShear.y) \ + X(rotation, rotation, false, false, changeIsRotation, changeRotation) \ + X(tintR, tint.r, false, true, changeIsTintR, changeTint.r) \ + X(tintG, tint.g, false, true, changeIsTintG, changeTint.g) \ + X(tintB, tint.b, false, true, changeIsTintB, changeTint.b) \ + X(tintA, tint.a, false, true, changeIsTintA, changeTint.a) \ + X(colorOffsetR, colorOffset.r, false, true, changeIsColorOffsetR, changeColorOffset.r) \ + X(colorOffsetG, colorOffset.g, false, true, changeIsColorOffsetG, changeColorOffset.g) \ + X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) + + struct FrameChange + { + std::optional regionId{}; +#define X(name, member, isLayerOnly, isColor, isEnabled, value) std::optional name{}; + FRAME_CHANGE_SCALARS +#undef X + std::optional duration{}; + std::optional shaderId{}; + std::optional isVisible{}; + std::optional interpolation{}; + std::optional isFlipX{}; + std::optional isFlipY{}; + }; + + inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, + BASIC_EASE_IN_OUT}; + + struct Reference + { + int animationIndex{-1}; + int itemType{(int)ItemType::NONE}; + int itemID{-1}; + int frameIndex{-1}; + int groupType{(int)ItemType::NONE}; + int groupId{-1}; + + auto operator<=>(const Reference&) const = default; + }; + + // A Reference expressed by runtime uids, so it survives inserts, deletes and moves. + struct Handle + { + std::uint64_t animation{}; + std::uint64_t item{}; + std::uint64_t frame{}; + + auto operator<=>(const Handle&) const = default; + }; + + inline float interpolation_factor(Interpolation interpolation, float value) + { + value = glm::clamp(value, 0.0f, 1.0f); + if (interpolation == Interpolation::LINEAR) return value; + if (interpolation == Interpolation::EASE_IN) return value * value; + if (interpolation == Interpolation::EASE_OUT) return 1.0f - ((1.0f - value) * (1.0f - value)); + if (interpolation == Interpolation::EASE_IN_OUT) + return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f); + return 0.0f; + } +} diff --git a/src/model/frames.cpp b/src/model/frames.cpp new file mode 100644 index 0000000..00ddcbe --- /dev/null +++ b/src/model/frames.cpp @@ -0,0 +1,244 @@ +#include "frames.hpp" + +#include +#include + +#include "math.hpp" + +using namespace anm2ed::util; + +namespace anm2ed::model +{ + void frame_mix(Frame& frame, const Frame& next, float amount) + { + frame.rotation = glm::mix(frame.rotation, next.rotation, amount); + frame.position = glm::mix(frame.position, next.position, amount); + frame.scale = glm::mix(frame.scale, next.scale, amount); + frame.shear = glm::mix(frame.shear, next.shear, amount); + frame.colorOffset = glm::mix(frame.colorOffset, next.colorOffset, amount); + frame.tint = glm::mix(frame.tint, next.tint, amount); + } + + // Splits an interpolated frame into uninterpolated frames of at most `interval`; the first keeps the frame's uid. + std::vector frame_bake_split(const Frame& original, const Frame& next, int interval, bool isRoundScale, + bool isRoundRotation) + { + auto total = std::max(original.duration, FRAME_DURATION_MIN); + interval = std::max(interval, FRAME_DURATION_MIN); + std::vector frames{}; + for (int duration = 0; duration < total; duration += interval) + { + auto& baked = frames.emplace_back(duration == 0 ? original : frame_clone(original)); + frame_mix(baked, next, interpolation_factor(original.interpolation, (float)duration / total)); + baked.duration = std::min(interval, total - duration); + baked.interpolation = Interpolation::NONE; + if (isRoundScale) baked.scale = glm::round(baked.scale); + if (isRoundRotation) baked.rotation = std::round(baked.rotation); + } + return frames; + } + + glm::mat4 frame_parent_model_get(const Frame& frame) + { + return math::quad_model_parent_get(frame.position, {}, math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); + } + + // The track's state at a time: the frame playing then, mixed toward the next one when interpolated. A trigger is + // returned only on its exact frame; otherwise the result is invisible. + Frame frame_generate(const Track& track, float time) + { + Frame frame{}; + frame.isVisible = false; + if (track.frames.empty()) return frame; + time = std::max(time, 0.0f); + + if (track.type == ItemType::TRIGGER) + { + for (const auto& trigger : track.frames) + if ((int)time == trigger.atFrame) return trigger; + return frame; + } + + const Frame* next{}; + int durationCurrent{}; + int durationNext{}; + for (int i = 0; i < (int)track.frames.size(); ++i) + { + frame = track.frames[i]; + durationNext += frame.duration; + if (time >= durationCurrent && time < durationNext) + { + if (i + 1 < (int)track.frames.size()) next = &track.frames[i + 1]; + break; + } + durationCurrent += frame.duration; + } + + if (frame.interpolation != Interpolation::NONE && next && frame.duration > 1) + frame_mix(frame, *next, + interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent))); + return frame; + } + + int frame_index_from_at_frame_get(const Track& track, int atFrame) + { + for (int i = 0; i < (int)track.frames.size(); ++i) + if (track.frames[i].atFrame == atFrame) return i; + return -1; + } + + int frame_index_from_time_get(const Track& track, float time) + { + if (track.type == ItemType::TRIGGER) return frame_index_from_at_frame_get(track, (int)time); + if (track.frames.empty()) return -1; + if (time <= 0.0f) return 0; + + float duration{}; + for (int i = 0; i < (int)track.frames.size(); ++i) + { + duration += track.frames[i].duration; + if (time < duration) return i; + } + return (int)track.frames.size() - 1; + } + + float frame_time_from_index_get(const Track& track, int index) + { + if (index < 0 || index >= (int)track.frames.size()) return 0.0f; + if (track.type == ItemType::TRIGGER) return (float)track.frames[index].atFrame; + float time{}; + for (int i = 0; i < index; ++i) + time += track.frames[i].duration; + return time; + } + + void frame_bake(Track& track, int index, int interval, bool isRoundScale, bool isRoundRotation) + { + if (index < 0 || index >= (int)track.frames.size()) return; + auto original = track.frames[index]; + if (original.duration <= FRAME_DURATION_MIN) + { + track.frames[index].interpolation = Interpolation::NONE; + return; + } + + auto next = index + 1 < (int)track.frames.size() ? track.frames[index + 1] : original; + auto baked = frame_bake_split(original, next, interval, isRoundScale, isRoundRotation); + track.frames.erase(track.frames.begin() + index); + track.frames.insert(track.frames.begin() + index, baked.begin(), baked.end()); + } + + void frames_generate_from_grid(Track& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot, int columns, + int count, int duration) + { + for (int i = 0; i < count; ++i) + { + auto& frame = track.frames.emplace_back(); + frame.duration = duration; + frame.pivot = pivot; + frame.size = size; + frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns)); + } + } + + void frames_sort_by_at_frame(Track& track) + { + std::stable_sort(track.frames.begin(), track.frames.end(), + [](const Frame& a, const Frame& b) { return a.atFrame < b.atFrame; }); + } + + void frames_change(Track& track, FrameChange change, ItemType itemType, ChangeType changeType, + const std::set& selection) + { + auto apply = [&](auto& target, const auto& optionalValue) + { + if (!optionalValue) return; + auto value = *optionalValue; + if (changeType == ChangeType::ADJUST) target = value; + if (changeType == ChangeType::ADD) target += value; + if (changeType == ChangeType::SUBTRACT) target -= value; + if (changeType == ChangeType::MULTIPLY) target *= value; + if (changeType == ChangeType::DIVIDE && value != decltype(value){}) target /= value; + }; + + for (auto index : selection) + { + if (index < 0 || index >= (int)track.frames.size()) continue; + auto& frame = track.frames[index]; + if (change.isVisible) frame.isVisible = *change.isVisible; + if (change.interpolation) frame.interpolation = *change.interpolation; + if (change.isFlipX) frame.scale.x = -frame.scale.x; + if (change.isFlipY) frame.scale.y = -frame.scale.y; + + apply(frame.duration, change.duration); + if (change.duration) frame.duration = std::max(FRAME_DURATION_MIN, frame.duration); + if (itemType == ItemType::LAYER && change.regionId) frame.regionId = *change.regionId; + if (itemType == ItemType::LAYER && change.shaderId) frame.shaderId = *change.shaderId; +#define X(name, member, isLayerOnly, isColor, isEnabled, value) \ + if (!isLayerOnly || itemType == ItemType::LAYER) apply(frame.member, change.name); + FRAME_CHANGE_SCALARS +#undef X + } + } + + // Bakes every ease-in/ease-out frame (not linear ones) in every track into single-step frames. + void special_interpolated_frames_bake(Model& model, int interval, bool isRoundScale, bool isRoundRotation) + { + for (int i = 0; i < model.animations_count_get(); ++i) + animation_tracks_each(*model.animation_edit(i), + [&](Track& track) + { + if (track.type == ItemType::TRIGGER) return; + for (int index = (int)track.frames.size() - 1; index >= 0; --index) + { + auto interpolation = track.frames[index].interpolation; + if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) + continue; + frame_bake(track, index, interval, isRoundScale, isRoundRotation); + } + }); + } + + // Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn. + glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform) + { + constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}}; + glm::vec2 min{std::numeric_limits::infinity()}; + glm::vec2 max{-std::numeric_limits::infinity()}; + bool isAny{}; + + for (float t = 0.0f; t < (float)animation.frameNum; t += 1.0f) + { + glm::mat4 transform(1.0f); + if (isRootTransform) transform *= frame_parent_model_get(frame_generate(animation.root, t)); + + tracks_each(animation.layers, + [&](const Track& track, const TrackGroup* group) + { + if (!track.isVisible || (group && !group->isVisible)) return; + auto itemTransform = transform; + if (isRootTransform && group) + itemTransform *= frame_parent_model_get(frame_generate(group->root, t)); + + auto frame = model.frame_effective(track.id, frame_generate(track, t)); + if (frame.size == glm::vec2() || !frame.isVisible) return; + + auto layerTransform = + itemTransform * math::quad_model_get(frame.size, frame.position, frame.pivot, + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); + for (auto& corner : CORNERS) + { + auto world = glm::vec2(layerTransform * glm::vec4(corner, 0.0f, 1.0f)); + min = glm::min(min, world); + max = glm::max(max, world); + isAny = true; + } + }); + } + + if (!isAny) return glm::vec4(-1.0f); + return {min.x, min.y, max.x - min.x, max.y - min.y}; + } +} diff --git a/src/model/frames.hpp b/src/model/frames.hpp new file mode 100644 index 0000000..4a2bca2 --- /dev/null +++ b/src/model/frames.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include +#include + +#include "model.hpp" + +namespace anm2ed::model +{ + void frame_mix(Frame&, const Frame&, float); + std::vector frame_bake_split(const Frame&, const Frame&, int, bool, bool); + glm::mat4 frame_parent_model_get(const Frame&); + Frame frame_generate(const Track&, float); + int frame_index_from_at_frame_get(const Track&, int); + int frame_index_from_time_get(const Track&, float); + float frame_time_from_index_get(const Track&, int); + void frame_bake(Track&, int, int, bool, bool); + void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); + void frames_sort_by_at_frame(Track&); + void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&); + void special_interpolated_frames_bake(Model&, int, bool, bool); + glm::vec4 animation_rect(const Model&, const Animation&, bool); +} diff --git a/src/model/model.cpp b/src/model/model.cpp new file mode 100644 index 0000000..4280737 --- /dev/null +++ b/src/model/model.cpp @@ -0,0 +1,481 @@ +#include "model.hpp" + +#include +#include + +namespace anm2ed::model +{ + // The slot holding the animation at a flat index (animations inside groups count in order), or nullptr. + template auto animation_slot_get(Entries& entries, int index) -> decltype(&std::get<0>(entries[0])) + { + if (index < 0) return nullptr; + for (auto& entry : entries) + { + if (auto animation = std::get_if>(&entry)) + { + if (index-- == 0) return animation; + continue; + } + auto& group = std::get(entry); + if (index < (int)group.animations.size()) return &group.animations[index]; + index -= (int)group.animations.size(); + } + return nullptr; + } + + int Model::animations_count_get() const + { + int count{}; + for (const auto& entry : animations.entries) + count += + std::holds_alternative(entry) ? (int)std::get(entry).animations.size() : 1; + return count; + } + + const Animation* Model::animation_get(int index) const + { + auto slot = animation_slot_get(animations.entries, index); + return slot ? slot->get() : nullptr; + } + + // Copy-on-write: an animation shared with undo history is cloned before it is changed. + Animation* Model::animation_edit(int index) + { + auto slot = animation_slot_get(animations.entries, index); + if (!slot || !*slot) return nullptr; + if (slot->use_count() > 1) *slot = std::make_shared(**slot); + return const_cast(slot->get()); + } + + std::vector> Model::animations_get() const + { + std::vector> result{}; + for (int i = 0; i < animations_count_get(); ++i) + result.emplace_back(i, animation_get(i)); + return result; + } + + template auto animation_group_find(Self& self, int index) + { + using Group = std::conditional_t, const AnimationGroup, AnimationGroup>; + Group* result{}; + if (index < 0) return result; + for (auto& entry : self.animations.entries) + { + if (std::holds_alternative>(entry)) + { + if (index-- == 0) return result; + continue; + } + auto& group = std::get(entry); + if (index < (int)group.animations.size()) return &group; + index -= (int)group.animations.size(); + } + return result; + } + + const AnimationGroup* Model::animation_group_get(int index) const { return animation_group_find(*this, index); } + AnimationGroup* Model::animation_group_edit(int index) { return animation_group_find(*this, index); } + + int Model::animation_group_id_get(int index) const + { + auto group = animation_group_get(index); + return group ? group->id : -1; + } + + template auto animation_track_group_find(A& animation, int groupType, int groupId) + { + using Group = std::conditional_t, const TrackGroup, TrackGroup>; + Group* result{}; + if (groupId < 0 || (groupType != LAYER && groupType != NULL_)) return result; + groups_each(animation_entries_get(animation, groupType), + [&](auto& group) + { + if (!result && group.id == groupId) result = &group; + }); + return result; + } + + TrackGroup* animation_track_group_get(Animation& animation, int groupType, int groupId) + { + return animation_track_group_find(animation, groupType, groupId); + } + + const TrackGroup* animation_track_group_get(const Animation& animation, int groupType, int groupId) + { + return animation_track_group_find(animation, groupType, groupId); + } + + // A track by item type and id; a group root when the item is ROOT with a group, and grouped tracks only match their + // own group when one is given. + template auto animation_track_find(A& animation, int itemType, int id, int groupType, int groupId) + { + using T = std::conditional_t, const Track, Track>; + T* result{}; + auto isGrouped = groupType != NONE && groupId != -1; + if (itemType == ROOT) + { + if (!isGrouped) return &animation.root; + auto group = animation_track_group_find(animation, groupType, groupId); + return group ? &group->root : result; + } + if (itemType == TRIGGER) return &animation.triggers; + if (itemType != LAYER && itemType != NULL_) return result; + + tracks_each(animation_entries_get(animation, itemType), + [&](auto& track, auto* group) + { + if (result || track.id != id) return; + if (isGrouped && (!group || group->id != groupId)) return; + result = &track; + }); + return result; + } + + const Track* animation_track_get(const Animation& animation, int itemType, int id, int groupType, int groupId) + { + return animation_track_find(animation, itemType, id, groupType, groupId); + } + + Track* animation_track_get(Animation& animation, int itemType, int id, int groupType, int groupId) + { + return animation_track_find(animation, itemType, id, groupType, groupId); + } + + const Track* Model::track_get(Reference reference) const + { + auto animation = animation_get(reference.animationIndex); + return animation ? animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, + reference.groupId) + : nullptr; + } + + Track* Model::track_edit(Reference reference) + { + if (!track_get(reference)) return nullptr; + auto animation = animation_edit(reference.animationIndex); + return animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, + reference.groupId); + } + + const TrackGroup* Model::track_group_get(int animationIndex, int groupType, int groupId) const + { + auto animation = animation_get(animationIndex); + return animation ? animation_track_group_get(*animation, groupType, groupId) : nullptr; + } + + TrackGroup* Model::track_group_edit(int animationIndex, int groupType, int groupId) + { + if (!track_group_get(animationIndex, groupType, groupId)) return nullptr; + return animation_track_group_get(*animation_edit(animationIndex), groupType, groupId); + } + + const Frame* Model::frame_get(Reference reference) const + { + auto track = track_get(reference); + if (!track || reference.frameIndex < 0 || reference.frameIndex >= (int)track->frames.size()) return nullptr; + return &track->frames[reference.frameIndex]; + } + + Frame* Model::frame_edit(Reference reference) + { + if (!frame_get(reference)) return nullptr; + return &track_edit(reference)->frames[reference.frameIndex]; + } + + const Spritesheet* Model::layer_spritesheet_get(int layerId) const + { + auto layer = item_get(content.layers, layerId); + return layer ? item_get(content.spritesheets, layer->spritesheetId) : nullptr; + } + + // The frame with its region's crop/size/pivot applied, as it is drawn. + Frame Model::frame_effective(int layerId, const Frame& frame) const + { + auto resolved = frame; + auto spritesheet = frame.regionId == -1 ? nullptr : layer_spritesheet_get(layerId); + auto region = spritesheet ? item_get(spritesheet->regions, frame.regionId) : nullptr; + if (!region) return resolved; + resolved.crop = region->crop; + resolved.size = region->size; + resolved.pivot = region->pivot; + return resolved; + } + + template std::set unused_ids_get(const Items& items, const std::set& used) + { + std::set unused{}; + for (const auto& item : items) + if (!used.contains(item.id)) unused.insert(item.id); + return unused; + } + + std::set Model::unused_get(ElementType type, const Animation* only) const + { + std::set used{}; + auto used_insert = [&](const Animation& animation) + { + if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) + tracks_each(type == ElementType::LAYER_ELEMENT ? animation.layers : animation.nulls, + [&](const Track& track, auto*) { used.insert(track.id); }); + for (const auto& trigger : animation.triggers.frames) + { + if (type == ElementType::EVENT_ELEMENT) used.insert(trigger.eventId); + if (type == ElementType::SOUND_ELEMENT) used.insert(trigger.soundIds.begin(), trigger.soundIds.end()); + } + if (type == ElementType::SHADER) + tracks_each(animation.layers, + [&](const Track& track, auto*) + { + for (const auto& frame : track.frames) + used.insert(frame.shaderId); + }); + }; + + if (type == ElementType::SPRITESHEET) + for (const auto& layer : content.layers) + used.insert(layer.spritesheetId); + else if (only) + used_insert(*only); + else + for (auto [index, animation] : animations_get()) + used_insert(*animation); + + switch (type) + { + case ElementType::SPRITESHEET: + return unused_ids_get(content.spritesheets, used); + case ElementType::SHADER: + return unused_ids_get(content.shaders, used); + case ElementType::LAYER_ELEMENT: + return unused_ids_get(content.layers, used); + case ElementType::NULL_ELEMENT: + return unused_ids_get(content.nulls, used); + case ElementType::EVENT_ELEMENT: + return unused_ids_get(content.events, used); + case ElementType::SOUND_ELEMENT: + return unused_ids_get(content.sounds, used); + default: + return {}; + } + } + + std::set Model::region_unused_get(int spritesheetId) const + { + std::set used{}; + for (auto [index, animation] : animations_get()) + tracks_each(animation->layers, + [&](const Track& track, auto*) + { + auto layer = item_get(content.layers, track.id); + if (!layer || layer->spritesheetId != spritesheetId) return; + for (const auto& frame : track.frames) + used.insert(frame.regionId); + }); + auto spritesheet = item_get(content.spritesheets, spritesheetId); + return spritesheet ? unused_ids_get(spritesheet->regions, used) : std::set{}; + } + + Handle Model::handle_get(Reference reference, bool isGroup) const + { + Handle handle{}; + auto animation = animation_get(reference.animationIndex); + if (!animation) return handle; + handle.animation = animation->uid; + + if (isGroup) + { + if (auto group = animation_track_group_get(*animation, reference.itemType, reference.itemID)) + handle.item = group->uid; + return handle; + } + + auto track = + animation_track_get(*animation, reference.itemType, reference.itemID, reference.groupType, reference.groupId); + if (!track) return handle; + handle.item = track->uid; + if (reference.frameIndex >= 0 && reference.frameIndex < (int)track->frames.size()) + handle.frame = track->frames[reference.frameIndex].uid; + return handle; + } + + std::uint64_t Model::uid_get(Reference reference, bool isGroup) const + { + auto handle = handle_get(reference, isGroup); + return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; + } + + template void animation_uids_each(Animation& animation, Callback&& callback) + { + callback(animation.uid); + for (auto* entries : {&animation.layers, &animation.nulls}) + groups_each(*entries, [&](TrackGroup& group) { callback(group.uid); }); + animation_tracks_each(animation, + [&](Track& track) + { + callback(track.uid); + for (auto& frame : track.frames) + callback(frame.uid); + }); + } + + // Gives any element that shares a uid with an earlier one a fresh uid (copies made without cloning). + void Model::uids_repair() + { + std::unordered_set seen{}; + auto repair = [&](std::uint64_t& uid) + { + if (!uid || !seen.insert(uid).second) uid = util::uid_next(); + }; + + for (int i = 0; i < animations_count_get(); ++i) + { + auto seenBefore = seen; + bool isDuplicate{}; + animation_uids_each(const_cast(*animation_get(i)), + [&](std::uint64_t& uid) { isDuplicate |= !uid || !seen.insert(uid).second; }); + if (!isDuplicate) continue; + seen = std::move(seenBefore); + animation_uids_each(*animation_edit(i), repair); + } + for (auto& entry : animations.entries) + if (auto group = std::get_if(&entry)) repair(group->uid); + for (auto& spritesheet : content.spritesheets) + { + repair(spritesheet.uid); + for (auto& region : spritesheet.regions) + repair(region.uid); + } + for (auto& shader : content.shaders) + repair(shader.uid); + for (auto& layer : content.layers) + repair(layer.uid); + for (auto& null : content.nulls) + repair(null.uid); + for (auto& event : content.events) + repair(event.uid); + for (auto& sound : content.sounds) + repair(sound.uid); + } + + int track_frames_count_get(const Track& track) { return (int)track.frames.size(); } + + int track_length_get(const Track& track) + { + int length{}; + for (const auto& frame : track.frames) + length = track.type == ItemType::TRIGGER ? std::max(length, frame.atFrame) : length + frame.duration; + return length; + } + + int animation_length_get(const Animation& animation) + { + int length{}; + animation_tracks_each(animation, [&](const Track& track) { length = std::max(length, track_length_get(track)); }); + return std::max(length, FRAME_DURATION_MIN); + } + + Frame frame_clone(Frame frame) + { + frame.uid = util::uid_next(); + return frame; + } + + Track track_clone(Track track) + { + track.uid = util::uid_next(); + for (auto& frame : track.frames) + frame.uid = util::uid_next(); + return track; + } + + Animation animation_clone(Animation animation) + { + animation_uids_each(animation, [](std::uint64_t& uid) { uid = util::uid_next(); }); + return animation; + } + + void track_locations_add(std::unordered_map& locations, const Track& track, + Reference reference) + { + constexpr ElementType TRACK_TYPES[] = {ElementType::UNKNOWN, ElementType::ROOT_ANIMATION, + ElementType::LAYER_ANIMATION, ElementType::NULL_ANIMATION, + ElementType::TRIGGERS}; + locations[track.uid] = {reference, TRACK_TYPES[(int)track.type]}; + for (const auto& frame : track.frames) + { + ++reference.frameIndex; + locations[frame.uid] = {reference, track.type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME}; + } + } + + UidIndex::UidIndex(const Model& model) + { + for (auto [index, animation] : model.animations_get()) + { + locations[animation->uid] = {{index}, ElementType::ANIMATION}; + track_locations_add(locations, animation->root, {index, ROOT}); + track_locations_add(locations, animation->triggers, {index, TRIGGER}); + for (auto type : {LAYER, NULL_}) + for (const auto& entry : animation_entries_get(*animation, type)) + if (auto track = std::get_if(&entry)) + track_locations_add(locations, *track, {index, type, track->id}); + else + { + const auto& group = std::get(entry); + locations[group.uid] = {{index, type, group.id}, ElementType::GROUP}; + track_locations_add(locations, group.root, {index, ROOT, -1, -1, type, group.id}); + for (const auto& groupTrack : group.tracks) + track_locations_add(locations, groupTrack, {index, type, groupTrack.id, -1, type, group.id}); + } + } + } + + bool UidIndex::contains(std::uint64_t uid) const { return uid && locations.contains(uid); } + + std::optional UidIndex::reference_get(std::uint64_t uid) const + { + auto it = locations.find(uid); + return it == locations.end() ? std::nullopt : std::optional(it->second.reference); + } + + ElementType UidIndex::type_get(std::uint64_t uid) const + { + auto it = locations.find(uid); + return it == locations.end() ? ElementType::UNKNOWN : it->second.type; + } + + // Equality by value; animations shared with another model compare by pointer first. + bool is_model_equal(const Model& left, const Model& right) + { + if (left.info != right.info || left.content != right.content || left.layout != right.layout || + left.extras != right.extras || left.isValid != right.isValid || + left.animations.defaultAnimation != right.animations.defaultAnimation || + left.animations.extras != right.animations.extras || + left.animations.entries.size() != right.animations.entries.size()) + return false; + + auto is_animation_equal = [](const std::shared_ptr& a, const std::shared_ptr& b) + { return a == b || (a && b && *a == *b); }; + for (std::size_t i = 0; i < left.animations.entries.size(); ++i) + { + const auto& a = left.animations.entries[i]; + const auto& b = right.animations.entries[i]; + if (a.index() != b.index()) return false; + if (auto animation = std::get_if>(&a)) + { + if (!is_animation_equal(*animation, std::get>(b))) return false; + continue; + } + const auto& groupA = std::get(a); + const auto& groupB = std::get(b); + if (groupA.uid != groupB.uid || groupA.id != groupB.id || groupA.name != groupB.name || + groupA.isExpanded != groupB.isExpanded || groupA.isVisible != groupB.isVisible || + groupA.extras != groupB.extras || groupA.animations.size() != groupB.animations.size()) + return false; + for (std::size_t j = 0; j < groupA.animations.size(); ++j) + if (!is_animation_equal(groupA.animations[j], groupB.animations[j])) return false; + } + return true; + } +} diff --git a/src/model/model.hpp b/src/model/model.hpp new file mode 100644 index 0000000..497f61b --- /dev/null +++ b/src/model/model.hpp @@ -0,0 +1,389 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "model/common.hpp" +#include "uid.hpp" + +// The typed document model. XML exists only in model/xml.cpp; everything else edits and reads these structs. +namespace anm2ed::model +{ + // An XML element the editor does not understand, kept verbatim so it survives a save. + struct XmlNode + { + std::string tag{}; + std::vector> attributes{}; + std::string text{}; + std::vector children{}; + + bool operator==(const XmlNode&) const = default; + }; + + // Unknown XML attached to a known node: attributes, text, and unknown children with the child index they had. + struct Extras + { + std::vector> attributes{}; + std::string text{}; + std::vector> children{}; + + bool operator==(const Extras&) const = default; + }; + + // A keyframe; on a triggers track the same struct is a trigger (atFrame, eventId, soundIds). + struct Frame + { + std::uint64_t uid{util::uid_next()}; + glm::vec2 crop{}; + glm::vec2 size{}; + glm::vec2 pivot{}; + glm::vec2 position{}; + glm::vec2 scale{100.0f, 100.0f}; + glm::vec2 shear{}; + float rotation{}; + glm::vec4 tint{types::color::WHITE}; + glm::vec3 colorOffset{}; + int duration{1}; + bool isVisible{true}; + Interpolation interpolation{Interpolation::NONE}; + int regionId{-1}; + int shaderId{-1}; + int atFrame{-1}; + int eventId{-1}; + std::vector soundIds{}; + Extras extras{}; + + bool operator==(const Frame&) const = default; + }; + + struct Track + { + std::uint64_t uid{util::uid_next()}; + ItemType type{ItemType::LAYER}; + int id{-1}; + bool isVisible{true}; + std::vector frames{}; + Extras extras{}; + + bool operator==(const Track&) const = default; + }; + + struct TrackGroup + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + bool isExpanded{true}; + bool isVisible{true}; + Track root{.type = ItemType::ROOT, .frames = {Frame{}}}; + std::vector tracks{}; + Extras extras{}; + + bool operator==(const TrackGroup&) const = default; + }; + + using TrackEntry = std::variant; + + struct Animation + { + std::uint64_t uid{util::uid_next()}; + std::string name{}; + int frameNum{1}; + bool isLoop{true}; + Track root{.type = ItemType::ROOT, .frames = {Frame{}}}; + std::vector layers{}; + std::vector nulls{}; + Track triggers{.type = ItemType::TRIGGER}; + std::vector layout{ElementType::ROOT_ANIMATION, ElementType::LAYER_ANIMATIONS, + ElementType::NULL_ANIMATIONS, ElementType::TRIGGERS}; + Extras extras{}; + Extras layersExtras{}; + Extras nullsExtras{}; + + bool operator==(const Animation&) const = default; + }; + + struct AnimationGroup + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + bool isExpanded{true}; + bool isVisible{true}; + std::vector> animations{}; + Extras extras{}; + + bool operator==(const AnimationGroup&) const = default; + }; + + using AnimationEntry = std::variant, AnimationGroup>; + + struct Region + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + glm::vec2 crop{}; + glm::vec2 size{}; + glm::vec2 pivot{}; + Origin origin{Origin::CUSTOM}; + Extras extras{}; + + bool operator==(const Region&) const = default; + }; + + struct Spritesheet + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::filesystem::path path{}; + std::vector regions{}; + Extras extras{}; + + bool operator==(const Spritesheet&) const = default; + }; + + struct Component + { + int index{-1}; + std::string binding{}; + std::string value{}; + Extras extras{}; + + bool operator==(const Component&) const = default; + }; + + struct Uniform + { + std::string name{}; + std::string binding{}; + std::string value{}; + std::vector components{}; + Extras extras{}; + + bool operator==(const Uniform&) const = default; + }; + + struct Shader + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + std::filesystem::path vertex{}; + std::filesystem::path fragment{}; + std::vector uniforms{}; + Extras extras{}; + + bool operator==(const Shader&) const = default; + }; + + struct Layer + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + int spritesheetId{}; + Extras extras{}; + + bool operator==(const Layer&) const = default; + }; + + struct Null + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + bool isShowRect{}; + Extras extras{}; + + bool operator==(const Null&) const = default; + }; + + struct Event + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::string name{}; + Extras extras{}; + + bool operator==(const Event&) const = default; + }; + + struct Sound + { + std::uint64_t uid{util::uid_next()}; + int id{-1}; + std::filesystem::path path{}; + Extras extras{}; + + bool operator==(const Sound&) const = default; + }; + + struct Info + { + std::string createdBy{"robot"}; + std::string createdOn{}; + int fps{30}; + int version{}; + Extras extras{}; + + bool operator==(const Info&) const = default; + }; + + struct Content + { + std::vector spritesheets{}; + std::vector shaders{}; + std::vector layers{}; + std::vector nulls{}; + std::vector events{}; + std::vector sounds{}; + std::vector layout{ElementType::SPRITESHEETS, ElementType::SHADERS, ElementType::LAYERS, + ElementType::NULLS, ElementType::EVENTS}; + Extras extras{}; + std::vector> containerExtras{}; + + bool operator==(const Content&) const = default; + }; + + struct Animations + { + std::string defaultAnimation{}; + std::vector entries{}; + Extras extras{}; + + bool operator==(const Animations&) const = default; + }; + + // Content item lookup by file id (layers, nulls, events, sounds, spritesheets, shaders, regions). + template auto item_get(Items& items, int id) -> decltype(&items.front()) + { + for (auto& item : items) + if (item.id == id) return &item; + return nullptr; + } + + template int item_next_id_get(const Items& items) + { + int id{-1}; + for (const auto& item : items) + id = std::max(id, item.id); + return id + 1; + } + + // Tracks of one kind (layer or null) in order, including those inside groups; callback(track, group or nullptr). + template void tracks_each(Entries& entries, Callback&& callback) + { + for (auto& entry : entries) + if (auto track = std::get_if(&entry)) + callback(*track, static_cast(entry))>(nullptr)); + else + { + auto& group = std::get(entry); + for (auto& groupTrack : group.tracks) + callback(groupTrack, &group); + } + } + + template void groups_each(Entries& entries, Callback&& callback) + { + for (auto& entry : entries) + if (auto group = std::get_if(&entry)) callback(*group); + } + + // Every track of an animation (root, group roots, layers, nulls, triggers). + template void animation_tracks_each(A& animation, Callback&& callback) + { + callback(animation.root); + for (auto* entries : {&animation.layers, &animation.nulls}) + for (auto& entry : *entries) + if (auto track = std::get_if(&entry)) + callback(*track); + else + { + auto& group = std::get(entry); + callback(group.root); + for (auto& groupTrack : group.tracks) + callback(groupTrack); + } + callback(animation.triggers); + } + + template auto& animation_entries_get(A& animation, int itemType) + { + return itemType == NULL_ ? animation.nulls : animation.layers; + } + + class Model + { + public: + Info info{}; + Content content{}; + Animations animations{}; + std::vector layout{ElementType::INFO, ElementType::CONTENT, ElementType::ANIMATIONS}; + Extras extras{}; + bool isValid{true}; + + int animations_count_get() const; + const Animation* animation_get(int) const; + Animation* animation_edit(int); + int animation_group_id_get(int) const; + const AnimationGroup* animation_group_get(int) const; + AnimationGroup* animation_group_edit(int); + std::vector> animations_get() const; + + const Track* track_get(Reference) const; + Track* track_edit(Reference); + const TrackGroup* track_group_get(int, int, int) const; + TrackGroup* track_group_edit(int, int, int); + const Frame* frame_get(Reference) const; + Frame* frame_edit(Reference); + + const Spritesheet* layer_spritesheet_get(int) const; + Frame frame_effective(int, const Frame&) const; + std::set unused_get(ElementType, const Animation* = nullptr) const; + std::set region_unused_get(int) const; + std::uint64_t uid_get(Reference, bool = false) const; + Handle handle_get(Reference, bool = false) const; + void uids_repair(); + }; + + // uid -> where that element is now (as a Reference) and what it is, built in one walk of the animations. + class UidIndex + { + public: + struct Location + { + Reference reference{}; + ElementType type{}; + }; + + private: + std::unordered_map locations{}; + + public: + UidIndex() = default; + explicit UidIndex(const Model&); + bool contains(std::uint64_t) const; + std::optional reference_get(std::uint64_t) const; + ElementType type_get(std::uint64_t) const; + }; + + bool is_model_equal(const Model&, const Model&); + int track_frames_count_get(const Track&); + int track_length_get(const Track&); + int animation_length_get(const Animation&); + const Track* animation_track_get(const Animation&, int, int, int = NONE, int = -1); + Track* animation_track_get(Animation&, int, int, int = NONE, int = -1); + TrackGroup* animation_track_group_get(Animation&, int, int); + const TrackGroup* animation_track_group_get(const Animation&, int, int); + Animation animation_clone(Animation); + Frame frame_clone(Frame); + Track track_clone(Track); +} diff --git a/src/model/xml.cpp b/src/model/xml.cpp new file mode 100644 index 0000000..804bed3 --- /dev/null +++ b/src/model/xml.cpp @@ -0,0 +1,866 @@ +#include "xml.hpp" + +#include + +#include "anm2/internal.hpp" + +using namespace tinyxml2; + +namespace anm2ed::model +{ + constexpr std::size_t XML_NODE_BUFFER_SIZE = 64; + + // Records an emitted element as an XmlNode, attribute values formatted exactly as the XML writer formats them. + struct XmlNodeSink : ElementSink + { + std::vector stack{}; + XmlNode root{}; + + void open(std::string_view tag) override + { + auto& node = stack.empty() ? root : stack.back()->children.emplace_back(); + node.tag = std::string(tag); + stack.push_back(&node); + } + + template void formatted_add(const char* name, T value) + { + char buffer[XML_NODE_BUFFER_SIZE]{}; + XMLUtil::ToStr(value, buffer, sizeof(buffer)); + attribute(name, (const char*)buffer); + } + + void attribute(const char* name, const char* value) override { stack.back()->attributes.emplace_back(name, value); } + void attribute(const char* name, int value) override { formatted_add(name, value); } + void attribute(const char* name, bool value) override { formatted_add(name, value); } + void attribute(const char* name, float value) override { formatted_add(name, value); } + void text(const char* value) override { stack.back()->text = value; } + void close() override { stack.pop_back(); } + }; + + XmlNode node_get(const Element& element, ElementType parentType) + { + XmlNodeSink sink{}; + element_emit(sink, element, parentType, SERIALIZE_ANM2ED_DEFAULT); + return sink.root; + } + + Element node_element_get(const XmlNode& node) + { + Element element{}; + element.tag = node.tag; + element.extraAttributes = node.attributes; + element.text = node.text; + for (const auto& child : node.children) + element.children.push_back(node_element_get(child)); + return element; + } + + Extras extras_read(const Element& element) { return {element.extraAttributes, element.text, {}}; } + + void extras_write(Element& element, const Extras& extras) + { + element.extraAttributes = extras.attributes; + element.text = extras.text; + for (const auto& [index, node] : extras.children) + element.children.insert(element.children.begin() + std::min(index, (int)element.children.size()), + node_element_get(node)); + } + + // Reads children: `known` returns false for a child it does not take, which is kept as unknown XML. + template void children_read(const Element& element, Extras& extras, Known&& known) + { + for (int i = 0; i < (int)element.children.size(); ++i) + if (!known(element.children[i])) extras.children.emplace_back(i, node_get(element.children[i], element.type)); + } + + Element element_make_with(ElementType type, const Extras& extras) + { + auto element = element_make(type); + extras_write(element, extras); + return element; + } + + Frame frame_read(const Element& element) + { + Frame frame{}; + frame.crop = element.crop; + frame.size = element.size; + frame.pivot = element.pivot; + frame.position = element.position; + frame.scale = element.scale; + frame.shear = element.shear; + frame.rotation = element.rotation; + frame.tint = element.tint; + frame.colorOffset = element.colorOffset; + frame.duration = element.duration; + frame.isVisible = element.isVisible; + frame.interpolation = element.interpolation; + frame.regionId = element.regionId; + frame.shaderId = element.shaderId; + frame.atFrame = element.atFrame; + frame.eventId = element.eventId; + frame.soundIds = element.soundIds; + frame.extras = extras_read(element); + return frame; + } + + Element frame_write(const Frame& frame, ItemType type) + { + auto element = element_make(type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME); + element.crop = frame.crop; + element.size = frame.size; + element.pivot = frame.pivot; + element.position = frame.position; + element.scale = frame.scale; + element.shear = frame.shear; + element.rotation = frame.rotation; + element.tint = frame.tint; + element.colorOffset = frame.colorOffset; + element.duration = frame.duration; + element.isVisible = frame.isVisible; + element.interpolation = frame.interpolation; + element.regionId = frame.regionId; + element.shaderId = frame.shaderId; + element.atFrame = frame.atFrame; + element.eventId = frame.eventId; + element.soundIds = frame.soundIds; + extras_write(element, frame.extras); + return element; + } + + ElementType track_element_type_get(ItemType type) + { + switch (type) + { + case ItemType::ROOT: + return ElementType::ROOT_ANIMATION; + case ItemType::NULL_: + return ElementType::NULL_ANIMATION; + case ItemType::TRIGGER: + return ElementType::TRIGGERS; + default: + return ElementType::LAYER_ANIMATION; + } + } + + Track track_read(const Element& element, ItemType type) + { + Track track{.type = type, .id = track_id_get(element), .isVisible = element.isVisible}; + auto frameType = track_frame_type_get(element); + children_read(element, track.extras, + [&](const Element& child) + { + if (child.type != frameType) return false; + track.frames.push_back(frame_read(child)); + return true; + }); + track.extras.attributes = element.extraAttributes; + track.extras.text = element.text; + return track; + } + + Element track_write(const Track& track, int groupId) + { + auto element = element_make(track_element_type_get(track.type)); + if (track.type == ItemType::LAYER) element.layerId = track.id; + if (track.type == ItemType::NULL_) element.nullId = track.id; + element.isVisible = track.isVisible; + element.groupId = groupId; + for (const auto& frame : track.frames) + element.children.push_back(frame_write(frame, track.type)); + extras_write(element, track.extras); + return element; + } + + // In memory the anm2 tracks are flat: a group element is followed (somewhere) by tracks carrying its id. + std::vector track_entries_read(const Element& container, ItemType type, Extras& extras) + { + std::vector entries{}; + std::map groupEntries{}; + auto trackType = track_element_type_get(type); + children_read(container, extras, + [&](const Element& child) + { + if (child.type == ElementType::GROUP) + { + TrackGroup group{.id = child.id, + .name = child.name, + .isExpanded = child.isExpanded, + .isVisible = child.isVisible, + .extras = extras_read(child)}; + if (auto root = child_first_get(child, ElementType::ROOT_ANIMATION)) + group.root = track_read(*root, ItemType::ROOT); + groupEntries[child.id] = entries.size(); + entries.emplace_back(std::move(group)); + return true; + } + if (child.type != trackType) return false; + auto track = track_read(child, type); + if (auto group = groupEntries.find(child.groupId); group != groupEntries.end()) + std::get(entries[group->second]).tracks.push_back(std::move(track)); + else + entries.emplace_back(std::move(track)); + return true; + }); + extras.attributes = container.extraAttributes; + extras.text = container.text; + return entries; + } + + Element track_entries_write(const std::vector& entries, ElementType containerType, const Extras& extras) + { + auto container = element_make(containerType); + for (const auto& entry : entries) + if (auto track = std::get_if(&entry)) + container.children.push_back(track_write(*track, -1)); + else + { + const auto& group = std::get(entry); + auto element = element_make(ElementType::GROUP); + element.id = group.id; + element.name = group.name; + element.isExpanded = group.isExpanded; + element.isVisible = group.isVisible; + element.children.push_back(track_write(group.root, -1)); + extras_write(element, group.extras); + container.children.push_back(std::move(element)); + for (const auto& groupTrack : group.tracks) + container.children.push_back(track_write(groupTrack, group.id)); + } + extras_write(container, extras); + return container; + } + + Animation animation_read(const Element& element) + { + Animation animation{.name = element.name, + .frameNum = element.frameNum, + .isLoop = element.isLoop, + .root = {.type = ItemType::ROOT}, + .layout = {}}; + std::set read{}; + children_read(element, animation.extras, + [&](const Element& child) + { + if (read.contains(child.type)) return false; + switch (child.type) + { + case ElementType::ROOT_ANIMATION: + animation.root = track_read(child, ItemType::ROOT); + break; + case ElementType::LAYER_ANIMATIONS: + animation.layers = track_entries_read(child, ItemType::LAYER, animation.layersExtras); + break; + case ElementType::NULL_ANIMATIONS: + animation.nulls = track_entries_read(child, ItemType::NULL_, animation.nullsExtras); + break; + case ElementType::TRIGGERS: + animation.triggers = track_read(child, ItemType::TRIGGER); + break; + default: + return false; + } + read.insert(child.type); + animation.layout.push_back(child.type); + return true; + }); + animation.extras.attributes = element.extraAttributes; + animation.extras.text = element.text; + return animation; + } + + // Known children in their recorded order; a part with content that was never in the file is appended. + template + void layout_write(Element& element, const std::vector& layout, + const std::vector>& parts, Write&& write) + { + for (auto type : layout) + element.children.push_back(write(type)); + for (auto [type, isContent] : parts) + if (isContent && !std::ranges::contains(layout, type)) element.children.push_back(write(type)); + } + + Element animation_write(const Animation& animation, int groupId) + { + auto element = element_make(ElementType::ANIMATION); + element.name = animation.name; + element.frameNum = animation.frameNum; + element.isLoop = animation.isLoop; + element.groupId = groupId; + layout_write(element, animation.layout, + {{ElementType::ROOT_ANIMATION, !animation.root.frames.empty()}, + {ElementType::LAYER_ANIMATIONS, !animation.layers.empty()}, + {ElementType::NULL_ANIMATIONS, !animation.nulls.empty()}, + {ElementType::TRIGGERS, !animation.triggers.frames.empty()}}, + [&](ElementType type) + { + switch (type) + { + case ElementType::ROOT_ANIMATION: + return track_write(animation.root, -1); + case ElementType::LAYER_ANIMATIONS: + return track_entries_write(animation.layers, type, animation.layersExtras); + case ElementType::NULL_ANIMATIONS: + return track_entries_write(animation.nulls, type, animation.nullsExtras); + default: + return track_write(animation.triggers, -1); + } + }); + extras_write(element, animation.extras); + return element; + } + + AnimationGroup animation_group_read(const Element& element) + { + return {.id = element.id, + .name = element.name, + .isExpanded = element.isExpanded, + .isVisible = element.isVisible, + .extras = extras_read(element)}; + } + + Element animation_group_write(const AnimationGroup& group) + { + auto element = element_make(ElementType::GROUP); + element.id = group.id; + element.name = group.name; + element.isExpanded = group.isExpanded; + element.isVisible = group.isVisible; + extras_write(element, group.extras); + return element; + } + + Animations animations_read(const Element& element) + { + Animations animations{.defaultAnimation = element.defaultAnimation}; + std::map groupEntries{}; + children_read(element, animations.extras, + [&](const Element& child) + { + if (child.type == ElementType::GROUP) + { + groupEntries[child.id] = animations.entries.size(); + animations.entries.emplace_back(animation_group_read(child)); + return true; + } + if (child.type != ElementType::ANIMATION) return false; + auto animation = std::make_shared(animation_read(child)); + if (auto group = groupEntries.find(child.groupId); group != groupEntries.end()) + std::get(animations.entries[group->second]).animations.push_back(animation); + else + animations.entries.emplace_back(animation); + return true; + }); + animations.extras.attributes = element.extraAttributes; + animations.extras.text = element.text; + return animations; + } + + Element animations_write(const Animations& animations) + { + auto element = element_make(ElementType::ANIMATIONS); + element.defaultAnimation = animations.defaultAnimation; + for (const auto& entry : animations.entries) + if (auto animation = std::get_if>(&entry)) + element.children.push_back(animation_write(**animation, -1)); + else + { + const auto& group = std::get(entry); + element.children.push_back(animation_group_write(group)); + for (const auto& groupAnimation : group.animations) + element.children.push_back(animation_write(*groupAnimation, group.id)); + } + extras_write(element, animations.extras); + return element; + } + + Region region_read(const Element& element) + { + return {.id = element.id, + .name = element.name, + .crop = element.crop, + .size = element.size, + .pivot = element.pivot, + .origin = element.origin, + .extras = extras_read(element)}; + } + + Element item_write(const Region& region) + { + auto element = element_make(ElementType::REGION); + element.id = region.id; + element.name = region.name; + element.crop = region.crop; + element.size = region.size; + element.pivot = region.pivot; + element.origin = region.origin; + extras_write(element, region.extras); + return element; + } + + Spritesheet spritesheet_read(const Element& element) + { + Spritesheet spritesheet{.id = element.id, .path = element.path}; + children_read(element, spritesheet.extras, + [&](const Element& child) + { + if (child.type != ElementType::REGION) return false; + spritesheet.regions.push_back(region_read(child)); + return true; + }); + spritesheet.extras.attributes = element.extraAttributes; + spritesheet.extras.text = element.text; + return spritesheet; + } + + Element item_write(const Spritesheet& spritesheet) + { + auto element = element_make(ElementType::SPRITESHEET); + element.id = spritesheet.id; + element.path = spritesheet.path; + for (const auto& region : spritesheet.regions) + element.children.push_back(item_write(region)); + extras_write(element, spritesheet.extras); + return element; + } + + Component component_read(const Element& element) + { + return {.index = element.index, .binding = element.binding, .value = element.value, .extras = extras_read(element)}; + } + + Uniform uniform_read(const Element& element) + { + Uniform uniform{.name = element.name, .binding = element.binding, .value = element.value}; + children_read(element, uniform.extras, + [&](const Element& child) + { + if (child.type != ElementType::COMPONENT) return false; + uniform.components.push_back(component_read(child)); + return true; + }); + uniform.extras.attributes = element.extraAttributes; + uniform.extras.text = element.text; + return uniform; + } + + Shader shader_read(const Element& element) + { + Shader shader{.id = element.id, .name = element.name, .vertex = element.vertex, .fragment = element.fragment}; + children_read(element, shader.extras, + [&](const Element& child) + { + if (child.type != ElementType::UNIFORM) return false; + shader.uniforms.push_back(uniform_read(child)); + return true; + }); + shader.extras.attributes = element.extraAttributes; + shader.extras.text = element.text; + return shader; + } + + Element item_write(const Shader& shader) + { + auto element = element_make(ElementType::SHADER); + element.id = shader.id; + element.name = shader.name; + element.vertex = shader.vertex; + element.fragment = shader.fragment; + for (const auto& uniform : shader.uniforms) + { + auto& uniformElement = element.children.emplace_back(element_make(ElementType::UNIFORM)); + uniformElement.name = uniform.name; + uniformElement.binding = uniform.binding; + uniformElement.value = uniform.value; + for (const auto& component : uniform.components) + { + auto& componentElement = uniformElement.children.emplace_back(element_make(ElementType::COMPONENT)); + componentElement.index = component.index; + componentElement.binding = component.binding; + componentElement.value = component.value; + extras_write(componentElement, component.extras); + } + extras_write(uniformElement, uniform.extras); + } + extras_write(element, shader.extras); + return element; + } + + Layer layer_read(const Element& element) + { + return { + .id = element.id, .name = element.name, .spritesheetId = element.spritesheetId, .extras = extras_read(element)}; + } + + Element item_write(const Layer& layer) + { + auto element = element_make(ElementType::LAYER_ELEMENT); + element.id = layer.id; + element.name = layer.name; + element.spritesheetId = layer.spritesheetId; + extras_write(element, layer.extras); + return element; + } + + Null null_read(const Element& element) + { + return {.id = element.id, .name = element.name, .isShowRect = element.isShowRect, .extras = extras_read(element)}; + } + + Element item_write(const Null& null) + { + auto element = element_make(ElementType::NULL_ELEMENT); + element.id = null.id; + element.name = null.name; + element.isShowRect = null.isShowRect; + extras_write(element, null.extras); + return element; + } + + Event event_read(const Element& element) + { + return {.id = element.id, .name = element.name, .extras = extras_read(element)}; + } + + Element item_write(const Event& event) + { + auto element = element_make(ElementType::EVENT_ELEMENT); + element.id = event.id; + element.name = event.name; + extras_write(element, event.extras); + return element; + } + + Sound sound_read(const Element& element) + { + return {.id = element.id, .path = element.path, .extras = extras_read(element)}; + } + + Element item_write(const Sound& sound) + { + auto element = element_make(ElementType::SOUND_ELEMENT); + element.id = sound.id; + element.path = sound.path; + extras_write(element, sound.extras); + return element; + } + + template Item item_read(const Element&); + template <> Spritesheet item_read(const Element& element) { return spritesheet_read(element); } + template <> Region item_read(const Element& element) { return region_read(element); } + template <> Shader item_read(const Element& element) { return shader_read(element); } + template <> Layer item_read(const Element& element) { return layer_read(element); } + template <> Null item_read(const Element& element) { return null_read(element); } + template <> Event item_read(const Element& element) { return event_read(element); } + template <> Sound item_read(const Element& element) { return sound_read(element); } + + template constexpr ElementType ITEM_TYPE{}; + template <> constexpr ElementType ITEM_TYPE{ElementType::SPRITESHEET}; + template <> constexpr ElementType ITEM_TYPE{ElementType::REGION}; + template <> constexpr ElementType ITEM_TYPE{ElementType::SHADER}; + template <> constexpr ElementType ITEM_TYPE{ElementType::LAYER_ELEMENT}; + template <> constexpr ElementType ITEM_TYPE{ElementType::NULL_ELEMENT}; + template <> constexpr ElementType ITEM_TYPE{ElementType::EVENT_ELEMENT}; + template <> constexpr ElementType ITEM_TYPE{ElementType::SOUND_ELEMENT}; + + template std::vector items_read(const Element& container, Content& content) + { + std::vector items{}; + Extras extras{extras_read(container)}; + children_read(container, extras, + [&](const Element& child) + { + if (child.type != ITEM_TYPE) return false; + items.push_back(item_read(child)); + return true; + }); + if (extras != Extras{}) content.containerExtras.emplace_back(container.type, std::move(extras)); + return items; + } + + template Element items_write(const std::vector& items, ElementType type, const Content& content) + { + auto container = element_make(type); + for (const auto& item : items) + container.children.push_back(item_write(item)); + for (const auto& [extrasType, extras] : content.containerExtras) + if (extrasType == type) extras_write(container, extras); + return container; + } + + Content content_read(const Element& element) + { + Content content{.layout = {}}; + std::set read{}; + children_read(element, content.extras, + [&](const Element& child) + { + if (read.contains(child.type)) return false; + switch (child.type) + { + case ElementType::SPRITESHEETS: + content.spritesheets = items_read(child, content); + break; + case ElementType::SHADERS: + content.shaders = items_read(child, content); + break; + case ElementType::LAYERS: + content.layers = items_read(child, content); + break; + case ElementType::NULLS: + content.nulls = items_read(child, content); + break; + case ElementType::EVENTS: + content.events = items_read(child, content); + break; + case ElementType::SOUNDS: + content.sounds = items_read(child, content); + break; + default: + return false; + } + read.insert(child.type); + content.layout.push_back(child.type); + return true; + }); + content.extras.attributes = element.extraAttributes; + content.extras.text = element.text; + return content; + } + + Element content_write(const Content& content) + { + auto element = element_make(ElementType::CONTENT); + layout_write(element, content.layout, + {{ElementType::SPRITESHEETS, !content.spritesheets.empty()}, + {ElementType::SHADERS, !content.shaders.empty()}, + {ElementType::LAYERS, !content.layers.empty()}, + {ElementType::NULLS, !content.nulls.empty()}, + {ElementType::EVENTS, !content.events.empty()}, + {ElementType::SOUNDS, !content.sounds.empty()}}, + [&](ElementType type) + { + switch (type) + { + case ElementType::SPRITESHEETS: + return items_write(content.spritesheets, type, content); + case ElementType::SHADERS: + return items_write(content.shaders, type, content); + case ElementType::LAYERS: + return items_write(content.layers, type, content); + case ElementType::NULLS: + return items_write(content.nulls, type, content); + case ElementType::EVENTS: + return items_write(content.events, type, content); + default: + return items_write(content.sounds, type, content); + } + }); + extras_write(element, content.extras); + return element; + } + + Model model_read(const Element& root) + { + Model model{.layout = {}}; + std::set read{}; + children_read(root, model.extras, + [&](const Element& child) + { + if (read.contains(child.type)) return false; + switch (child.type) + { + case ElementType::INFO: + model.info = {child.createdBy, child.createdOn, child.fps, child.version, {}}; + children_read(child, model.info.extras, [](const Element&) { return false; }); + model.info.extras.attributes = child.extraAttributes; + model.info.extras.text = child.text; + break; + case ElementType::CONTENT: + model.content = content_read(child); + break; + case ElementType::ANIMATIONS: + model.animations = animations_read(child); + break; + default: + return false; + } + read.insert(child.type); + model.layout.push_back(child.type); + return true; + }); + model.extras.attributes = root.extraAttributes; + model.extras.text = root.text; + return model; + } + + Element model_write(const Model& model) + { + auto root = element_make(ElementType::ANIMATED_ACTOR); + layout_write(root, model.layout, + {{ElementType::INFO, model.info.fps != Info{}.fps || model.info.createdBy != Info{}.createdBy}, + {ElementType::CONTENT, true}, + {ElementType::ANIMATIONS, !model.animations.entries.empty()}}, + [&](ElementType type) + { + if (type == ElementType::CONTENT) return content_write(model.content); + if (type == ElementType::ANIMATIONS) return animations_write(model.animations); + auto info = element_make(ElementType::INFO); + info.createdBy = model.info.createdBy; + info.createdOn = model.info.createdOn; + info.fps = model.info.fps; + info.version = model.info.version; + extras_write(info, model.info.extras); + return info; + }); + extras_write(root, model.extras); + return root; + } + + Anm2 anm2_get(const Model& model) + { + Anm2 anm2{}; + anm2.root = model_write(model); + anm2.isValid = model.isValid; + return anm2; + } + + Model model_from_anm2(const Anm2& anm2) + { + auto model = model_read(anm2.root); + model.isValid = anm2.isValid; + return model; + } + + Model model_make() { return model_from_anm2(Anm2()); } + + bool model_load(Model& model, const std::filesystem::path& path, std::string* errorString) + { + Anm2 anm2{}; + auto isLoaded = anm2.load(path, errorString); + model = model_from_anm2(anm2); + return isLoaded; + } + + bool model_load_string(Model& model, std::string_view text, std::string* errorString) + { + Anm2 anm2{}; + auto isLoaded = anm2.load_string(text, errorString); + model = model_from_anm2(anm2); + return isLoaded; + } + + bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options) + { + return anm2_get(model).save(path, errorString, options); + } + + std::string model_to_string(const Model& model, Options options) { return anm2_get(model).to_string(options); } + + std::string model_serialize(const Model& model, Flags flags) + { + return element_to_string(anm2_get(model).normalized_for_serialize(flags).root, flags); + } + + std::uint64_t model_hash(const Model& model, Options options) { return anm2_hash_get(model_write(model), options); } + + bool is_special_interpolated_frames(const Model& model) + { + for (auto [index, animation] : model.animations_get()) + { + bool isSpecial{}; + animation_tracks_each(*animation, + [&](const Track& track) + { + for (const auto& frame : track.frames) + isSpecial |= track.type != ItemType::TRIGGER && + frame.interpolation != Interpolation::NONE && + frame.interpolation != Interpolation::LINEAR; + }); + if (isSpecial) return true; + } + return false; + } + + std::string frame_to_string(const Frame& frame, ItemType type) + { + return element_to_string(frame_write(frame, type), track_element_type_get(type)); + } + + std::string animation_to_string(const Animation& animation, int groupId) + { + return element_to_string(animation_write(animation, groupId)); + } + + std::string animation_group_to_string(const AnimationGroup& group) + { + return element_to_string(animation_group_write(group)); + } + + bool document_parse(XMLDocument& document, const std::string& text, std::string* errorString) + { + if (document.Parse(text.c_str()) == XML_SUCCESS) return true; + if (errorString) *errorString = document.ErrorStr(); + return false; + } + + std::vector frames_from_string(const std::string& text, ItemType type, std::string* errorString) + { + XMLDocument document{}; + if (!document_parse(document, text, errorString)) return {}; + auto tag = element_tag_get(type == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME).data(); + std::vector frames{}; + for (auto element = document.FirstChildElement(tag); element; element = element->NextSiblingElement(tag)) + frames.push_back(frame_read(element_read(element))); + if (frames.empty() && errorString) *errorString = std::format("No valid {}(s).", tag); + return frames; + } + + // Animations and animation groups in clipboard order; an animation keeps the group id it was copied with. + std::vector animations_from_string(const std::string& text, std::string* errorString) + { + XMLDocument document{}; + if (!document_parse(document, text, errorString)) return {}; + auto container = element_make(ElementType::ANIMATIONS); + for (auto element = document.FirstChildElement(); element; element = element->NextSiblingElement()) + { + auto item = element_read(element); + if (item.type == ElementType::ANIMATION || item.type == ElementType::GROUP) + container.children.push_back(std::move(item)); + } + auto entries = animations_read(container).entries; + if (entries.empty() && errorString) *errorString = "No valid animation(s)."; + return entries; + } + + template std::string item_to_string(const Item& item) { return element_to_string(item_write(item)); } + + template std::vector items_from_string(const std::string& text, std::string* errorString) + { + XMLDocument document{}; + if (!document_parse(document, text, errorString)) return {}; + auto tag = element_tag_get(ITEM_TYPE).data(); + std::vector items{}; + for (auto element = document.FirstChildElement(tag); element; element = element->NextSiblingElement(tag)) + { + auto item = item_read(element_read(element)); + if constexpr (requires { item.path; }) item.path = util::path::backslash_handle(item.path); + items.push_back(std::move(item)); + } + if (items.empty() && errorString) *errorString = std::format("No valid {}(s).", tag); + return items; + } + +#define X(Item) \ + template std::string item_to_string(const Item&); \ + template std::vector items_from_string(const std::string&, std::string*); + X(Spritesheet) + X(Region) + X(Shader) + X(Layer) + X(Null) + X(Event) + X(Sound) +#undef X +} diff --git a/src/model/xml.hpp b/src/model/xml.hpp new file mode 100644 index 0000000..c239720 --- /dev/null +++ b/src/model/xml.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include +#include + +#include "model.hpp" + +// The only place the model meets XML: reading and writing documents (with the SourceDocument copy) and clipboard text. +namespace anm2ed::model +{ + Model model_make(); + bool model_load(Model&, const std::filesystem::path&, std::string* = nullptr); + bool model_load_string(Model&, std::string_view, std::string* = nullptr); + bool model_save(const Model&, const std::filesystem::path&, std::string* = nullptr, Options = {}); + std::string model_to_string(const Model&, Options = {}); + std::string model_serialize(const Model&, Flags); + std::uint64_t model_hash(const Model&, Options = {}); + bool is_special_interpolated_frames(const Model&); + + std::string frame_to_string(const Frame&, ItemType); + std::string animation_to_string(const Animation&, int = -1); + std::string animation_group_to_string(const AnimationGroup&); + std::vector frames_from_string(const std::string&, ItemType, std::string* = nullptr); + std::vector animations_from_string(const std::string&, std::string* = nullptr); + + template std::string item_to_string(const Item&); + template std::vector items_from_string(const std::string&, std::string* = nullptr); +} diff --git a/src/resource/shader.cpp b/src/resource/shader.cpp index 4ee6404..40dee0f 100644 --- a/src/resource/shader.cpp +++ b/src/resource/shader.cpp @@ -6,8 +6,8 @@ #include #include -#include "anm2/anm2.hpp" #include "log.hpp" +#include "model/model.hpp" namespace anm2ed::resource::shader { @@ -249,12 +249,12 @@ namespace anm2ed::resource::shader return binding == UNIFORM_BINDING_MANUAL || binding == UNIFORM_BINDING_PLAYBACK_TIME; } - void uniform_configs_apply(const Element& shaderElement, std::vector& uniforms) + void uniform_configs_apply(const model::Shader& shader, std::vector& uniforms) { for (auto& uniform : uniforms) { - auto config = shader_uniform_get(shaderElement, uniform.name); - if (!config) continue; + auto config = std::ranges::find(shader.uniforms, uniform.name, &model::Uniform::name); + if (config == shader.uniforms.end()) continue; if (auto binding = uniform_binding_get(config->binding); !config->binding.empty() && is_uniform_binding_valid(binding, uniform.valueType)) @@ -262,8 +262,8 @@ namespace anm2ed::resource::shader if (!config->value.empty()) uniform_value_parse(uniform, config->value); for (int index = 0; index < (int)uniform.components.size(); ++index) { - auto component = shader_uniform_component_get(*config, index); - if (!component) continue; + auto component = std::ranges::find(config->components, index, &model::Component::index); + if (component == config->components.end()) continue; if (auto binding = uniform_binding_get(component->binding); !component->binding.empty() && is_component_binding_valid(binding)) uniform.components[index].binding = binding; @@ -272,21 +272,19 @@ namespace anm2ed::resource::shader } } - bool uniform_configs_trim(Element& shaderElement, const std::vector& uniforms) + // Drops saved uniform settings the compiled shader no longer has or cannot use. + bool uniform_configs_trim(model::Shader& shader, const std::vector& uniforms) { - bool isChanged = std::erase_if(shaderElement.children, - [&](const Element& child) + bool isChanged = std::erase_if(shader.uniforms, + [&](const model::Uniform& config) { - return child.type == ElementType::UNIFORM && - std::ranges::none_of(uniforms, [&](const Uniform& uniform) - { return uniform.name == child.name; }); + return std::ranges::none_of(uniforms, [&](const Uniform& uniform) + { return uniform.name == config.name; }); }) > 0; - for (auto& config : shaderElement.children) + for (auto& config : shader.uniforms) { - if (config.type != ElementType::UNIFORM) continue; auto& uniform = *std::ranges::find(uniforms, config.name, &Uniform::name); - if (!config.binding.empty() && !is_uniform_binding_valid(uniform_binding_get(config.binding), uniform.valueType)) { config.binding.clear(); @@ -295,18 +293,13 @@ namespace anm2ed::resource::shader auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; auto isComponents = uniform_binding_get(config.binding) == UNIFORM_BINDING_COMPONENTS; - isChanged |= std::erase_if(config.children, - [&](const Element& component) - { - return component.type == ElementType::COMPONENT && - (!isComponents || component.index < 0 || component.index >= componentCount); - }) > 0; + isChanged |= + std::erase_if(config.components, [&](const model::Component& component) + { return !isComponents || component.index < 0 || component.index >= componentCount; }) > 0; - for (auto& component : config.children) + for (auto& component : config.components) { - if (component.type != ElementType::COMPONENT || component.binding.empty() || - is_component_binding_valid(uniform_binding_get(component.binding))) - continue; + if (component.binding.empty() || is_component_binding_valid(uniform_binding_get(component.binding))) continue; component.binding.clear(); isChanged = true; } @@ -315,27 +308,21 @@ namespace anm2ed::resource::shader return isChanged; } - void uniform_config_save(Element& shaderElement, const Uniform& uniform) + void uniform_config_save(model::Shader& shader, const Uniform& uniform) { - auto config = shader_uniform_get(shaderElement, uniform.name); - if (!config) - { - config = &shaderElement.children.emplace_back(element_make(ElementType::UNIFORM)); - config->name = uniform.name; - } + auto config = std::ranges::find(shader.uniforms, uniform.name, &model::Uniform::name); + if (config == shader.uniforms.end()) config = shader.uniforms.insert(shader.uniforms.end(), {.name = uniform.name}); config->binding = std::string(uniform_binding_value_get(uniform.binding)); config->value = uniform_value_string_get(uniform); - std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; }); + config->components.clear(); if (uniform.binding != UNIFORM_BINDING_COMPONENTS) return; for (int index = 0; index < (int)uniform.components.size(); ++index) - { - auto& component = config->children.emplace_back(element_make(ElementType::COMPONENT)); - component.index = index; - component.binding = std::string(uniform_binding_value_get(uniform.components[index].binding)); - component.value = std::format("{:.6g}", uniform.components[index].value); - } + config->components.push_back( + {.index = index, + .binding = std::string(uniform_binding_value_get(uniform.components[index].binding)), + .value = std::format("{:.6g}", uniform.components[index].value)}); } bool is_uniform_binding_valid(UniformBinding binding, UniformValueType type) diff --git a/src/resource/shader.hpp b/src/resource/shader.hpp index 70faa07..168aaf6 100644 --- a/src/resource/shader.hpp +++ b/src/resource/shader.hpp @@ -8,9 +8,9 @@ #include #include -namespace anm2ed +namespace anm2ed::model { - struct Element; + struct Shader; } namespace anm2ed::resource::shader @@ -366,9 +366,9 @@ namespace anm2ed::resource::shader {GRID_VERTEX, GRID_FRAGMENT}}; UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); - void uniform_configs_apply(const Element&, std::vector&); - bool uniform_configs_trim(Element&, const std::vector&); - void uniform_config_save(Element&, const Uniform&); + void uniform_configs_apply(const model::Shader&, std::vector&); + bool uniform_configs_trim(model::Shader&, const std::vector&); + void uniform_config_save(model::Shader&, const Uniform&); UniformBinding uniform_binding_get(std::string_view); std::string_view uniform_binding_value_get(UniformBinding); std::string_view uniform_binding_label_get(UniformBinding); diff --git a/src/selection.cpp b/src/selection.cpp index 7098e03..c180167 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -2,7 +2,8 @@ namespace anm2ed { - std::set selection_references_get(const Selection& selection, const UidIndex& index, SelectionKind kind) + std::set selection_references_get(const Selection& selection, const model::UidIndex& index, + SelectionKind kind) { std::set references{}; if (auto uids = selection.uids.find(kind); uids != selection.uids.end()) @@ -16,31 +17,31 @@ namespace anm2ed return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; } - void selection_references_set(Selection& selection, const Anm2& anm2, SelectionKind kind, + void selection_references_set(Selection& selection, const model::Model& model, SelectionKind kind, const std::set& references) { auto& uids = selection.uids[kind]; uids.clear(); for (auto reference : references) - if (auto uid = handle_uid_get(anm2.handle_get(reference, kind == SelectionKind::GROUPS))) uids.insert(uid); + if (auto uid = handle_uid_get(model.handle_get(reference, kind == SelectionKind::GROUPS))) uids.insert(uid); } // The most specific part of the focus that still exists. - Reference selection_focus_get(const Selection& selection, const UidIndex& index) + Reference selection_focus_get(const Selection& selection, const model::UidIndex& index) { for (auto uid : {selection.focus.frame, selection.focus.item, selection.focus.animation}) if (auto reference = index.reference_get(uid)) return *reference; return {}; } - void selection_focus_set(Selection& selection, const Anm2& anm2, Reference reference) + void selection_focus_set(Selection& selection, const model::Model& model, Reference reference) { - selection.focus = anm2.handle_get(reference); + selection.focus = model.handle_get(reference); } // After an edit: drops uids that no longer exist, and moves a focus whose element was removed to its nearest // survivor (a frame at the same index of its track, the animation's root track, or the nearest animation). - void selection_follow(Selection& selection, const Anm2& anm2, const UidIndex& index, Reference before) + void selection_follow(Selection& selection, const model::Model& model, const model::UidIndex& index, Reference before) { for (auto& [kind, uids] : selection.uids) std::erase_if(uids, [&](std::uint64_t uid) { return !index.contains(uid); }); @@ -51,8 +52,7 @@ namespace anm2ed if (is_removed(animationUid) || !animationUid) { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - auto count = animations ? animations_count_get(*animations) : 0; + auto count = model.animations_count_get(); reference = count > 0 && animationUid ? Reference{std::clamp(before.animationIndex, 0, count - 1), ROOT} : Reference{}; } @@ -60,13 +60,13 @@ namespace anm2ed reference = {reference.animationIndex, ROOT}; else if (is_removed(frameUid)) { - auto track = anm2.element_get(reference); - auto count = track ? track_frames_count_get(*track) : 0; + auto track = model.track_get(reference); + auto count = track ? (int)track->frames.size() : 0; reference.frameIndex = count > 0 ? std::clamp(before.frameIndex, 0, count - 1) : -1; } else return; - selection_focus_set(selection, anm2, reference); + selection_focus_set(selection, model, reference); } } diff --git a/src/selection.hpp b/src/selection.hpp index 79e187b..b7b4e35 100644 --- a/src/selection.hpp +++ b/src/selection.hpp @@ -3,7 +3,7 @@ #include #include -#include "anm2/anm2.hpp" +#include "model/model.hpp" namespace anm2ed { @@ -26,9 +26,9 @@ namespace anm2ed bool operator==(const Selection&) const = default; }; - std::set selection_references_get(const Selection&, const UidIndex&, SelectionKind); - void selection_references_set(Selection&, const Anm2&, SelectionKind, const std::set&); - Reference selection_focus_get(const Selection&, const UidIndex&); - void selection_focus_set(Selection&, const Anm2&, Reference); - void selection_follow(Selection&, const Anm2&, const UidIndex&, Reference); + std::set selection_references_get(const Selection&, const model::UidIndex&, SelectionKind); + void selection_references_set(Selection&, const model::Model&, SelectionKind, const std::set&); + Reference selection_focus_get(const Selection&, const model::UidIndex&); + void selection_focus_set(Selection&, const model::Model&, Reference); + void selection_follow(Selection&, const model::Model&, const model::UidIndex&, Reference); } diff --git a/src/settings.hpp b/src/settings.hpp index 3289126..0a168d5 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -5,7 +5,7 @@ #include -#include "anm2/anm2.hpp" +#include "model/common.hpp" #include "origin.hpp" #include "render.hpp" #include "strings.hpp" diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 985776e..5b389fb 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -1,24 +1,22 @@ #include "snapshots.hpp" -#include #include -#include - namespace anm2ed::snapshots { - bool is_vec2_equal(const glm::vec2& left, const glm::vec2& right) { return glm::all(glm::equal(left, right)); } + template bool is_value_equal(const T& left, const T& right) { return left == right; } - bool is_vec3_equal(const glm::vec3& left, const glm::vec3& right) { return glm::all(glm::equal(left, right)); } + bool is_value_equal(const model::Model& left, const model::Model& right) + { + return model::is_model_equal(left, right); + } - bool is_vec4_equal(const glm::vec4& left, const glm::vec4& right) { return glm::all(glm::equal(left, right)); } - - bool is_playback_equal(const Playback& left, const Playback& right) + bool is_value_equal(const Playback& left, const Playback& right) { return left.time == right.time && left.isPlaying == right.isPlaying && left.isFinished == right.isFinished; } - bool is_storage_equal(const Storage& left, const Storage& right) + bool is_value_equal(const Storage& left, const Storage& right) { return left.reference == right.reference && left.hovered == right.hovered && left.labelsString == right.labelsString && left.ids == right.ids && @@ -26,118 +24,34 @@ namespace anm2ed::snapshots left.references == right.references; } - template bool is_value_equal(const T& left, const T& right) { return left == right; } - - bool is_value_equal(const Playback& left, const Playback& right) { return is_playback_equal(left, right); } - - bool is_value_equal(const Storage& left, const Storage& right) { return is_storage_equal(left, right); } - - bool is_element_shallow_equal(const Element& left, const Element& right) + bool is_step_empty(const SnapshotStep& step) { - return left.type == right.type && left.tag == right.tag && left.name == right.name && - left.createdBy == right.createdBy && left.createdOn == right.createdOn && left.path == right.path && - left.vertex == right.vertex && left.fragment == right.fragment && left.binding == right.binding && - left.value == right.value && left.defaultAnimation == right.defaultAnimation && left.id == right.id && - left.layerId == right.layerId && left.nullId == right.nullId && left.spritesheetId == right.spritesheetId && - left.fps == right.fps && left.version == right.version && left.frameNum == right.frameNum && - left.duration == right.duration && left.atFrame == right.atFrame && left.eventId == right.eventId && - left.regionId == right.regionId && left.shaderId == right.shaderId && left.soundId == right.soundId && - left.groupId == right.groupId && left.index == right.index && left.isLoop == right.isLoop && - left.isVisible == right.isVisible && left.isShowRect == right.isShowRect && - left.isExpanded == right.isExpanded && left.isEnabled == right.isEnabled && - left.interpolation == right.interpolation && left.origin == right.origin && - left.rotation == right.rotation && left.soundIds == right.soundIds && - is_vec2_equal(left.pivot, right.pivot) && is_vec2_equal(left.crop, right.crop) && - is_vec2_equal(left.position, right.position) && is_vec2_equal(left.size, right.size) && - is_vec2_equal(left.scale, right.scale) && is_vec2_equal(left.shear, right.shear) && - is_vec3_equal(left.colorOffset, right.colorOffset) && is_vec4_equal(left.tint, right.tint); - } - - bool is_element_recurseable(const Element& left, const Element& right) - { - if (left.type != right.type) return false; - if (left.children.size() != right.children.size()) return false; - - for (size_t i = 0; i < left.children.size(); ++i) - if (left.children[i].type != right.children[i].type) return false; - - return true; - } - - bool is_element_equal(const Element& left, const Element& right) - { - if (!is_element_shallow_equal(left, right)) return false; - if (left.children.size() != right.children.size()) return false; - - for (size_t i = 0; i < left.children.size(); ++i) - if (!is_element_equal(left.children[i], right.children[i])) return false; - - return true; - } - - void element_steps_build(std::vector& out, const Element& before, const Element& after, - std::vector& path) - { - if (!is_element_recurseable(before, after) || !is_element_shallow_equal(before, after)) - { - out.push_back({path, before, after}); - return; - } - - for (size_t i = 0; i < before.children.size(); ++i) - { - path.push_back((int)i); - element_steps_build(out, before.children[i], after.children[i], path); - path.pop_back(); - } - } - - template ElementPointer element_get(E& root, const std::vector& path) - { - auto element = &root; - for (auto index : path) - { - if (index < 0 || index >= (int)element->children.size()) return nullptr; - element = &element->children[index]; - } - return element; - } - - SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) - { - SnapshotAnm2Step step{}; - if (before.isValid != after.isValid) step.isValid = SnapshotStepValue{before.isValid, after.isValid}; - - std::vector path{}; - element_steps_build(step.elements, before.root, after.root, path); - return step; - } - - void step_state_seed(SnapshotStep& step, const Snapshot& snapshot) - { -#define X(type, name) step.name = SnapshotStepValue{snapshot.name, {}}; +#define X(type, name) \ + if (!is_value_equal(step.before.name, step.after.name)) return false; SNAPSHOT_STEP_STATE_FIELDS #undef X + return true; } - SnapshotStep step_anm2_make(const Snapshot& snapshot) + void step_apply(Snapshot& current, const SnapshotStep& step, bool isUndo) { - SnapshotStep step{}; - step.anm2.isValid = SnapshotStepValue{snapshot.anm2.isValid, {}}; - step.anm2.elements.push_back({{}, snapshot.anm2.root, {}}); - step_state_seed(step, snapshot); - return step; + const auto& target = isUndo ? step.before : step.after; +#define X(type, name) \ + if (!is_value_equal(step.before.name, step.after.name)) current.name = target.name; + SNAPSHOT_STEP_STATE_FIELDS +#undef X + current.message = step.after.message; } Reference focus_get(const Snapshot& snapshot) { - return selection_focus_get(snapshot.selection, UidIndex(snapshot.anm2)); + return selection_focus_get(snapshot.selection, model::UidIndex(snapshot.model)); } void selection_follow(Snapshot& snapshot, Reference before) { - snapshot.anm2.uids_repair(); - ::anm2ed::selection_follow(snapshot.selection, snapshot.anm2, UidIndex(snapshot.anm2), before); + snapshot.model.uids_repair(); + ::anm2ed::selection_follow(snapshot.selection, snapshot.model, model::UidIndex(snapshot.model), before); } } @@ -145,179 +59,84 @@ namespace anm2ed { int SnapshotStack::maxSize = snapshots::MAX; - bool SnapshotAnm2Step::is_empty() const { return !isValid && elements.empty(); } - - void SnapshotAnm2Step::apply(Anm2& anm2, SnapshotStepDirection direction) const - { - if (isValid) anm2.isValid = direction == SnapshotStepDirection::UNDO ? isValid->undo : isValid->redo; - - for (auto& elementStep : elements) - if (auto* element = snapshots::element_get(anm2.root, elementStep.path); element) - *element = direction == SnapshotStepDirection::UNDO ? elementStep.undo : elementStep.redo; - } - - bool SnapshotStep::is_empty() const - { - if (!anm2.is_empty()) return false; - -#define X(type, name) \ - if (this->name) return false; - SNAPSHOT_STEP_STATE_FIELDS -#undef X - - return true; - } - - void SnapshotStep::apply(Snapshot& snapshot, SnapshotStepDirection direction) const - { - snapshot.message = message; - anm2.apply(snapshot.anm2, direction); - -#define X(type, name) \ - if (this->name) snapshot.name = direction == SnapshotStepDirection::UNDO ? this->name->undo : this->name->redo; - SNAPSHOT_STEP_STATE_FIELDS -#undef X - } - bool SnapshotStack::is_empty() { return stack.empty(); } + std::size_t SnapshotStack::size() const { return stack.size(); } void SnapshotStack::push(SnapshotStep step) { - if (maxSize <= 0) - { - stack.clear(); - return; - } - if ((int)stack.size() >= maxSize) stack.pop_front(); stack.push_back(std::move(step)); + trim_to_limit(); } std::optional SnapshotStack::pop() { - if (is_empty()) return std::nullopt; - auto snapshot = std::move(stack.back()); + if (stack.empty()) return std::nullopt; + auto step = std::move(stack.back()); stack.pop_back(); - return snapshot; + return step; } void SnapshotStack::clear() { stack.clear(); } void SnapshotStack::trim_to_limit() { - if (maxSize <= 0) - { - clear(); - return; - } - while ((int)stack.size() > maxSize) stack.pop_front(); } - void SnapshotStack::max_size_set(int value) { maxSize = std::max(0, value); } - + void SnapshotStack::max_size_set(int value) { maxSize = std::max(value, 0); } int SnapshotStack::max_size_get() { return maxSize; } - void Snapshots::step_push(const std::string& message, SnapshotStep step) + // Starts an undoable edit: remembers the state before it (cheap; animations are shared). + void Snapshots::push(const std::string& message) { - if (pendingStep || pendingFocus) commit(); + if (pending || pendingFocus) commit(); pendingFocus = snapshots::focus_get(current); current.message = message; - step.message = message; - pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + pending = current; } - void Snapshots::push(const std::string& message) { step_push(message, snapshots::step_anm2_make(current)); } - void Snapshots::commit() { - const auto& snapshot = current; if (pendingFocus) snapshots::selection_follow(current, *std::exchange(pendingFocus, std::nullopt)); - if (!pendingStep) return; - - auto step = std::move(*pendingStep); - pendingStep.reset(); - - Anm2 before{}; - before.isValid = step.anm2.isValid ? step.anm2.isValid->undo : snapshot.anm2.isValid; - before.root = std::move(step.anm2.elements.front().undo); - step.anm2 = snapshots::anm2_step_make(before, snapshot.anm2); - - if (step.anm2.isValid) - { - step.anm2.isValid->redo = snapshot.anm2.isValid; - if (step.anm2.isValid->undo == step.anm2.isValid->redo) step.anm2.isValid.reset(); - } - - for (auto it = step.anm2.elements.begin(); it != step.anm2.elements.end();) - { - auto* element = snapshots::element_get(snapshot.anm2.root, it->path); - if (!element) - { - it = step.anm2.elements.erase(it); - continue; - } - - it->redo = *element; - if (snapshots::is_element_equal(it->undo, it->redo)) - { - it = step.anm2.elements.erase(it); - continue; - } - - ++it; - } - -#define X(type, name) \ - if (step.name) \ - { \ - step.name->redo = snapshot.name; \ - if (snapshots::is_value_equal(step.name->undo, step.name->redo)) step.name.reset(); \ - } - SNAPSHOT_STEP_STATE_FIELDS -#undef X - - if (step.is_empty()) return; - + if (!pending) return; + SnapshotStep step{std::move(*std::exchange(pending, std::nullopt)), current}; + if (snapshots::is_step_empty(step)) return; undoStack.push(std::move(step)); redoStack.clear(); } bool Snapshots::undo() { - pendingStep.reset(); + pending.reset(); pendingFocus.reset(); - if (auto step = undoStack.pop()) - { - auto focus = snapshots::focus_get(current); - step->apply(current, SnapshotStepDirection::UNDO); - snapshots::selection_follow(current, focus); - redoStack.push(std::move(*step)); - return true; - } - return false; + auto step = undoStack.pop(); + if (!step) return false; + auto focus = snapshots::focus_get(current); + snapshots::step_apply(current, *step, true); + snapshots::selection_follow(current, focus); + redoStack.push(std::move(*step)); + return true; } bool Snapshots::redo() { - pendingStep.reset(); + pending.reset(); pendingFocus.reset(); - if (auto step = redoStack.pop()) - { - auto focus = snapshots::focus_get(current); - step->apply(current, SnapshotStepDirection::REDO); - snapshots::selection_follow(current, focus); - undoStack.push(std::move(*step)); - return true; - } - return false; + auto step = redoStack.pop(); + if (!step) return false; + auto focus = snapshots::focus_get(current); + snapshots::step_apply(current, *step, false); + snapshots::selection_follow(current, focus); + undoStack.push(std::move(*step)); + return true; } void Snapshots::reset() { undoStack.clear(); redoStack.clear(); - pendingStep.reset(); + pending.reset(); pendingFocus.reset(); } diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 728748c..2dd1c67 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -3,10 +3,9 @@ #include #include #include -#include -#include +#include -#include "anm2/anm2.hpp" +#include "model/model.hpp" #include "playback.hpp" #include "selection.hpp" #include "storage.hpp" @@ -19,57 +18,10 @@ namespace anm2ed::snapshots namespace anm2ed { - enum class SnapshotStepDirection - { - UNDO, - REDO - }; - - template struct SnapshotStepValue - { - T undo{}; - T redo{}; - }; - - struct SnapshotElementStep - { - std::vector path{}; - Element undo{}; - Element redo{}; - }; - - struct SnapshotAnm2Step - { - std::optional> isValid{}; - std::vector elements{}; - - bool is_empty() const; - void apply(Anm2&, SnapshotStepDirection) const; - }; - - class Snapshot - { - public: - Playback playback{}; - Storage event{}; - Storage layer{}; - Storage merge{}; - Storage null{}; - Storage region{}; - Storage shader{}; - Storage sound{}; - Storage spritesheet{}; - std::map textures{}; - std::map sounds{}; - Anm2 anm2{}; - Selection selection{}; - float frameTime{}; - std::string message = snapshots::ACTION; - }; - using AssetKeys = std::map; #define SNAPSHOT_STEP_STATE_FIELDS \ + X(model::Model, model) \ X(Playback, playback) \ X(Storage, event) \ X(Storage, layer) \ @@ -84,25 +36,27 @@ namespace anm2ed X(AssetKeys, textures) \ X(AssetKeys, sounds) - struct SnapshotStep + // Everything undo restores. The model's animations are shared between snapshots and copied only when edited. + struct Snapshot { - std::string message = snapshots::ACTION; - SnapshotAnm2Step anm2{}; - -#define X(type, name) std::optional> name{}; +#define X(type, name) type name{}; SNAPSHOT_STEP_STATE_FIELDS #undef X + std::string message = snapshots::ACTION; + }; - bool is_empty() const; - void apply(Snapshot&, SnapshotStepDirection) const; + // One undoable edit: the state before and after it; undo/redo restore only the fields the edit changed. + struct SnapshotStep + { + Snapshot before{}; + Snapshot after{}; }; class SnapshotStack { public: - SnapshotStack() = default; - bool is_empty(); + std::size_t size() const; void push(SnapshotStep); std::optional pop(); void clear(); @@ -122,11 +76,10 @@ namespace anm2ed SnapshotStack undoStack{}; SnapshotStack redoStack{}; Snapshot current{}; - std::optional pendingStep{}; + std::optional pending{}; std::optional pendingFocus{}; void push(const std::string&); - void step_push(const std::string&, SnapshotStep); void commit(); bool undo(); bool redo(); diff --git a/src/storage.hpp b/src/storage.hpp index 5cd4987..7cea83b 100644 --- a/src/storage.hpp +++ b/src/storage.hpp @@ -1,8 +1,10 @@ #pragma once #include +#include +#include -#include "anm2/anm2.hpp" +#include "model/common.hpp" #include "util/imgui/multiselect.hpp" namespace anm2ed diff --git a/tests/common.hpp b/tests/common.hpp index 809d333..a5ad9f6 100644 --- a/tests/common.hpp +++ b/tests/common.hpp @@ -8,7 +8,8 @@ #include #include -#include "anm2/anm2.hpp" +#include "edit/edit.hpp" +#include "model/xml.hpp" #include "util/xml.hpp" namespace anm2ed::test @@ -52,32 +53,33 @@ namespace anm2ed::test return fixtures; } - inline Anm2 anm2_load(const std::string& text) + inline model::Model model_load(const std::string& text) { - Anm2 anm2{}; - REQUIRE(anm2.load_string(text)); - return anm2; + model::Model model{}; + REQUIRE(model::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 variants_get(const Anm2& anm2) + inline std::vector variants_get(const model::Model& model) { std::vector variants{}; std::string hashes{}; for (auto [name, flags] : PRESETS) { - variants.emplace_back(name, element_to_string(anm2.normalized_for_serialize(flags).root, flags)); + variants.emplace_back(name, model::model_serialize(model, flags)); for (auto [formatName, isExtended] : FORMATS) - hashes += std::format("{}.{} {:016x}\n", name, formatName, anm2.hash({flags, isExtended})); + hashes += std::format("{}.{} {:016x}\n", name, formatName, model::model_hash(model, {flags, isExtended})); } for (auto [name, isExtended] : FORMATS) - variants.emplace_back(name, anm2.to_string({.isExtendedFormat = isExtended})); + variants.emplace_back(name, model::model_to_string(model, {.isExtendedFormat = isExtended})); for (auto [name, type] : MERGES) { - auto merged = anm2; + auto merged = model; std::set sources{0, 1, 2}; - merged.animations_merge(0, sources, type, type == types::merge::PREPEND || type == types::merge::REPLACE); - variants.emplace_back(name, merged.to_string({.isExtendedFormat = true})); + edit::animations_merge(merged, 0, sources, type, type == types::merge::PREPEND || type == types::merge::REPLACE, + {}); + variants.emplace_back(name, model::model_to_string(merged, {.isExtendedFormat = true})); } variants.emplace_back("hashes", hashes); return variants; @@ -94,25 +96,23 @@ namespace anm2ed::test } // Save/reload properties every document must hold. - inline void invariants_check(const Anm2& anm2) + inline void invariants_check(const model::Model& model) { for (auto [name, isExtended] : FORMATS) { INFO("format: ", std::string(name)); // The first save may repair invalid input (dangling ids, duplicates); after that, saves must be fixed points. - auto text = anm2.to_string({.isExtendedFormat = isExtended}); - auto reloaded = anm2_load(text); - auto resaved = reloaded.to_string({.isExtendedFormat = isExtended}); + auto text = model::model_to_string(model, {.isExtendedFormat = isExtended}); + auto reloaded = model_load(text); + auto resaved = model::model_to_string(reloaded, {.isExtendedFormat = isExtended}); CHECK(resaved == text); - CHECK(anm2_load(resaved).hash() == reloaded.hash()); + CHECK(model::model_hash(model_load(resaved)) == model::model_hash(reloaded)); } // Loading only the game's view and re-saving it for the game must not change it. - auto game = game_document_get(anm2.to_string()); - auto gameAnm2 = anm2_load(game); - CHECK(element_to_string(gameAnm2.normalized_for_serialize(SERIALIZE_ISAAC_DEFAULT).root, SERIALIZE_ISAAC_DEFAULT) == - game); + auto game = game_document_get(model::model_to_string(model)); + CHECK(model::model_serialize(model_load(game), SERIALIZE_ISAAC_DEFAULT) == game); } // Compares against a stored golden; ANM2ED_UPDATE_GOLDEN (or a missing golden when isBootstrap) rewrites it. diff --git a/tests/corpus_local.cpp b/tests/corpus_local.cpp index f3bc5d9..930a3ee 100644 --- a/tests/corpus_local.cpp +++ b/tests/corpus_local.cpp @@ -17,9 +17,9 @@ TEST_CASE("local corpus matches baselines" * doctest::skip(!is_env_set("ANM2ED_C if (line.empty()) continue; INFO("file: ", line); auto key = std::format("{:016x}", std::hash{}(line)); - Anm2 anm2{}; + model::Model anm2{}; std::string error{}; - if (!anm2.load(line, &error)) + if (!model::model_load(anm2, line, &error)) { golden_check(baseline / (key + ".error.txt"), error, true); continue; diff --git a/tests/invariants.cpp b/tests/invariants.cpp index f1959e8..69b6389 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -8,6 +8,6 @@ TEST_CASE("per-fixture invariants") for (const auto& fixture : fixtures_get()) { INFO("fixture: ", fixture.filename().string()); - invariants_check(anm2_load(file_load(fixture))); + invariants_check(model_load(file_load(fixture))); } } diff --git a/tests/operations.cpp b/tests/operations.cpp index 3bf4b3a..fbb4efc 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -1,29 +1,31 @@ #include "common.hpp" -#include "edit/edit.hpp" +#include "model/frames.hpp" #include "util/pack.hpp" using namespace anm2ed; using namespace anm2ed::test; -Anm2 fixture_load(const char* name) { return anm2_load(file_load(CORPUS_DIR / name)); } +model::Model fixture_load(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } -void operation_check(const char* name, const Anm2& anm2) +void operation_check(const char* name, const model::Model& model) { - golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), anm2.to_string({.isExtendedFormat = true})); + golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), + model::model_to_string(model, {.isExtendedFormat = true})); } -Element& layer_track_get(Anm2& anm2, int animationIndex, int layerId) +model::Track& layer_track_get(model::Model& model, int animationIndex, int layerId) { - auto track = animation_item_get(*anm2.element_get(ElementType::ANIMATION, animationIndex), ItemType::LAYER, layerId); + auto track = model.track_edit({animationIndex, LAYER, layerId}); REQUIRE(track); return *track; } -int groups_named_count(const Element& element, std::string_view name) +int groups_named_count(const model::Animation& animation, std::string_view name) { int count{}; - element_each(element, [&](const Element& child) { count += child.type == ElementType::GROUP && child.name == name; }); + for (const auto* entries : {&animation.layers, &animation.nulls}) + model::groups_each(*entries, [&](const model::TrackGroup& group) { count += group.name == name; }); return count; } @@ -32,10 +34,9 @@ TEST_CASE("animations_merge keeps one group per name") for (auto [name, type] : MERGES) { INFO("merge: ", std::string(name)); - auto anm2 = fixture_load("03a_groups_nested.anm2"); - std::set sources{0, 1}; - anm2.animations_merge(0, sources, type, false); - CHECK(groups_named_count(*anm2.element_get(ElementType::ANIMATION, 0), "Main") == 1); + auto model = fixture_load("03a_groups_nested.anm2"); + edit::animations_merge(model, 0, {0, 1}, type, false, {}); + CHECK(groups_named_count(*model.animation_get(0), "Main") == 1); } } @@ -47,34 +48,31 @@ TEST_CASE("file_merge presets") {"file_merge_replace", FILE_MERGE_PRESET_REPLACE_MATCHING}}; for (auto [name, preset] : PRESETS_FILE_MERGE) { - auto anm2 = fixture_load("02_items.anm2"); - CHECK(anm2.file_merge(CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); - operation_check(name, anm2); + auto model = fixture_load("02_items.anm2"); + CHECK(edit::file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); + operation_check(name, model); } } TEST_CASE("item_add") { - auto anm2 = fixture_load("02_items.anm2"); - auto layer = element_make(ElementType::LAYER_ELEMENT); - layer.name = "added"; - layer.spritesheetId = 1; - CHECK(anm2.item_add(ItemType::LAYER, 0, layer, 1, types::destination::ALL) == 2); - auto null = element_make(ElementType::NULL_ELEMENT); - null.name = "thisOnly"; - CHECK(anm2.item_add(ItemType::NULL_, 1, null, -1, types::destination::THIS) == 2); - operation_check("item_add", anm2); + auto model = fixture_load("02_items.anm2"); + CHECK(edit::item_add(model, ItemType::LAYER, 0, -1, "added", 1, false, 1, types::destination::ALL) == 2); + CHECK(edit::item_add(model, ItemType::NULL_, 1, -1, "thisOnly", 0, false, -1, types::destination::THIS) == 2); + operation_check("item_add", model); } TEST_CASE("regions_generate and regions_scan") { - auto anm2 = fixture_load("02_items.anm2"); - CHECK(anm2.regions_generate({0}, {}, "Region {}", RegionFrameMapping::SET)); - CHECK_FALSE(anm2.regions_generate({0}, {}, "Region {}", RegionFrameMapping::SET)); - operation_check("regions_generate", anm2); + auto model = fixture_load("02_items.anm2"); + edit::regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + auto generated = model; + edit::regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + CHECK(model::is_model_equal(model, generated)); + operation_check("regions_generate", model); auto scanned = fixture_load("05_regions.anm2"); - scanned.regions_scan(); + edit::regions_scan(scanned); operation_check("regions_scan", scanned); } @@ -87,30 +85,30 @@ TEST_CASE("frames_change") {"divide", ChangeType::DIVIDE}}; for (auto [name, type] : CHANGES) { - auto anm2 = fixture_load("02_items.anm2"); + 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(anm2, 0, 0), change, ItemType::LAYER, type, {0, 1}); - operation_check(std::format("frames_change_{}", name).c_str(), anm2); + model::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 anm2 = fixture_load("07_special_interpolation.anm2"); - frame_bake(layer_track_get(anm2, 0, 0), 0, 2, true, false); - frame_bake(layer_track_get(anm2, 0, 0), 3, 1, false, true); - operation_check("frame_bake", anm2); + auto model = fixture_load("07_special_interpolation.anm2"); + model::frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false); + model::frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true); + operation_check("frame_bake", model); - auto from = element_make(ElementType::FRAME); - auto to = element_make(ElementType::FRAME); + model::Frame from{}; + model::Frame to{}; to.position = {10.0f, -20.0f}; to.shear = {30.0f, 0.0f}; to.rotation = 90.0f; to.tint = {0.0f, 1.0f, 1.0f, 0.5f}; - frame_mix(from, to, 0.5f); + model::frame_mix(from, to, 0.5f); CHECK(from.position == glm::vec2(5.0f, -10.0f)); CHECK(from.shear == glm::vec2(15.0f, 0.0f)); CHECK(from.rotation == doctest::Approx(45.0f)); @@ -144,80 +142,83 @@ TEST_CASE("edit layer operations") { const char* name; const char* fixture; - std::function operation; + std::function operation; std::size_t uidCount; }; const Reference head{0, LAYER, 0}; const Case CASES[] = { - {"frame_insert", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, - {"trigger_insert", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, - 1}, + {"frame_insert", "02_items.anm2", + [&](model::Model& anm2) { return edit::frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, + {"trigger_insert", "02_items.anm2", + [&](model::Model& anm2) { return edit::frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1}, {"frames_delete", "02_items.anm2", - [&](Anm2& anm2) { return edit::frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, - {"frames_duplicate", "02_items.anm2", [&](Anm2& anm2) + [&](model::Model& anm2) { return edit::frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, + {"frames_duplicate", "02_items.anm2", [&](model::Model& anm2) { return edit::frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2}, {"frames_reverse", "07_special_interpolation.anm2", - [&](Anm2& anm2) { return edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, - {"frames_bake", "07_special_interpolation.anm2", - [&](Anm2& anm2) { return edit::frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, - {"frame_split", "02_items.anm2", [&](Anm2& anm2) { return edit::frame_split(anm2, {0, LAYER, 1, 0}, 2); }, 1}, + [&](model::Model& anm2) { return edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, + {"frames_bake", "07_special_interpolation.anm2", [&](model::Model& anm2) + { return edit::frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, + {"frame_split", "02_items.anm2", [&](model::Model& anm2) { return edit::frame_split(anm2, {0, LAYER, 1, 0}, 2); }, + 1}, {"frames_move", "02_items.anm2", - [&](Anm2& anm2) { return edit::frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, + [&](model::Model& anm2) { return edit::frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, {"frames_paste", "02_items.anm2", - [&](Anm2& anm2) + [&](model::Model& anm2) { - auto frame = anm2.element_get(Reference{0, LAYER, 1, 0}); - auto text = element_to_string(*frame, ElementType::LAYER_ANIMATION) + - element_to_string(*frame, ElementType::LAYER_ANIMATION); + auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0}); + auto text = model::frame_to_string(*frame, ItemType::LAYER) + model::frame_to_string(*frame, ItemType::LAYER); return edit::frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); }, 2}, {"root_bake_into", "04_group_root_transform.anm2", - [&](Anm2& anm2) + [&](model::Model& anm2) { return edit::root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, {.isRoundScale = true, .isMatchRootInterpolation = true}); }, 1}, {"items_group", "03b_groups_legacy_flat.anm2", - [&](Anm2& anm2) { return edit::items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, - {"items_move", "03b_groups_legacy_flat.anm2", - [&](Anm2& anm2) { return edit::items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, + [&](model::Model& anm2) { return edit::items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, + {"items_move", "03b_groups_legacy_flat.anm2", [&](model::Model& anm2) + { return edit::items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, {"items_remove", "03b_groups_legacy_flat.anm2", - [&](Anm2& anm2) { return edit::items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, + [&](model::Model& anm2) { return edit::items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, {"animation_add", "03a_groups_nested.anm2", - [&](Anm2& anm2) { return edit::animation_add(anm2, 1, 0, 0, "Added"); }, 1}, + [&](model::Model& anm2) { return edit::animation_add(anm2, 1, 0, 0, "Added"); }, 1}, {"animations_remove", "03a_groups_nested.anm2", - [&](Anm2& anm2) { return edit::animations_remove(anm2, {1}, {0}); }, 0}, - {"animations_move", "02_items.anm2", [&](Anm2& anm2) { return edit::animations_move(anm2, {0}, {}, 2, -1); }, 1}, - {"animations_group", "02_items.anm2", [&](Anm2& anm2) { return edit::animations_group(anm2, {0, 1}, "Group"); }, - 0}, + [&](model::Model& anm2) { return edit::animations_remove(anm2, {1}, {0}); }, 0}, + {"animations_move", "02_items.anm2", [&](model::Model& anm2) + { return edit::animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1}, + {"animations_group", "02_items.anm2", + [&](model::Model& anm2) { return edit::animations_group(anm2, {0, 1}, "Group"); }, 0}, {"animations_paste", "02_items.anm2", - [&](Anm2& anm2) + [&](model::Model& anm2) { std::set groupIds{}; - auto text = element_to_string(*anm2.element_get(ElementType::ANIMATION, 1)); + auto text = model::animation_to_string(*anm2.animation_get(1)); return edit::animations_paste(anm2, text, 0, -1, groupIds, nullptr); }, 1}, - {"regions_remove_unused", "05_regions.anm2", [&](Anm2& anm2) { return edit::regions_remove_unused(anm2, 0); }, 0}, + {"regions_remove_unused", "05_regions.anm2", + [&](model::Model& anm2) { return edit::regions_remove_unused(anm2, 0); }, 0}, {"regions_paste", "05_regions.anm2", - [&](Anm2& anm2) + [&](model::Model& anm2) { - auto region = child_id_get(*anm2.element_get(ElementType::SPRITESHEET, 0), ElementType::REGION, 1); - return edit::regions_paste(anm2, 0, element_to_string(*region), 1, nullptr); + auto region = model::item_get(model::item_get(anm2.content.spritesheets, 0)->regions, 1); + return edit::regions_paste(anm2, 0, model::item_to_string(*region), 1, nullptr); }, 0}, {"animation_grid_generate", "05_regions.anm2", - [&](Anm2& anm2) + [&](model::Model& anm2) { return edit::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", - [&](Anm2& anm2) + [&](model::Model& anm2) { FrameChange change{.positionX = 3.0f, .rotation = 10.0f}; return edit::frames_change_apply( @@ -226,18 +227,17 @@ TEST_CASE("edit layer operations") }, 0}, {"animations_merge", "03a_groups_nested.anm2", - [&](Anm2& anm2) { return edit::animations_merge(anm2, 0, {1}, types::merge::APPEND, true, {0}); }, 1}, + [&](model::Model& anm2) { return edit::animations_merge(anm2, 0, {1}, types::merge::APPEND, true, {0}); }, 1}, }; for (const auto& entry : CASES) { INFO("operation: ", std::string(entry.name)); auto anm2 = fixture_load(entry.fixture); - anm2.uids_repair(); auto uids = entry.operation(anm2); CHECK(uids.size() == entry.uidCount); anm2.uids_repair(); - UidIndex index(anm2); + model::UidIndex index(anm2); for (auto uid : uids) CHECK(index.reference_get(uid)); operation_check(entry.name, anm2); diff --git a/tests/roundtrip.cpp b/tests/roundtrip.cpp index cc2fb3e..cc66e4b 100644 --- a/tests/roundtrip.cpp +++ b/tests/roundtrip.cpp @@ -9,7 +9,7 @@ TEST_CASE("fixtures match goldens") REQUIRE(!fixtures.empty()); for (const auto& fixture : fixtures) { - auto anm2 = anm2_load(file_load(fixture)); + auto anm2 = model_load(file_load(fixture)); for (const auto& [name, text] : variants_get(anm2)) golden_check(GOLDEN_DIR / std::format("{}.{}.xml", fixture.stem().string(), name), text); } diff --git a/tests/selection.cpp b/tests/selection.cpp index 0d624ab..bea624e 100644 --- a/tests/selection.cpp +++ b/tests/selection.cpp @@ -6,31 +6,32 @@ using namespace anm2ed; using namespace anm2ed::test; -Anm2 fixture_load_with_uids(const char* name) -{ - auto anm2 = anm2_load(file_load(CORPUS_DIR / name)); - anm2.uids_repair(); - return anm2; -} +model::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(Anm2& anm2, Selection& selection, auto&& edit) +void selection_edit(model::Model& anm2, Selection& selection, auto&& edit) { - auto before = selection_focus_get(selection, UidIndex(anm2)); + auto before = selection_focus_get(selection, model::UidIndex(anm2)); edit(); anm2.uids_repair(); - selection_follow(selection, anm2, UidIndex(anm2), before); + selection_follow(selection, anm2, model::UidIndex(anm2), before); } TEST_CASE("uids are unique and non-zero after load") { for (const auto& fixture : fixtures_get()) { - auto anm2 = anm2_load(file_load(fixture)); + auto anm2 = model_load(file_load(fixture)); std::set uids{}; bool isUnique{true}; - element_each(anm2.root, - [&](const Element& element) { isUnique &= element.uid != 0 && uids.insert(element.uid).second; }); + for (auto [index, animation] : anm2.animations_get()) + model::animation_tracks_each(*animation, + [&](const model::Track& track) + { + isUnique &= uids.insert(track.uid).second; + for (const auto& frame : track.frames) + isUnique &= uids.insert(frame.uid).second; + }); INFO("fixture: ", fixture.filename().string()); CHECK(isUnique); } @@ -46,7 +47,7 @@ TEST_CASE("selected frames and focus follow inserts and moves") selection_edit(anm2, selection, [&] { edit::frame_insert(anm2, {0, LAYER, 0, -1}, 0); }); selection_edit(anm2, selection, [&] { edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); }); - UidIndex index(anm2); + model::UidIndex index(anm2); CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0}); CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) == std::set{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}); @@ -60,33 +61,32 @@ TEST_CASE("a removed focus falls back to its nearest survivor") selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); selection_edit(anm2, selection, [&] { edit::frames_delete(anm2, {{0, LAYER, 0, 1}}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); + CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); CHECK(selection.uids[SelectionKind::FRAMES].empty()); selection_edit(anm2, selection, [&] { edit::items_remove(anm2, 0, {{LAYER, {0}}}, {}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); + CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, ROOT}); selection_focus_set(selection, anm2, {1, ROOT, -1, 0}); selection_edit(anm2, selection, [&] { edit::animations_remove(anm2, {1}, {}); }); - CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); + CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, ROOT}); } TEST_CASE("track and group selection follow regrouping") { auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2"); - auto group = - child_first_get(*child_first_get(*anm2.element_get(ElementType::ANIMATION, 0), ElementType::LAYER_ANIMATIONS), - ElementType::GROUP); + const model::TrackGroup* group{}; + model::groups_each(anm2.animation_get(0)->layers, [&](const model::TrackGroup& candidate) { group = &candidate; }); REQUIRE(group); + auto groupId = group->id; Selection selection{}; - selection_references_set(selection, anm2, SelectionKind::TRACKS, {{0, LAYER, 0, -1, LAYER, group->id}}); - selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, group->id}}); + 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, [&] { edit::items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); }); - UidIndex index(anm2); + model::UidIndex index(anm2); CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set{{0, LAYER, 0}}); - CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == - std::set{{0, LAYER, group->id}}); + CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == std::set{{0, LAYER, groupId}}); } diff --git a/tests/undo.cpp b/tests/undo.cpp index e22ab4b..b51bffb 100644 --- a/tests/undo.cpp +++ b/tests/undo.cpp @@ -12,22 +12,29 @@ constexpr int WALK_STEPS = 150; constexpr int WALK_SEED = 1234; constexpr int UNDO_LIMIT = 1000; -std::vector references_all_get(const Anm2& anm2, bool isFrames) +std::vector references_all_get(const model::Model& anm2, bool isFrames) { - UidIndex index(anm2); + model::UidIndex index(anm2); std::vector result{}; - element_each(anm2.root, - [&](const Element& element) - { - auto reference = index.reference_get(element.uid); - if (!reference || reference->itemType == NONE || reference->itemType == TRIGGER) return; - if (isFrames == (reference->frameIndex >= 0)) result.push_back(*reference); - }); + 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()) + model::animation_tracks_each(*animation, + [&](const model::Track& track) + { + add(track.uid); + for (const auto& frame : track.frames) + add(frame.uid); + }); return result; } // One random edit on randomly chosen live elements; returns false when nothing applicable exists. -bool edit_random_apply(Anm2& anm2, std::mt19937& random) +bool edit_random_apply(model::Model& anm2, std::mt19937& random) { auto frames = references_all_get(anm2, true); auto tracks = references_all_get(anm2, false); @@ -64,7 +71,7 @@ bool edit_random_apply(Anm2& anm2, std::mt19937& random) edit::animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); break; default: - edit::animations_move(anm2, {frame.animationIndex}, {}, 0, -1); + edit::animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0}); break; } return true; @@ -78,30 +85,31 @@ TEST_CASE("undo and redo restore every state of a random edit walk") { INFO("fixture: ", name); Snapshots snapshots{}; - snapshots.current.anm2 = anm2_load(file_load(CORPUS_DIR / name)); + snapshots.current.model = model_load(file_load(CORPUS_DIR / name)); std::mt19937 random(WALK_SEED); - std::vector hashes{snapshots.current.anm2.hash()}; + std::vector hashes{model::model_hash(snapshots.current.model)}; for (int step = 0; step < WALK_STEPS; ++step) { snapshots.push("Edit"); - if (!edit_random_apply(snapshots.current.anm2, random)) break; + if (!edit_random_apply(snapshots.current.model, random)) break; + auto count = snapshots.undoStack.size(); snapshots.commit(); - if (snapshots.current.anm2.hash() != hashes.back()) hashes.push_back(snapshots.current.anm2.hash()); + if (snapshots.undoStack.size() != count) hashes.push_back(model::model_hash(snapshots.current.model)); } REQUIRE(hashes.size() > 1); for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it) { REQUIRE(snapshots.undo()); - CHECK(snapshots.current.anm2.hash() == *it); + CHECK(model::model_hash(snapshots.current.model) == *it); } CHECK_FALSE(snapshots.undo()); for (auto it = hashes.begin() + 1; it != hashes.end(); ++it) { REQUIRE(snapshots.redo()); - CHECK(snapshots.current.anm2.hash() == *it); + CHECK(model::model_hash(snapshots.current.model) == *it); } } } @@ -110,21 +118,20 @@ TEST_CASE("selection follows its frame through an edit and its undo") { Snapshots snapshots{}; auto& current = snapshots.current; - current.anm2 = anm2_load(file_load(CORPUS_DIR / "02_items.anm2")); - current.anm2.uids_repair(); - selection_focus_set(current.selection, current.anm2, {0, LAYER, 0, 1}); - selection_references_set(current.selection, current.anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); + 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"); - edit::frame_insert(current.anm2, {0, LAYER, 0, -1}, 0); - auto& track = *current.anm2.element_get(Reference{0, LAYER, 0}); - std::rotate(track.children.begin(), track.children.end() - 1, track.children.end()); + edit::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.anm2); + model::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{{0, LAYER, 0, 2}}); REQUIRE(snapshots.undo()); - CHECK(selection_focus_get(current.selection, UidIndex(current.anm2)) == Reference{0, LAYER, 0, 1}); + CHECK(selection_focus_get(current.selection, model::UidIndex(current.model)) == Reference{0, LAYER, 0, 1}); }