From 41ed3479258f819d517d09d3f04670de7af45ae2 Mon Sep 17 00:00:00 2001 From: shweet Date: Sat, 3 Oct 2026 12:41:23 -0400 Subject: [PATCH] Split anm2 and timeline into modules; merge groups by name Baseline before de-bloat refactor. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 2 + src/anm2/animation.cpp | 185 + src/anm2/anm2.cpp | 3185 +------------ src/anm2/element.cpp | 683 +++ src/anm2/frames.cpp | 478 ++ src/anm2/groups.cpp | 440 ++ src/anm2/hash.cpp | 333 ++ src/anm2/internal.hpp | 106 + src/anm2/merge.cpp | 213 + src/anm2/normalize.cpp | 260 ++ src/anm2/xml.cpp | 618 +++ src/imgui/dockspace.hpp | 2 +- src/imgui/window/timeline.cpp | 4231 ------------------ src/imgui/window/timeline/commands.cpp | 2086 +++++++++ src/imgui/window/timeline/context.hpp | 355 ++ src/imgui/window/timeline/frames.cpp | 1135 +++++ src/imgui/window/timeline/popups.cpp | 248 + src/imgui/window/timeline/timeline.cpp | 67 + src/imgui/window/{ => timeline}/timeline.hpp | 8 + src/imgui/window/timeline/tracks.cpp | 629 +++ 20 files changed, 7849 insertions(+), 7415 deletions(-) create mode 100644 src/anm2/animation.cpp create mode 100644 src/anm2/element.cpp create mode 100644 src/anm2/frames.cpp create mode 100644 src/anm2/groups.cpp create mode 100644 src/anm2/hash.cpp create mode 100644 src/anm2/internal.hpp create mode 100644 src/anm2/merge.cpp create mode 100644 src/anm2/normalize.cpp create mode 100644 src/anm2/xml.cpp delete mode 100644 src/imgui/window/timeline.cpp create mode 100644 src/imgui/window/timeline/commands.cpp create mode 100644 src/imgui/window/timeline/context.hpp create mode 100644 src/imgui/window/timeline/frames.cpp create mode 100644 src/imgui/window/timeline/popups.cpp create mode 100644 src/imgui/window/timeline/timeline.cpp rename src/imgui/window/{ => timeline}/timeline.hpp (95%) create mode 100644 src/imgui/window/timeline/tracks.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 95ab13d..14c7d18 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -94,6 +94,8 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS src/imgui/*.hpp src/imgui/window/*.cpp src/imgui/window/*.hpp + src/imgui/window/timeline/*.cpp + src/imgui/window/timeline/*.hpp src/imgui/popup/*.cpp src/imgui/popup/*.hpp src/imgui/wizard/*.cpp diff --git a/src/anm2/animation.cpp b/src/anm2/animation.cpp new file mode 100644 index 0000000..7f43bc7 --- /dev/null +++ b/src/anm2/animation.cpp @@ -0,0 +1,185 @@ +#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 = element_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 *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); + } + + 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 *= math::quad_model_parent_get( + groupRootFrame.position, {}, math::percent_to_unit(groupRootFrame.scale), + groupRootFrame.rotation, math::percent_to_unit(groupRootFrame.shear)); + } + + 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}; + } + + Element* animation_container_get(Element& animation, ElementType type) + { + if (auto container = child_first_get(animation, type)) return container; + animation.children.push_back(element_make(type)); + return &animation.children.back(); + } + + int Anm2::layer_animation_add(int animationIndex, int id, int insertBeforeId, std::string name, int spritesheetId, + types::destination::Type destination) + { + auto layers = element_get(ElementType::LAYERS); + if (!layers) return -1; + + id = id == -1 ? element_child_next_id_get(*layers, ElementType::LAYER_ELEMENT) : id; + auto layer = element_child_id_get(*layers, ElementType::LAYER_ELEMENT, id); + if (!layer) + { + layers->children.push_back(element_make(ElementType::LAYER_ELEMENT)); + layer = &layers->children.back(); + layer->id = id; + } + + if (!name.empty()) layer->name = name; + layer->spritesheetId = element_get(ElementType::SPRITESHEET, spritesheetId) ? spritesheetId : 0; + + auto add = [&](Element& animation) + { + if (animation_item_get(animation, ItemType::LAYER, id)) return; + auto layerAnimations = animation_container_get(animation, ElementType::LAYER_ANIMATIONS); + auto item = element_make(ElementType::LAYER_ANIMATION); + item.layerId = id; + + if (insertBeforeId != -1) + for (auto it = layerAnimations->children.begin(); it != layerAnimations->children.end(); ++it) + if (it->type == ElementType::LAYER_ANIMATION && it->layerId == insertBeforeId) + { + layerAnimations->children.insert(it, item); + return; + } + + layerAnimations->children.push_back(item); + }; + + 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; + } + + int Anm2::null_animation_add(int animationIndex, int id, std::string name, bool isShowRect, + types::destination::Type destination) + { + auto nulls = element_get(ElementType::NULLS); + if (!nulls) return -1; + + id = id == -1 ? element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT) : id; + auto null = element_child_id_get(*nulls, ElementType::NULL_ELEMENT, id); + if (!null) + { + nulls->children.push_back(element_make(ElementType::NULL_ELEMENT)); + null = &nulls->children.back(); + null->id = id; + } + + if (!name.empty()) null->name = name; + null->isShowRect = isShowRect; + + auto add = [&](Element& animation) + { + if (animation_item_get(animation, ItemType::NULL_, id)) return; + auto nullAnimations = animation_container_get(animation, ElementType::NULL_ANIMATIONS); + auto item = element_make(ElementType::NULL_ANIMATION); + item.nullId = id; + nullAnimations->children.push_back(item); + }; + + 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 cbd96c4..0e47bc3 100644 --- a/src/anm2/anm2.cpp +++ b/src/anm2/anm2.cpp @@ -1,124 +1,10 @@ -#include "anm2.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "file.hpp" -#include "math.hpp" -#include "path.hpp" -#include "time.hpp" -#include "working_directory.hpp" -#include "xml.hpp" +#include "internal.hpp" using namespace anm2ed::util; using namespace tinyxml2; namespace anm2ed { -#define ANM2_STRING_ATTRIBUTES \ - X("Name", name) \ - X("CreatedBy", createdBy) \ - X("CreatedOn", createdOn) \ - X("Binding", binding) \ - X("Value", value) \ - X("DefaultAnimation", defaultAnimation) - -#define ANM2_PATH_ATTRIBUTES \ - X("Path", path) \ - X("Vertex", vertex) \ - X("Fragment", fragment) - -#define ANM2_INT_ATTRIBUTES \ - X("Id", id) \ - X("LayerId", layerId) \ - X("NullId", nullId) \ - X("SpritesheetId", spritesheetId) \ - X("Fps", fps) \ - X("Version", version) \ - X("FrameNum", frameNum) \ - X("Delay", duration) \ - X("AtFrame", atFrame) \ - X("EventId", eventId) \ - X("RegionId", regionId) \ - X("ShaderId", shaderId) \ - X("SoundId", soundId) \ - X("GroupId", groupId) \ - X("Index", index) - -#define ANM2_BOOL_ATTRIBUTES \ - X("Loop", isLoop) \ - X("Visible", isVisible) \ - X("ShowRect", isShowRect) \ - X("IsExpanded", isExpanded) \ - X("Enabled", isEnabled) - -#define ANM2_FLOAT_ATTRIBUTES \ - X("Rotation", rotation) \ - X("XPivot", pivot.x) \ - X("YPivot", pivot.y) \ - X("XCrop", crop.x) \ - X("YCrop", crop.y) \ - X("XPosition", position.x) \ - X("YPosition", position.y) \ - X("Width", size.x) \ - X("Height", size.y) \ - X("XScale", scale.x) \ - X("YScale", scale.y) \ - X("ShearX", shear.x) \ - X("ShearY", shear.y) - -#define ANM2_COLOR_ATTRIBUTES \ - X("RedTint", tint.r) \ - X("GreenTint", tint.g) \ - X("BlueTint", tint.b) \ - X("AlphaTint", tint.a) \ - X("RedOffset", colorOffset.r) \ - X("GreenOffset", colorOffset.g) \ - X("BlueOffset", colorOffset.b) - - constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; - - constexpr std::array ELEMENT_TAGS = { -#define X(symbol, tag) std::string_view{tag}, - ANM2_ELEMENT_TYPES -#undef X - }; - - constexpr std::array INTERPOLATION_VALUES = { - "", "", "EaseIn", "EaseOut", "EaseInOut"}; - - constexpr std::array ORIGIN_VALUES = {"", "TopLeft", "Center"}; - constexpr std::string_view ANM2ED_GROUP_FRAME_BACKUP_TAG = "FrameRestore"; - constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; - constexpr std::string_view LEGACY_OVERLAY_TAG = "Overlay"; - - void group_metadata_embed(Element&); - void group_metadata_extract(Element&, Flags); - void groups_flatten(Element&); - void groups_nest(Element&); - void group_frames_restore(Element&); - void source_document_erase(Element&); - void shader_ids_repair(Element&); - void shader_frame_ids_repair(Element&); - void shader_ids_remap(Element&); - void region_ids_remap(Element&); - void region_frame_ids_repair(Element&); - Element* child_first_get(Element&, ElementType); - const Element* child_first_get(const Element&, ElementType); - bool is_track(const Element&); - bool is_track_child_valid(ElementType, ElementType); - float interpolation_factor(Interpolation, float); - int animations_count_get(const Element& animations) { int count{}; @@ -198,2254 +84,6 @@ namespace anm2ed return true; } - ElementType element_type_get(std::string_view tag) - { - for (std::size_t i = 0; i < ELEMENT_TAGS.size(); ++i) - if (ELEMENT_TAGS[i] == tag) return (ElementType)i; - return ElementType::UNKNOWN; - } - - std::string_view element_tag_get(ElementType type) - { - auto index = (std::size_t)type; - if (index >= ELEMENT_TAGS.size()) return {}; - return ELEMENT_TAGS[index]; - } - - ElementType element_container_type_get(ElementType type) - { - switch (type) - { - case ElementType::SPRITESHEET: - return ElementType::SPRITESHEETS; - case ElementType::SHADER: - return ElementType::SHADERS; - case ElementType::LAYER_ELEMENT: - return ElementType::LAYERS; - case ElementType::NULL_ELEMENT: - return ElementType::NULLS; - case ElementType::EVENT_ELEMENT: - return ElementType::EVENTS; - case ElementType::SOUND_ELEMENT: - return ElementType::SOUNDS; - case ElementType::ANIMATION: - return ElementType::ANIMATIONS; - default: - return ElementType::UNKNOWN; - } - } - - Element element_make(ElementType type) - { - Element element{}; - element.type = type; - element.tag = std::string(element_tag_get(type)); - return element; - } - - Element root_animation_make() - { - auto root = element_make(ElementType::ROOT_ANIMATION); - root.children.push_back(element_make(ElementType::FRAME)); - return root; - } - - bool is_frame_transform_default(const Element& frame) - { - auto base = element_make(ElementType::FRAME); - return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation && - frame.shear == base.shear && frame.tint == base.tint && frame.colorOffset == base.colorOffset; - } - - bool is_root_animation_transform_default(const Element& root) - { - for (const auto& frame : root.children) - if (frame.type == ElementType::FRAME && !is_frame_transform_default(frame)) return false; - return true; - } - - bool is_group_frame_backup(const Element& element) - { - return element.type == ElementType::UNKNOWN && element.tag == ANM2ED_GROUP_FRAME_BACKUP_TAG; - } - - void group_frame_backups_erase(Element& group) - { - std::erase_if(group.children, [](const Element& child) { return is_group_frame_backup(child); }); - } - - Element group_frame_backup_make(const Element& container, const Element& group, ElementType trackType) - { - Element backup{}; - backup.type = ElementType::UNKNOWN; - backup.tag = std::string(ANM2ED_GROUP_FRAME_BACKUP_TAG); - - if (auto root = child_first_get(group, ElementType::ROOT_ANIMATION)) backup.children.push_back(*root); - - for (const auto& item : container.children) - if (item.type == trackType && item.groupId == group.id) backup.children.push_back(item); - - return backup; - } - - void frame_group_root_apply(Element& frame, const Element& rootFrame) - { - auto rootScale = math::percent_to_unit(rootFrame.scale); - auto offset = frame.position * rootScale; - auto radians = glm::radians(rootFrame.rotation); - auto cos = std::cos(radians); - auto sin = std::sin(radians); - - frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); - frame.scale *= rootScale; - frame.rotation += rootFrame.rotation; - frame.tint *= rootFrame.tint; - frame.colorOffset += rootFrame.colorOffset; - } - - void track_group_root_bake(Element& track, const Element& root, int frameNum) - { - auto trackLength = track_length_get(track); - if (trackLength <= 0) return; - - auto length = std::max({trackLength, track_length_get(root), frameNum, FRAME_DURATION_MIN}); - std::vector frames{}; - frames.reserve(length); - - for (int time = 0; time < length; ++time) - { - auto frame = frame_generate(track, (float)time); - auto rootFrame = frame_generate(root, (float)time); - frame_group_root_apply(frame, rootFrame); - frame.duration = FRAME_DURATION_MIN; - frame.interpolation = Interpolation::NONE; - frames.push_back(std::move(frame)); - } - - track.children = std::move(frames); - } - - void group_frames_bake(Element& container, ElementType trackType, int frameNum) - { - for (auto& group : container.children) - { - if (group.type != ElementType::GROUP) continue; - group_frame_backups_erase(group); - auto root = child_first_get(group, ElementType::ROOT_ANIMATION); - if (!root || is_root_animation_transform_default(*root)) continue; - - auto backup = group_frame_backup_make(container, group, trackType); - for (auto& item : container.children) - if (item.type == trackType && item.groupId == group.id) track_group_root_bake(item, *root, frameNum); - - *root = root_animation_make(); - group.children.push_back(std::move(backup)); - } - } - - void group_frames_bake(Element& element) - { - if (element.type == ElementType::ANIMATION) - { - if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS)) - group_frames_bake(*layerAnimations, ElementType::LAYER_ANIMATION, element.frameNum); - if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS)) - group_frames_bake(*nullAnimations, ElementType::NULL_ANIMATION, element.frameNum); - } - - for (auto& child : element.children) - group_frames_bake(child); - } - - void group_frames_restore(Element& container, ElementType trackType) - { - std::set restoredGroupIds{}; - - for (auto& group : container.children) - { - if (group.type != ElementType::GROUP) continue; - if (group.id < 0) continue; - - const Element* backup{}; - for (const auto& child : group.children) - if (is_group_frame_backup(child)) - { - backup = &child; - break; - } - - if (!backup) continue; - - auto root = root_animation_make(); - if (auto currentRoot = child_first_get(group, ElementType::ROOT_ANIMATION)) root = *currentRoot; - - std::vector restoredTracks{}; - bool isRootRestored{}; - for (const auto& child : backup->children) - { - if (child.type == ElementType::ROOT_ANIMATION && !isRootRestored) - { - root = child; - isRootRestored = true; - } - else if (child.type == trackType) - { - auto track = child; - track.groupId = group.id; - restoredTracks.push_back(std::move(track)); - } - } - - if (!isRootRestored && restoredTracks.empty()) continue; - - group.children = {std::move(root)}; - group.children.insert(group.children.end(), std::make_move_iterator(restoredTracks.begin()), - std::make_move_iterator(restoredTracks.end())); - restoredGroupIds.insert(group.id); - } - - if (restoredGroupIds.empty()) return; - - std::erase_if(container.children, [&](const Element& item) - { return item.type == trackType && restoredGroupIds.contains(item.groupId); }); - } - - void group_frames_restore(Element& element) - { - if (element.type == ElementType::ANIMATION) - { - if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS)) - group_frames_restore(*layerAnimations, ElementType::LAYER_ANIMATION); - if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS)) - group_frames_restore(*nullAnimations, ElementType::NULL_ANIMATION); - } - - for (auto& child : element.children) - group_frames_restore(child); - } - - bool string_query(const XMLElement* element, const char* name, std::string& out) - { - if (!element) return false; - if (auto value = element->Attribute(name); value) - { - out = value; - return true; - } - return false; - } - - bool path_query(const XMLElement* element, const char* name, std::filesystem::path& out) - { - std::string value{}; - if (!string_query(element, name, value)) return false; - out = path::from_utf8(value); - return true; - } - - void path_set(XMLElement* element, const char* name, const std::filesystem::path& value) - { - if (!element || value.empty()) return; - auto valueUtf8 = path::to_utf8(value); - element->SetAttribute(name, valueUtf8.c_str()); - } - - float color_read(const XMLElement* element, const char* name, float fallback) - { - int value{}; - if (!element || element->QueryIntAttribute(name, &value) != XML_SUCCESS) return fallback; - return math::uint8_to_float(value); - } - - int color_write(float value) { return math::float_to_uint8(value); } - - Interpolation interpolation_read(const XMLElement* element, const char* attribute) - { - bool isFallback{}; - if (element) element->QueryBoolAttribute(attribute, &isFallback); - - auto value = element ? element->Attribute(attribute) : nullptr; - if (!value) return Interpolation::NONE; - - for (std::size_t i = 0; i < INTERPOLATION_VALUES.size(); ++i) - if (!INTERPOLATION_VALUES[i].empty() && INTERPOLATION_VALUES[i] == value) return (Interpolation)i; - - return isFallback ? Interpolation::LINEAR : Interpolation::NONE; - } - - Interpolation interpolation_read(const XMLElement* element) { return interpolation_read(element, "Interpolated"); } - - void interpolation_write(XMLElement* element, Interpolation interpolation) - { - if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) - { - element->SetAttribute("Interpolated", interpolation == Interpolation::LINEAR); - return; - } - - auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; - if (!value.empty()) element->SetAttribute("Interpolated", value.data()); - } - - Origin origin_read(const XMLElement* element) - { - auto value = element ? element->Attribute("Origin") : nullptr; - if (!value) return Origin::CUSTOM; - - for (std::size_t i = 0; i < ORIGIN_VALUES.size(); ++i) - if (!ORIGIN_VALUES[i].empty() && ORIGIN_VALUES[i] == value) return (Origin)i; - - return Origin::CUSTOM; - } - - void origin_write(XMLElement* out, const Element& element) - { - auto origin = ORIGIN_VALUES[(std::size_t)element.origin]; - if (!origin.empty()) - { - out->SetAttribute("Origin", origin.data()); - return; - } - - out->SetAttribute("XPivot", element.pivot.x); - out->SetAttribute("YPivot", element.pivot.y); - } - - void element_attributes_read(Element& out, const XMLElement* element) - { -#define X(attribute, member) string_query(element, attribute, out.member); - ANM2_STRING_ATTRIBUTES -#undef X -#define X(attribute, member) path_query(element, attribute, out.member); - ANM2_PATH_ATTRIBUTES -#undef X -#define X(attribute, member) element->QueryIntAttribute(attribute, &out.member); - ANM2_INT_ATTRIBUTES -#undef X -#define X(attribute, member) element->QueryBoolAttribute(attribute, &out.member); - ANM2_BOOL_ATTRIBUTES -#undef X -#define X(attribute, member) element->QueryFloatAttribute(attribute, &out.member); - ANM2_FLOAT_ATTRIBUTES -#undef X -#define X(attribute, member) out.member = color_read(element, attribute, out.member); - ANM2_COLOR_ATTRIBUTES -#undef X - - out.interpolation = interpolation_read(element); - out.origin = origin_read(element); - if (out.type == ElementType::REGION && out.origin == Origin::TOP_LEFT) out.pivot = {}; - if (out.type == ElementType::REGION && out.origin == Origin::CENTER) out.pivot = out.size * 0.5f; - } - - bool bake_attributes_read(const XMLElement* element, Interpolation& interpolation, int& bakeDelay) - { - if (!element || !element->Attribute("BakeInterpolation")) return false; - - interpolation = interpolation_read(element, "BakeInterpolation"); - element->QueryIntAttribute("BakeDelay", &bakeDelay); - return bakeDelay >= FRAME_DURATION_MIN; - } - - const XMLElement* bake_frames_skip(const XMLElement* element, int bakeDelay) - { - for (int i = 0; element && i < bakeDelay; ++i) - element = element->NextSiblingElement(); - return element; - } - - void element_children_read(Element& out, const XMLElement* element) - { - auto child = element->FirstChildElement(); - while (child) - { - auto childName = std::string_view(child->Name() ? child->Name() : ""); - if (childName == LEGACY_OVERLAY_TAG) - { - child = child->NextSiblingElement(); - continue; - } - - auto childType = element_type_get(childName); - if (childType == ElementType::FRAME && is_track(out)) - { - Interpolation bakeInterpolation{}; - int bakeDelay{}; - if (bake_attributes_read(child, bakeInterpolation, bakeDelay)) - { - auto restored = element_read(child); - restored.interpolation = bakeInterpolation; - restored.duration = bakeDelay; - if (is_track_child_valid(out.type, restored.type)) out.children.push_back(std::move(restored)); - child = bake_frames_skip(child, bakeDelay); - continue; - } - } - - auto childElement = element_read(child); - if (is_track_child_valid(out.type, childElement.type)) out.children.push_back(std::move(childElement)); - child = child->NextSiblingElement(); - } - } - - Element element_read(const XMLElement* element) - { - Element out{}; - if (!element) return out; - - out.tag = element->Name() ? element->Name() : ""; - out.type = element_type_get(out.tag); - element_attributes_read(out, element); - - element_children_read(out, element); - - if (out.type == ElementType::TRIGGER && out.soundId != -1) - { - bool isSoundFound{}; - for (const auto& child : out.children) - if (child.type == ElementType::SOUND_ELEMENT && child.id == out.soundId) isSoundFound = true; - - if (!isSoundFound) - { - auto sound = element_make(ElementType::SOUND_ELEMENT); - sound.id = out.soundId; - out.children.insert(out.children.begin(), sound); - } - } - - if (out.type == ElementType::TRIGGER) - for (const auto& child : out.children) - if (child.type == ElementType::SOUND_ELEMENT && child.id != -1) out.soundIds.push_back(child.id); - - return out; - } - - bool is_nested_group_parent(ElementType parentType, Flags flags) - { - return has_flag(flags, SERIALIZE_NESTED_GROUPS) && - (parentType == ElementType::ANIMATIONS || parentType == ElementType::LAYER_ANIMATIONS || - parentType == ElementType::NULL_ANIMATIONS); - } - - bool is_group_id_serialized(Flags flags) - { - return has_flag(flags, SERIALIZE_GROUPS) && !has_flag(flags, SERIALIZE_NESTED_GROUPS); - } - - bool element_write_skip(const Element& element, ElementType parentType, Flags flags) - { - if (!is_track_child_valid(parentType, element.type)) return true; - if ((element.type == ElementType::SHADERS || element.type == ElementType::SHADER || - element.type == ElementType::UNIFORM || element.type == ElementType::COMPONENT) && - !has_flag(flags, SERIALIZE_EXTENSIONS)) - return true; - if (element.type == ElementType::SHADERS && element.children.empty()) return true; - if (element.type == ElementType::SOUNDS && (!has_flag(flags, SERIALIZE_SOUNDS) || element.children.empty())) - return true; - if ((element.type == ElementType::LAYER_ANIMATION_GROUPS || element.type == ElementType::NULL_ANIMATION_GROUPS) && - (!has_flag(flags, SERIALIZE_GROUPS) || element.children.empty())) - return true; - if (element.type == ElementType::SOUND_ELEMENT && parentType == ElementType::TRIGGER) return true; - if (element.type == ElementType::REGION && !has_flag(flags, SERIALIZE_REGIONS)) return true; - if (element.type == ElementType::GROUP && !has_flag(flags, SERIALIZE_GROUPS)) return true; - return false; - } - - void frame_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags) - { - if (parentType == ElementType::LAYER_ANIMATION) - { - bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1; - bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion; - - if (isHasValidRegion) out->SetAttribute("RegionId", element.regionId); - if (isWriteRegionValues) - { - out->SetAttribute("XPivot", element.pivot.x); - out->SetAttribute("YPivot", element.pivot.y); - out->SetAttribute("XCrop", element.crop.x); - out->SetAttribute("YCrop", element.crop.y); - out->SetAttribute("Width", element.size.x); - out->SetAttribute("Height", element.size.y); - } - } - - out->SetAttribute("XPosition", element.position.x); - out->SetAttribute("YPosition", element.position.y); - out->SetAttribute("Delay", element.duration); - out->SetAttribute("Visible", element.isVisible); - out->SetAttribute("XScale", element.scale.x); - out->SetAttribute("YScale", element.scale.y); - if (has_flag(flags, SERIALIZE_EXTENSIONS)) - { - out->SetAttribute("ShearX", element.shear.x); - out->SetAttribute("ShearY", element.shear.y); - } - out->SetAttribute("RedTint", color_write(element.tint.r)); - out->SetAttribute("GreenTint", color_write(element.tint.g)); - out->SetAttribute("BlueTint", color_write(element.tint.b)); - out->SetAttribute("AlphaTint", color_write(element.tint.a)); - out->SetAttribute("RedOffset", color_write(element.colorOffset.r)); - out->SetAttribute("GreenOffset", color_write(element.colorOffset.g)); - out->SetAttribute("BlueOffset", color_write(element.colorOffset.b)); - out->SetAttribute("Rotation", element.rotation); - interpolation_write(out, element.interpolation); - if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) - out->SetAttribute("ShaderId", element.shaderId); - } - - void element_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags) - { - if (element.type == ElementType::INFO) - { - out->SetAttribute("CreatedBy", element.createdBy.c_str()); - out->SetAttribute("CreatedOn", element.createdOn.c_str()); - out->SetAttribute("Fps", element.fps); - out->SetAttribute("Version", element.version); - } - else if (element.type == ElementType::ANIMATIONS) - out->SetAttribute("DefaultAnimation", element.defaultAnimation.c_str()); - else if (element.type == ElementType::SPRITESHEET) - { - out->SetAttribute("Id", element.id); - path_set(out, "Path", element.path); - } - else if (element.type == ElementType::SHADER) - { - out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - path_set(out, "Vertex", element.vertex); - path_set(out, "Fragment", element.fragment); - } - else if (element.type == ElementType::UNIFORM) - { - out->SetAttribute("Name", element.name.c_str()); - if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str()); - if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str()); - } - else if (element.type == ElementType::COMPONENT) - { - out->SetAttribute("Index", element.index); - if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str()); - if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str()); - } - else if (element.type == ElementType::REGION) - { - out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - out->SetAttribute("XCrop", element.crop.x); - out->SetAttribute("YCrop", element.crop.y); - out->SetAttribute("Width", element.size.x); - out->SetAttribute("Height", element.size.y); - origin_write(out, element); - } - else if (element.type == ElementType::LAYER_ELEMENT) - { - out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - out->SetAttribute("SpritesheetId", element.spritesheetId); - } - else if (element.type == ElementType::NULL_ELEMENT) - { - out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - if (element.isShowRect) out->SetAttribute("ShowRect", element.isShowRect); - } - else if (element.type == ElementType::GROUP) - { - if (!is_nested_group_parent(parentType, flags)) out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - out->SetAttribute("IsExpanded", element.isExpanded); - out->SetAttribute("Visible", element.isVisible); - if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) && - element.index != -1) - out->SetAttribute("Index", element.index); - } - else if (element.type == ElementType::EVENT_ELEMENT) - { - out->SetAttribute("Id", element.id); - out->SetAttribute("Name", element.name.c_str()); - } - else if (element.type == ElementType::SOUND_ELEMENT) - { - out->SetAttribute("Id", element.id); - if (parentType != ElementType::TRIGGER) path_set(out, "Path", element.path); - } - else if (element.type == ElementType::ANIMATION) - { - out->SetAttribute("Name", element.name.c_str()); - out->SetAttribute("FrameNum", element.frameNum); - out->SetAttribute("Loop", element.isLoop); - if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); - } - else if (element.type == ElementType::LAYER_ANIMATION) - { - out->SetAttribute("LayerId", element.layerId); - out->SetAttribute("Visible", element.isVisible); - if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); - } - else if (element.type == ElementType::NULL_ANIMATION) - { - out->SetAttribute("NullId", element.nullId); - out->SetAttribute("Visible", element.isVisible); - if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); - } - else if (element.type == ElementType::FRAME) - frame_attributes_write(out, element, parentType, flags); - else if (element.type == ElementType::TRIGGER) - { - if (element.eventId != -1) out->SetAttribute("EventId", element.eventId); - out->SetAttribute("AtFrame", element.atFrame); - } - } - - void bake_attributes_write(XMLElement* out, Interpolation interpolation, int bakeDelay) - { - auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; - if (!value.empty()) out->SetAttribute("BakeInterpolation", value.data()); - out->SetAttribute("BakeDelay", bakeDelay); - } - - bool is_frame_bake_serialized(const Element& frame, Flags flags) - { - return has_flag(flags, SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES) && frame.type == ElementType::FRAME && - frame.interpolation != Interpolation::NONE && frame.interpolation != Interpolation::LINEAR; - } - - XMLElement* element_to_xml(XMLDocument& document, const Element& element, ElementType parentType, Flags flags); - - void baked_frames_insert(XMLDocument& document, XMLElement* out, const Element& track, int index, Flags flags) - { - const auto& original = track.children[index]; - auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME - ? track.children[index + 1] - : original; - auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN); - - for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex) - { - auto baked = original; - auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay); - baked.duration = FRAME_DURATION_MIN; - baked.interpolation = Interpolation::NONE; - baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); - baked.position = glm::mix(original.position, nextFrame.position, amount); - baked.scale = glm::mix(original.scale, nextFrame.scale, amount); - baked.shear = glm::mix(original.shear, nextFrame.shear, amount); - baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); - baked.tint = glm::mix(original.tint, nextFrame.tint, amount); - auto frame = element_to_xml(document, baked, track.type, flags); - if (bakeIndex == 0) bake_attributes_write(frame, original.interpolation, bakeDelay); - out->InsertEndChild(frame); - } - } - - void trigger_sounds_xml_insert(XMLDocument& document, XMLElement* out, const Element& element, Flags flags) - { - if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return; - - for (auto soundId : element.soundIds) - { - if (soundId == -1) continue; - auto sound = document.NewElement(element_tag_get(ElementType::SOUND_ELEMENT).data()); - sound->SetAttribute("Id", soundId); - out->InsertEndChild(sound); - } - } - - XMLElement* element_to_xml(XMLDocument& document, const Element& element, ElementType parentType, Flags flags) - { - auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type); - auto out = document.NewElement(tag.empty() ? element.tag.c_str() : tag.data()); - element_attributes_write(out, element, parentType, flags); - trigger_sounds_xml_insert(document, out, element, flags); - - for (int i = 0; i < (int)element.children.size(); ++i) - { - const auto& child = element.children[i]; - if (element_write_skip(child, element.type, flags)) continue; - - if (is_track(element) && is_frame_bake_serialized(child, flags)) - baked_frames_insert(document, out, element, i, flags); - else - out->InsertEndChild(element_to_xml(document, child, element.type, flags)); - } - - return out; - } - - 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{}; - document.InsertEndChild(element_to_xml(document, element, parentType, flags)); - return xml::document_to_string(document); - } - - std::string element_to_string(const Element& element, Flags flags) - { - return element_to_string(element, ElementType::UNKNOWN, flags); - } - - constexpr std::uint64_t ANM2_HASH_OFFSET = 14695981039346656037ull; - constexpr std::uint64_t ANM2_HASH_PRIME = 1099511628211ull; - - struct BakeAttributes - { - Interpolation interpolation{Interpolation::NONE}; - int delay{FRAME_DURATION_MIN}; - }; - - void hash_byte_append(std::uint64_t& hash, unsigned char value) - { - hash ^= value; - hash *= ANM2_HASH_PRIME; - } - - void hash_bytes_append(std::uint64_t& hash, const char* data, std::size_t size) - { - for (std::size_t i = 0; i < size; ++i) - hash_byte_append(hash, (unsigned char)data[i]); - } - - void hash_string_append(std::uint64_t& hash, std::string_view value) - { - auto size = (std::uint64_t)value.size(); - hash_bytes_append(hash, reinterpret_cast(&size), sizeof(size)); - hash_bytes_append(hash, value.data(), value.size()); - } - - void hash_attr_append(std::uint64_t& hash, std::string_view name, std::string_view value) - { - hash_byte_append(hash, 'A'); - hash_string_append(hash, name); - hash_string_append(hash, value); - } - - void hash_attr_append(std::uint64_t& hash, std::string_view name, int value) - { - char buffer[32]{}; - XMLUtil::ToStr(value, buffer, sizeof(buffer)); - hash_attr_append(hash, name, std::string_view(buffer)); - } - - void hash_attr_append(std::uint64_t& hash, std::string_view name, bool isValue) - { - char buffer[8]{}; - XMLUtil::ToStr(isValue, buffer, sizeof(buffer)); - hash_attr_append(hash, name, std::string_view(buffer)); - } - - void hash_attr_append(std::uint64_t& hash, std::string_view name, float value) - { - char buffer[64]{}; - XMLUtil::ToStr(value, buffer, sizeof(buffer)); - hash_attr_append(hash, name, std::string_view(buffer)); - } - - void hash_path_attr_append(std::uint64_t& hash, std::string_view name, const std::filesystem::path& pathValue) - { - if (pathValue.empty()) return; - auto value = path::to_utf8(pathValue); - hash_attr_append(hash, name, value); - } - - void hash_interpolation_attr_append(std::uint64_t& hash, Interpolation interpolation) - { - if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) - { - hash_attr_append(hash, "Interpolated", interpolation == Interpolation::LINEAR); - return; - } - - auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; - if (!value.empty()) hash_attr_append(hash, "Interpolated", value); - } - - void hash_origin_attr_append(std::uint64_t& hash, const Element& element) - { - auto origin = ORIGIN_VALUES[(std::size_t)element.origin]; - if (!origin.empty()) - { - hash_attr_append(hash, "Origin", origin); - return; - } - - hash_attr_append(hash, "XPivot", element.pivot.x); - hash_attr_append(hash, "YPivot", element.pivot.y); - } - - void frame_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags) - { - if (parentType == ElementType::LAYER_ANIMATION) - { - bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1; - bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion; - - if (isHasValidRegion) hash_attr_append(hash, "RegionId", element.regionId); - if (isWriteRegionValues) - { - hash_attr_append(hash, "XPivot", element.pivot.x); - hash_attr_append(hash, "YPivot", element.pivot.y); - hash_attr_append(hash, "XCrop", element.crop.x); - hash_attr_append(hash, "YCrop", element.crop.y); - hash_attr_append(hash, "Width", element.size.x); - hash_attr_append(hash, "Height", element.size.y); - } - } - - hash_attr_append(hash, "XPosition", element.position.x); - hash_attr_append(hash, "YPosition", element.position.y); - hash_attr_append(hash, "Delay", element.duration); - hash_attr_append(hash, "Visible", element.isVisible); - hash_attr_append(hash, "XScale", element.scale.x); - hash_attr_append(hash, "YScale", element.scale.y); - if (has_flag(flags, SERIALIZE_EXTENSIONS)) - { - hash_attr_append(hash, "ShearX", element.shear.x); - hash_attr_append(hash, "ShearY", element.shear.y); - } - hash_attr_append(hash, "RedTint", color_write(element.tint.r)); - hash_attr_append(hash, "GreenTint", color_write(element.tint.g)); - hash_attr_append(hash, "BlueTint", color_write(element.tint.b)); - hash_attr_append(hash, "AlphaTint", color_write(element.tint.a)); - hash_attr_append(hash, "RedOffset", color_write(element.colorOffset.r)); - hash_attr_append(hash, "GreenOffset", color_write(element.colorOffset.g)); - hash_attr_append(hash, "BlueOffset", color_write(element.colorOffset.b)); - hash_attr_append(hash, "Rotation", element.rotation); - hash_interpolation_attr_append(hash, element.interpolation); - if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) - hash_attr_append(hash, "ShaderId", element.shaderId); - } - - void bake_attributes_hash_append(std::uint64_t& hash, Interpolation interpolation, int bakeDelay) - { - auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; - if (!value.empty()) hash_attr_append(hash, "BakeInterpolation", value); - hash_attr_append(hash, "BakeDelay", bakeDelay); - } - - void element_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags) - { - if (element.type == ElementType::INFO) - { - hash_attr_append(hash, "CreatedBy", element.createdBy); - hash_attr_append(hash, "CreatedOn", element.createdOn); - hash_attr_append(hash, "Fps", element.fps); - hash_attr_append(hash, "Version", element.version); - } - else if (element.type == ElementType::ANIMATIONS) - hash_attr_append(hash, "DefaultAnimation", element.defaultAnimation); - else if (element.type == ElementType::SPRITESHEET) - { - hash_attr_append(hash, "Id", element.id); - hash_path_attr_append(hash, "Path", element.path); - } - else if (element.type == ElementType::SHADER) - { - hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - hash_path_attr_append(hash, "Vertex", element.vertex); - hash_path_attr_append(hash, "Fragment", element.fragment); - } - else if (element.type == ElementType::UNIFORM) - { - hash_attr_append(hash, "Name", element.name); - if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding); - if (!element.value.empty()) hash_attr_append(hash, "Value", element.value); - } - else if (element.type == ElementType::COMPONENT) - { - hash_attr_append(hash, "Index", element.index); - if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding); - if (!element.value.empty()) hash_attr_append(hash, "Value", element.value); - } - else if (element.type == ElementType::REGION) - { - hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - hash_attr_append(hash, "XCrop", element.crop.x); - hash_attr_append(hash, "YCrop", element.crop.y); - hash_attr_append(hash, "Width", element.size.x); - hash_attr_append(hash, "Height", element.size.y); - hash_origin_attr_append(hash, element); - } - else if (element.type == ElementType::LAYER_ELEMENT) - { - hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - hash_attr_append(hash, "SpritesheetId", element.spritesheetId); - } - else if (element.type == ElementType::NULL_ELEMENT) - { - hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - if (element.isShowRect) hash_attr_append(hash, "ShowRect", element.isShowRect); - } - else if (element.type == ElementType::GROUP) - { - if (!is_nested_group_parent(parentType, flags)) hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - hash_attr_append(hash, "IsExpanded", element.isExpanded); - hash_attr_append(hash, "Visible", element.isVisible); - if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) && - element.index != -1) - hash_attr_append(hash, "Index", element.index); - } - else if (element.type == ElementType::EVENT_ELEMENT) - { - hash_attr_append(hash, "Id", element.id); - hash_attr_append(hash, "Name", element.name); - } - else if (element.type == ElementType::SOUND_ELEMENT) - { - hash_attr_append(hash, "Id", element.id); - if (parentType != ElementType::TRIGGER) hash_path_attr_append(hash, "Path", element.path); - } - else if (element.type == ElementType::ANIMATION) - { - hash_attr_append(hash, "Name", element.name); - hash_attr_append(hash, "FrameNum", element.frameNum); - hash_attr_append(hash, "Loop", element.isLoop); - if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); - } - else if (element.type == ElementType::LAYER_ANIMATION) - { - hash_attr_append(hash, "LayerId", element.layerId); - hash_attr_append(hash, "Visible", element.isVisible); - if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); - } - else if (element.type == ElementType::NULL_ANIMATION) - { - hash_attr_append(hash, "NullId", element.nullId); - hash_attr_append(hash, "Visible", element.isVisible); - if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); - } - else if (element.type == ElementType::FRAME) - frame_attributes_hash_append(hash, element, parentType, flags); - else if (element.type == ElementType::TRIGGER) - { - if (element.eventId != -1) hash_attr_append(hash, "EventId", element.eventId); - hash_attr_append(hash, "AtFrame", element.atFrame); - } - } - - void element_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags, - std::optional bakeAttributes = std::nullopt); - - void trigger_sounds_hash_append(std::uint64_t& hash, const Element& element, Flags flags) - { - if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return; - - for (auto soundId : element.soundIds) - { - if (soundId == -1) continue; - auto sound = element_make(ElementType::SOUND_ELEMENT); - sound.id = soundId; - element_hash_append(hash, sound, ElementType::TRIGGER, flags); - } - } - - void baked_frames_hash_append(std::uint64_t& hash, const Element& track, int index, Flags flags) - { - const auto& original = track.children[index]; - auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME - ? track.children[index + 1] - : original; - auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN); - - for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex) - { - auto baked = original; - auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay); - baked.duration = FRAME_DURATION_MIN; - baked.interpolation = Interpolation::NONE; - baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); - baked.position = glm::mix(original.position, nextFrame.position, amount); - baked.scale = glm::mix(original.scale, nextFrame.scale, amount); - baked.shear = glm::mix(original.shear, nextFrame.shear, amount); - baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); - baked.tint = glm::mix(original.tint, nextFrame.tint, amount); - element_hash_append(hash, baked, track.type, flags, - bakeIndex == 0 ? std::optional({original.interpolation, bakeDelay}) - : std::nullopt); - } - } - - void element_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags, - std::optional bakeAttributes) - { - auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type); - hash_byte_append(hash, 'E'); - hash_string_append(hash, tag.empty() ? std::string_view(element.tag) : tag); - - element_attributes_hash_append(hash, element, parentType, flags); - if (bakeAttributes) bake_attributes_hash_append(hash, bakeAttributes->interpolation, bakeAttributes->delay); - - hash_byte_append(hash, '['); - trigger_sounds_hash_append(hash, element, flags); - for (int i = 0; i < (int)element.children.size(); ++i) - { - const auto& child = element.children[i]; - if (element_write_skip(child, element.type, flags)) continue; - - if (is_track(element) && is_frame_bake_serialized(child, flags)) - baked_frames_hash_append(hash, element, i, flags); - else - element_hash_append(hash, child, element.type, flags); - } - hash_byte_append(hash, ']'); - } - - std::uint64_t element_hash(const Element& element, Flags flags) - { - auto hash = ANM2_HASH_OFFSET; - element_hash_append(hash, element, ElementType::UNKNOWN, flags); - return hash; - } - - int child_index_get(const Element& element, ElementType type) - { - for (int i = 0; i < (int)element.children.size(); ++i) - if (element.children[i].type == type) return i; - return -1; - } - - ElementType track_container_track_type_get(ElementType containerType) - { - if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION; - if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION; - return ElementType::UNKNOWN; - } - - ElementType track_container_group_container_type_get(ElementType containerType) - { - if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION_GROUPS; - if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION_GROUPS; - return ElementType::UNKNOWN; - } - - int track_group_insert_index_get(const Element& container, ElementType trackType, int groupId) - { - for (int i = 0; i < (int)container.children.size(); ++i) - if (container.children[i].type == trackType && container.children[i].groupId == groupId) return i; - return (int)container.children.size(); - } - - void group_metadata_embed(Element& animation, ElementType trackContainerType) - { - auto groupContainerType = track_container_group_container_type_get(trackContainerType); - auto trackType = track_container_track_type_get(trackContainerType); - auto groupContainerIndex = child_index_get(animation, groupContainerType); - if (groupContainerIndex < 0 || trackType == ElementType::UNKNOWN) return; - - std::vector groups{}; - for (const auto& child : animation.children[groupContainerIndex].children) - if (child.type == ElementType::GROUP) groups.push_back(child); - - if (!groups.empty()) - { - auto trackContainerIndex = child_index_get(animation, trackContainerType); - if (trackContainerIndex < 0) - { - animation.children.push_back(element_make(trackContainerType)); - trackContainerIndex = (int)animation.children.size() - 1; - } - - auto& container = animation.children[trackContainerIndex]; - std::set groupIds{}; - for (const auto& group : groups) - if (group.id >= 0) groupIds.insert(group.id); - std::erase_if(container.children, [&](const Element& child) - { return child.type == ElementType::GROUP && groupIds.contains(child.id); }); - - std::stable_sort(groups.begin(), groups.end(), - [](const Element& left, const Element& right) - { - if (left.index == -1 || right.index == -1) return left.index != -1; - return left.index < right.index; - }); - - for (auto& group : groups) - { - auto insertIndex = group.index >= 0 ? std::min(group.index, (int)container.children.size()) - : track_group_insert_index_get(container, trackType, group.id); - group.index = -1; - container.children.insert(container.children.begin() + insertIndex, std::move(group)); - } - } - - std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; }); - } - - void group_metadata_embed(Element& element) - { - if (element.type == ElementType::ANIMATION) - { - group_metadata_embed(element, ElementType::LAYER_ANIMATIONS); - group_metadata_embed(element, ElementType::NULL_ANIMATIONS); - } - - for (auto& child : element.children) - group_metadata_embed(child); - } - - void group_metadata_extract(Element& animation, ElementType trackContainerType, Flags flags) - { - auto groupContainerType = track_container_group_container_type_get(trackContainerType); - if (groupContainerType == ElementType::UNKNOWN) return; - - std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; }); - if (!has_flag(flags, SERIALIZE_GROUPS)) return; - - auto trackContainerIndex = child_index_get(animation, trackContainerType); - if (trackContainerIndex < 0) return; - - auto& container = animation.children[trackContainerIndex]; - auto groupContainer = element_make(groupContainerType); - std::vector tracks{}; - tracks.reserve(container.children.size()); - - for (int i = 0; i < (int)container.children.size(); ++i) - { - auto child = container.children[i]; - if (child.type == ElementType::GROUP) - { - child.index = i; - groupContainer.children.push_back(std::move(child)); - } - else - tracks.push_back(std::move(child)); - } - - container.children = std::move(tracks); - if (groupContainer.children.empty()) return; - animation.children.insert(animation.children.begin() + trackContainerIndex + 1, std::move(groupContainer)); - } - - void group_metadata_extract(Element& element, Flags flags) - { - if (element.type == ElementType::ANIMATION) - { - group_metadata_extract(element, ElementType::LAYER_ANIMATIONS, flags); - group_metadata_extract(element, ElementType::NULL_ANIMATIONS, flags); - } - - for (auto& child : element.children) - group_metadata_extract(child, flags); - } - - void groups_flatten(Element& element) - { - auto container_flatten = [](Element& container, ElementType childType, bool isRootKept) - { - int nextGroupId{}; - for (const auto& item : container.children) - if (item.type == ElementType::GROUP) nextGroupId = std::max(nextGroupId, item.id + 1); - - std::vector flattened{}; - for (auto item : container.children) - { - if (item.type != ElementType::GROUP) - { - flattened.push_back(item); - continue; - } - - if (item.id < 0) item.id = nextGroupId++; - auto groupId = item.id; - auto children = std::move(item.children); - item.children.clear(); - - if (isRootKept) - { - bool isRootFound{}; - - for (auto child : children) - if (child.type == ElementType::ROOT_ANIMATION) - { - if (isRootFound) continue; - item.children.push_back(child); - isRootFound = true; - } - - if (!isRootFound) item.children.push_back(root_animation_make()); - } - - flattened.push_back(item); - - for (auto child : children) - { - if (child.type != childType) continue; - child.groupId = groupId; - flattened.push_back(child); - } - } - - std::set groupIds{}; - for (const auto& item : flattened) - if (item.type == ElementType::GROUP) groupIds.insert(item.id); - - for (auto& item : flattened) - if (item.type == childType && !groupIds.contains(item.groupId)) item.groupId = -1; - - container.children = std::move(flattened); - }; - - if (element.type == ElementType::ANIMATIONS) - container_flatten(element, ElementType::ANIMATION, false); - else if (element.type == ElementType::LAYER_ANIMATIONS) - container_flatten(element, ElementType::LAYER_ANIMATION, true); - else if (element.type == ElementType::NULL_ANIMATIONS) - container_flatten(element, ElementType::NULL_ANIMATION, true); - - for (auto& child : element.children) - groups_flatten(child); - } - - void group_children_nest(Element& container, ElementType childType) - { - if (childType == ElementType::UNKNOWN) return; - - std::set groupIds{}; - for (const auto& child : container.children) - if (child.type == ElementType::GROUP && child.id >= 0) groupIds.insert(child.id); - if (groupIds.empty()) return; - - std::unordered_map> groupedChildren{}; - for (const auto& child : container.children) - { - if (child.type != childType || !groupIds.contains(child.groupId)) continue; - auto groupedChild = child; - groupedChild.groupId = -1; - groupedChildren[child.groupId].push_back(std::move(groupedChild)); - } - - std::vector nested{}; - nested.reserve(container.children.size()); - for (auto child : container.children) - { - if (child.type == childType && groupIds.contains(child.groupId)) continue; - if (child.type == ElementType::GROUP) - { - auto groupId = child.id; - child.index = -1; - if (auto grouped = groupedChildren.find(groupId); grouped != groupedChildren.end()) - child.children.insert(child.children.end(), std::make_move_iterator(grouped->second.begin()), - std::make_move_iterator(grouped->second.end())); - } - nested.push_back(std::move(child)); - } - - container.children = std::move(nested); - } - - void groups_nest(Element& element) - { - if (element.type == ElementType::ANIMATIONS) - group_children_nest(element, ElementType::ANIMATION); - else if (element.type == ElementType::LAYER_ANIMATIONS) - group_children_nest(element, ElementType::LAYER_ANIMATION); - else if (element.type == ElementType::NULL_ANIMATIONS) - group_children_nest(element, ElementType::NULL_ANIMATION); - - for (auto& child : element.children) - groups_nest(child); - } - - void source_document_erase(Element& element) - { - std::erase_if(element.children, [](const Element& child) { return is_source_document_tag(child.tag); }); - for (auto& child : element.children) - source_document_erase(child); - } - - Element* child_first_get(Element& element, ElementType type) - { - for (auto& child : element.children) - if (child.type == type) return &child; - return nullptr; - } - - const Element* child_first_get(const Element& element, ElementType type) - { - for (const auto& child : element.children) - if (child.type == type) return &child; - return nullptr; - } - - Element* element_child_first_get(Element& element, ElementType type) { return child_first_get(element, type); } - - const Element* element_child_first_get(const Element& element, ElementType type) - { - return child_first_get(element, type); - } - - Element* shader_uniform_get(Element& shader, std::string_view name, bool isCreate) - { - for (auto& child : shader.children) - if (child.type == ElementType::UNIFORM && child.name == name) return &child; - if (!isCreate) return nullptr; - - shader.children.push_back(element_make(ElementType::UNIFORM)); - shader.children.back().name = std::string(name); - return &shader.children.back(); - } - - const Element* shader_uniform_get(const Element& shader, std::string_view name) - { - for (const auto& child : shader.children) - if (child.type == ElementType::UNIFORM && child.name == name) return &child; - return nullptr; - } - - Element* shader_uniform_component_get(Element& uniform, int index, bool isCreate) - { - for (auto& child : uniform.children) - if (child.type == ElementType::COMPONENT && child.index == index) return &child; - if (!isCreate) return nullptr; - - uniform.children.push_back(element_make(ElementType::COMPONENT)); - uniform.children.back().index = index; - return &uniform.children.back(); - } - - const Element* shader_uniform_component_get(const Element& uniform, int index) - { - for (const auto& child : uniform.children) - if (child.type == ElementType::COMPONENT && child.index == index) return &child; - return nullptr; - } - - Element* child_id_get(Element& element, ElementType type, int id) - { - for (auto& child : element.children) - if (child.type == type && child.id == id) return &child; - return nullptr; - } - - const Element* child_id_get(const Element& element, ElementType type, int id) - { - for (const auto& child : element.children) - if (child.type == type && child.id == id) return &child; - return nullptr; - } - - Element* element_child_id_get(Element& element, ElementType type, int id) { return child_id_get(element, type, id); } - - const Element* element_child_id_get(const Element& element, ElementType type, int id) - { - return child_id_get(element, type, id); - } - - 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) - { - for (auto it = element.children.begin(); it != element.children.end(); ++it) - { - if (it->type != type || it->id != id) continue; - element.children.erase(it); - return true; - } - return false; - } - - Element* element_first_get(Element& element, ElementType type) - { - if (element.type == type) return &element; - for (auto& child : element.children) - if (auto result = element_first_get(child, type); result) return result; - return nullptr; - } - - const Element* element_first_get(const Element& element, ElementType type) - { - if (element.type == type) return &element; - for (const auto& child : element.children) - if (auto result = element_first_get(child, type); result) return result; - return nullptr; - } - - 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(const Element& element) - { - return element.type == ElementType::ROOT_ANIMATION || element.type == ElementType::LAYER_ANIMATION || - element.type == ElementType::NULL_ANIMATION || element.type == ElementType::TRIGGERS; - } - - bool is_track_child_valid(ElementType parentType, ElementType childType) - { - if (parentType == ElementType::CONTENT && childType == ElementType::SHADERS) return true; - if (parentType == ElementType::SHADERS) return childType == ElementType::SHADER; - if (parentType == ElementType::SHADER) return childType == ElementType::UNIFORM; - if (parentType == ElementType::UNIFORM) return childType == ElementType::COMPONENT; - if (childType == ElementType::SHADERS || childType == ElementType::SHADER || childType == ElementType::UNIFORM || - childType == ElementType::COMPONENT) - return false; - if (parentType == ElementType::TRIGGERS) return childType == ElementType::TRIGGER; - if (parentType == ElementType::TRIGGER) return childType == ElementType::SOUND_ELEMENT; - if (parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) - return childType == ElementType::GROUP; - if (parentType == ElementType::ROOT_ANIMATION || parentType == ElementType::LAYER_ANIMATION || - parentType == ElementType::NULL_ANIMATION) - return childType == ElementType::FRAME; - return true; - } - - ElementType track_frame_type_get(const Element& track) - { - return track.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - } - - ElementType item_type_to_track_type_get(ItemType type) - { - if (type == ItemType::ROOT) return ElementType::ROOT_ANIMATION; - if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATION; - if (type == ItemType::NULL_) return ElementType::NULL_ANIMATION; - if (type == ItemType::TRIGGER) return ElementType::TRIGGERS; - return ElementType::UNKNOWN; - } - - ElementType item_type_to_container_type_get(ItemType type) - { - if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATIONS; - if (type == ItemType::NULL_) return ElementType::NULL_ANIMATIONS; - return ElementType::UNKNOWN; - } - - Element* animation_group_get(Element& animation, int groupType, int groupId) - { - if (groupId < 0) return nullptr; - auto containerType = item_type_to_container_type_get(static_cast(groupType)); - auto container = child_first_get(animation, containerType); - return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; - } - - const Element* animation_group_get(const Element& animation, int groupType, int groupId) - { - if (groupId < 0) return nullptr; - auto containerType = item_type_to_container_type_get(static_cast(groupType)); - auto container = child_first_get(animation, containerType); - return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; - } - - Element* animation_group_root_get(Element& animation, int groupType, int groupId) - { - auto group = animation_group_get(animation, groupType, groupId); - return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; - } - - const Element* animation_group_root_get(const Element& animation, int groupType, int groupId) - { - auto group = animation_group_get(animation, groupType, groupId); - return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; - } - - Element* animation_group_root_ensure(Element& animation, int groupType, int groupId) - { - auto group = animation_group_get(animation, groupType, groupId); - if (!group) return nullptr; - if (auto root = child_first_get(*group, ElementType::ROOT_ANIMATION)) return root; - group->children.push_back(root_animation_make()); - return &group->children.back(); - } - - int track_id_get(const Element& track) - { - if (track.type == ElementType::LAYER_ANIMATION) return track.layerId; - if (track.type == ElementType::NULL_ANIMATION) return track.nullId; - return -1; - } - - template void tracks_each(Element& parent, ElementType trackType, Callback&& callback) - { - for (auto& child : parent.children) - { - if (child.type == trackType) - callback(child); - else if (child.type == ElementType::GROUP) - tracks_each(child, trackType, callback); - } - } - - template void tracks_each(const Element& parent, ElementType trackType, Callback&& callback) - { - for (const auto& child : parent.children) - { - if (child.type == trackType) - callback(child); - else if (child.type == ElementType::GROUP) - tracks_each(child, trackType, callback); - } - } - - Element* track_find(Element& parent, ElementType trackType, int id) - { - for (auto& child : parent.children) - { - if (child.type == trackType && track_id_get(child) == id) return &child; - if (child.type == ElementType::GROUP) - if (auto found = track_find(child, trackType, id)) return found; - } - return nullptr; - } - - const Element* track_find(const Element& parent, ElementType trackType, int id) - { - for (const auto& child : parent.children) - { - if (child.type == trackType && track_id_get(child) == id) return &child; - if (child.type == ElementType::GROUP) - if (auto found = track_find(child, trackType, id)) return found; - } - return nullptr; - } - - Element* track_group_find(Element& parent, ElementType trackType, int id, int groupId) - { - for (auto& child : parent.children) - { - if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child; - if (child.type == ElementType::GROUP) - if (auto found = track_group_find(child, trackType, id, groupId)) return found; - } - return nullptr; - } - - const Element* track_group_find(const Element& parent, ElementType trackType, int id, int groupId) - { - for (const auto& child : parent.children) - { - if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child; - if (child.type == ElementType::GROUP) - if (auto found = track_group_find(child, trackType, id, groupId)) return found; - } - return nullptr; - } - - void shader_ids_repair(Element& root) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; - if (!shaders) return; - - std::set usedIds{}; - int nextId{}; - for (auto& shader : shaders->children) - { - if (shader.type != ElementType::SHADER) continue; - - while (usedIds.contains(nextId)) - ++nextId; - if (shader.id < 0 || usedIds.contains(shader.id)) shader.id = nextId++; - usedIds.insert(shader.id); - if (shader.name.empty()) shader.name = "New Shader"; - } - } - - void shader_frame_ids_repair(Element& root) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; - auto animations = element_first_get(root, ElementType::ANIMATIONS); - if (!animations) return; - - std::set shaderIds{}; - if (shaders) - for (const auto& shader : shaders->children) - if (shader.type == ElementType::SHADER) shaderIds.insert(shader.id); - - auto frame_repair = [&](auto&& self, Element& element) -> void - { - if (element.type == ElementType::FRAME && element.shaderId != -1 && !shaderIds.contains(element.shaderId)) - element.shaderId = -1; - for (auto& child : element.children) - self(self, child); - }; - frame_repair(frame_repair, *animations); - } - - void region_frame_ids_repair(Element& root) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; - auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; - auto animations = element_first_get(root, ElementType::ANIMATIONS); - if (!layers || !spritesheets || !animations) return; - - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](Element& layerAnimation) - { - auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId); - auto spritesheet = - layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!spritesheet) return; - - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME) continue; - - auto frameCrop = glm::ivec2(frame.crop); - auto frameSize = glm::ivec2(frame.size); - auto framePivot = glm::ivec2(frame.pivot); - auto is_region_match = [&](const Element& region) - { - return region.type == ElementType::REGION && glm::ivec2(region.crop) == frameCrop && - glm::ivec2(region.size) == frameSize && glm::ivec2(region.pivot) == framePivot; - }; - - auto region = frame.regionId == -1 - ? nullptr - : child_id_get(*spritesheet, ElementType::REGION, frame.regionId); - if (region && is_region_match(*region)) continue; - - for (const auto& candidate : spritesheet->children) - if (is_region_match(candidate)) - { - frame.regionId = candidate.id; - break; - } - } - }); - } - } - - void region_ids_remap(Element& root) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; - auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; - auto animations = element_first_get(root, ElementType::ANIMATIONS); - if (!spritesheets) return; - - std::unordered_map> remaps{}; - for (auto& spritesheet : spritesheets->children) - { - if (spritesheet.type != ElementType::SPRITESHEET) continue; - - std::unordered_map remap{}; - int nextId{}; - for (auto& region : spritesheet.children) - { - if (region.type != ElementType::REGION) continue; - remap[region.id] = nextId; - region.id = nextId++; - } - if (!remap.empty()) remaps[spritesheet.id] = std::move(remap); - } - - if (!layers || !animations || remaps.empty()) return; - - std::unordered_map layerSpritesheets{}; - for (const auto& layer : layers->children) - if (layer.type == ElementType::LAYER_ELEMENT) layerSpritesheets[layer.id] = layer.spritesheetId; - - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](Element& layerAnimation) - { - auto layer = layerSpritesheets.find(layerAnimation.layerId); - if (layer == layerSpritesheets.end()) return; - auto remap = remaps.find(layer->second); - if (remap == remaps.end()) return; - - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; - if (auto it = remap->second.find(frame.regionId); it != remap->second.end()) - frame.regionId = it->second; - else - frame.regionId = -1; - } - }); - } - } - - void shader_ids_remap(Element& root) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; - - std::unordered_map remap{}; - int nextId{}; - if (shaders) - for (auto& shader : shaders->children) - { - if (shader.type != ElementType::SHADER) continue; - remap[shader.id] = nextId; - shader.id = nextId++; - } - - auto frame_remap = [&](auto&& self, Element& element) -> void - { - if (element.type == ElementType::FRAME && element.shaderId != -1) - { - if (auto it = remap.find(element.shaderId); it != remap.end()) - element.shaderId = it->second; - else - element.shaderId = -1; - } - for (auto& child : element.children) - self(self, child); - }; - frame_remap(frame_remap, root); - } - - bool is_track_group_visible(const Element& container, const Element& track) - { - 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; - } - - Element* animation_item_get(Element& animation, ItemType type, int id, int groupType, int groupId) - { - auto trackType = item_type_to_track_type_get(type); - if (type == ItemType::ROOT && groupType != NONE && groupId != -1) - return animation_group_root_get(animation, groupType, groupId); - if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType); - - auto container = child_first_get(animation, item_type_to_container_type_get(type)); - if (!container) return nullptr; - return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId) - : track_find(*container, trackType, id); - } - - Element* animation_item_get(Element& animation, ItemType type, int id) - { - return animation_item_get(animation, type, id, NONE, -1); - } - - const Element* animation_item_get(const Element& animation, ItemType type, int id, int groupType, int groupId) - { - auto trackType = item_type_to_track_type_get(type); - if (type == ItemType::ROOT && groupType != NONE && groupId != -1) - return animation_group_root_get(animation, groupType, groupId); - if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType); - - auto container = child_first_get(animation, item_type_to_container_type_get(type)); - if (!container) return nullptr; - return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId) - : track_find(*container, trackType, id); - } - - const Element* animation_item_get(const Element& animation, ItemType type, int id) - { - return animation_item_get(animation, type, id, NONE, -1); - } - - 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) continue; - if (frameIndex == index) return i; - ++frameIndex; - } - return -1; - } - - int track_frames_count_get(const Element& track) - { - auto frameType = track_frame_type_get(track); - int count{}; - for (const auto& child : track.children) - if (child.type == frameType) ++count; - return count; - } - - int track_frame_insert_child_index_get(const Element& track, int index) - { - auto targetFrameIndex = std::max(0, index); - 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) continue; - if (frameIndex == targetFrameIndex) return i; - ++frameIndex; - } - return (int)track.children.size(); - } - - Element* track_frame_get(Element& track, int index) - { - auto childIndex = track_frame_child_index_get(track, index); - return childIndex == -1 ? nullptr : &track.children[childIndex]; - } - - const Element* track_frame_get(const Element& track, int index) - { - auto childIndex = track_frame_child_index_get(track, index); - return childIndex == -1 ? nullptr : &track.children[childIndex]; - } - - Element frame_generate(const Element& track, float time) - { - auto frame = element_make(track_frame_type_get(track)); - frame.isVisible = false; - if (track.children.empty()) return frame; - - time = std::max(time, 0.0f); - - const Element* frameNext = nullptr; - int durationCurrent{}; - int durationNext{}; - auto frameType = track_frame_type_get(track); - - for (int i = 0; i < (int)track.children.size(); ++i) - { - const auto& iFrame = track.children[i]; - if (iFrame.type != frameType) continue; - - if (frameType == ElementType::TRIGGER) - { - if ((int)time == iFrame.atFrame) - { - frame = iFrame; - break; - } - continue; - } - - frame = iFrame; - durationNext += frame.duration; - - if (time >= durationCurrent && time < durationNext) - { - for (int next = i + 1; next < (int)track.children.size(); ++next) - if (track.children[next].type == ElementType::FRAME) - { - frameNext = &track.children[next]; - break; - } - break; - } - - durationCurrent += frame.duration; - } - - if (frameType != ElementType::TRIGGER && frame.interpolation != Interpolation::NONE && frameNext && - frame.duration > 1) - { - auto amount = - interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent)); - frame.rotation = glm::mix(frame.rotation, frameNext->rotation, amount); - frame.position = glm::mix(frame.position, frameNext->position, amount); - frame.scale = glm::mix(frame.scale, frameNext->scale, amount); - frame.shear = glm::mix(frame.shear, frameNext->shear, amount); - frame.colorOffset = glm::mix(frame.colorOffset, frameNext->colorOffset, amount); - frame.tint = glm::mix(frame.tint, frameNext->tint, amount); - } - - 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); - int frameCount{}; - for (const auto& frame : track.children) - if (frame.type == frameType) ++frameCount; - 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 frame = &track.children[childIndex]; - - auto original = *frame; - if (original.duration <= FRAME_DURATION_MIN) - { - frame->interpolation = Interpolation::NONE; - return; - } - - auto nextFrame = track_frame_get(track, index + 1); - auto next = nextFrame ? *nextFrame : original; - int duration{}; - interval = std::max(interval, FRAME_DURATION_MIN); - std::vector bakedFrames{}; - bakedFrames.reserve((original.duration + interval - 1) / interval); - - while (duration < original.duration) - { - auto baked = original; - auto amount = interpolation_factor(original.interpolation, (float)duration / original.duration); - baked.duration = std::min(interval, original.duration - duration); - baked.interpolation = Interpolation::NONE; - baked.rotation = glm::mix(original.rotation, next.rotation, amount); - baked.position = glm::mix(original.position, next.position, amount); - baked.scale = glm::mix(original.scale, next.scale, amount); - baked.shear = glm::mix(original.shear, next.shear, amount); - baked.colorOffset = glm::mix(original.colorOffset, next.colorOffset, amount); - baked.tint = glm::mix(original.tint, next.tint, amount); - if (isRoundScale) baked.scale = glm::round(baked.scale); - if (isRoundRotation) baked.rotation = std::round(baked.rotation); - - bakedFrames.push_back(baked); - duration += baked.duration; - } - - if (bakedFrames.empty()) return; - track.children[childIndex] = std::move(bakedFrames.front()); - track.children.insert(track.children.begin() + childIndex + 1, std::make_move_iterator(bakedFrames.begin() + 1), - std::make_move_iterator(bakedFrames.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 first = - frameType == ElementType::TRIGGER ? document.FirstChildElement("Trigger") : document.FirstChildElement("Frame"); - if (!first) - { - if (errorString) *errorString = frameType == ElementType::TRIGGER ? "No valid trigger(s)." : "No valid frame(s)."; - 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("Frame")) - { - 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("Trigger")) - { - 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) - { - const auto clamp_identity = [](auto value) { return value; }; - const auto clamp_duration = [](int value) { return std::max(FRAME_DURATION_MIN, value); }; - - if (selection.empty()) return; - - auto apply_scalar_with_clamp = [&](auto& target, const auto& optionalValue, auto clampFunc) - { - if (!optionalValue) return; - auto value = *optionalValue; - - switch (changeType) - { - case ChangeType::ADJUST: - target = clampFunc(value); - break; - case ChangeType::ADD: - target = clampFunc(target + value); - break; - case ChangeType::SUBTRACT: - target = clampFunc(target - value); - break; - case ChangeType::MULTIPLY: - target = clampFunc(target * value); - break; - case ChangeType::DIVIDE: - if (value == decltype(value){}) return; - target = clampFunc(target / value); - break; - } - }; - - auto apply_scalar = [&](auto& target, const auto& optionalValue) - { apply_scalar_with_clamp(target, optionalValue, clamp_identity); }; - - 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_scalar(frame->rotation, change.rotation); - apply_scalar_with_clamp(frame->duration, change.duration, clamp_duration); - - if (itemType == ItemType::LAYER) - { - apply_scalar(frame->crop.x, change.cropX); - apply_scalar(frame->crop.y, change.cropY); - apply_scalar(frame->pivot.x, change.pivotX); - apply_scalar(frame->pivot.y, change.pivotY); - apply_scalar(frame->size.x, change.sizeX); - apply_scalar(frame->size.y, change.sizeY); - if (change.regionId) frame->regionId = *change.regionId; - if (change.shaderId) frame->shaderId = *change.shaderId; - } - - apply_scalar(frame->position.x, change.positionX); - apply_scalar(frame->position.y, change.positionY); - apply_scalar(frame->scale.x, change.scaleX); - apply_scalar(frame->scale.y, change.scaleY); - apply_scalar(frame->shear.x, change.shearX); - apply_scalar(frame->shear.y, change.shearY); - apply_scalar(frame->colorOffset.x, change.colorOffsetR); - apply_scalar(frame->colorOffset.y, change.colorOffsetG); - apply_scalar(frame->colorOffset.z, change.colorOffsetB); - apply_scalar(frame->tint.x, change.tintR); - apply_scalar(frame->tint.y, change.tintG); - apply_scalar(frame->tint.z, change.tintB); - apply_scalar(frame->tint.w, change.tintA); - } - } - - 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; - } - - enum class InterpolationBakeType - { - SPECIAL, - ALL - }; - - bool is_frame_interpolation_baked(const Element& frame, InterpolationBakeType type) - { - if (frame.interpolation == Interpolation::NONE) return false; - return type == InterpolationBakeType::ALL || frame.interpolation != Interpolation::LINEAR; - } - - void track_frames_bake(Element& track, int interval, bool isRoundScale, bool isRoundRotation, - InterpolationBakeType type) - { - for (int index = (int)track.children.size() - 1; index >= 0; --index) - { - auto original = track.children[index]; - if (original.type != ElementType::FRAME) continue; - if (!is_frame_interpolation_baked(original, type)) continue; - - if (original.duration <= FRAME_DURATION_MIN) - { - track.children[index].interpolation = Interpolation::NONE; - continue; - } - - auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME - ? track.children[index + 1] - : original; - int duration{}; - int insertIndex = index; - - while (duration < original.duration) - { - auto baked = original; - float amount = interpolation_factor(original.interpolation, (float)duration / original.duration); - baked.duration = std::min(interval, original.duration - duration); - baked.interpolation = Interpolation::NONE; - baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); - baked.position = glm::mix(original.position, nextFrame.position, amount); - baked.scale = glm::mix(original.scale, nextFrame.scale, amount); - baked.shear = glm::mix(original.shear, nextFrame.shear, amount); - baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); - baked.tint = glm::mix(original.tint, nextFrame.tint, amount); - if (isRoundScale) baked.scale = glm::round(baked.scale); - if (isRoundRotation) baked.rotation = std::round(baked.rotation); - - if (insertIndex == index) - track.children[insertIndex] = baked; - else - track.children.insert(track.children.begin() + insertIndex, baked); - - duration += baked.duration; - ++insertIndex; - } - } - } - - void interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation, - InterpolationBakeType type) - { - if (is_track(element)) - { - track_frames_bake(element, interval, isRoundScale, isRoundRotation, type); - return; - } - - for (auto& child : element.children) - 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); - } - - void layer_animation_ids_remap(Element& element, const std::unordered_map& remap) - { - if (element.type == ElementType::LAYER_ANIMATION) - if (auto it = remap.find(element.layerId); it != remap.end()) element.layerId = it->second; - - for (auto& child : element.children) - layer_animation_ids_remap(child, remap); - } - Anm2::Anm2() { root = element_make(ElementType::ANIMATED_ACTOR); @@ -2553,10 +191,7 @@ namespace anm2ed std::uint64_t Anm2::hash(Options options) const { - auto hash = ANM2_HASH_OFFSET; - hash_byte_append(hash, options.isExtendedFormat ? 'E' : 'A'); - element_hash_append(hash, root, ElementType::UNKNOWN, SERIALIZE_ANM2ED_DEFAULT); - return hash; + return anm2_hash_get(root, options); } bool Anm2::is_special_interpolated_frames() const { return ::anm2ed::is_special_interpolated_frames(root); } @@ -2566,820 +201,4 @@ namespace anm2ed ::anm2ed::special_interpolated_frames_bake(root, std::max(interval, FRAME_DURATION_MIN), isRoundScale, isRoundRotation); } - - void Anm2::region_frames_sync(bool isClearInvalid) - { - auto content = child_first_get(root, ElementType::CONTENT); - auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; - auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; - auto animations = element_first_get(root, ElementType::ANIMATIONS); - if (!layers || !spritesheets || !animations) return; - - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](Element& layerAnimation) - { - auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId); - auto spritesheet = - layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!spritesheet) return; - - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; - auto region = child_id_get(*spritesheet, ElementType::REGION, frame.regionId); - if (!region) - { - if (isClearInvalid) frame.regionId = -1; - continue; - } - - frame.crop = region->crop; - frame.size = region->size; - frame.pivot = region->pivot; - } - }); - } - } - - Anm2 Anm2::normalized_for_serialize(Flags flags) const - { - auto normalized = *this; - source_document_erase(normalized.root); - group_frames_restore(normalized.root); - groups_flatten(normalized.root); - if (has_flag(flags, SERIALIZE_BAKE_GROUP_FRAMES)) group_frames_bake(normalized.root); - if (has_flag(flags, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)) - all_interpolated_frames_bake(normalized.root, FRAME_DURATION_MIN, false, false); - region_ids_remap(normalized.root); - shader_ids_remap(normalized.root); - if (has_flag(flags, SERIALIZE_GROUPS) && has_flag(flags, SERIALIZE_NESTED_GROUPS)) - groups_nest(normalized.root); - else - group_metadata_extract(normalized.root, flags); - - auto content = child_first_get(normalized.root, ElementType::CONTENT); - if (content) std::erase_if(content->children, [](const Element& element) { return element.tag == "Groups"; }); - if (auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr) - { - std::unordered_map remap{}; - int nextId{}; - for (auto& layer : layers->children) - { - if (layer.type != ElementType::LAYER_ELEMENT) continue; - remap[layer.id] = nextId; - layer.id = nextId++; - } - layer_animation_ids_remap(normalized.root, remap); - } - - return normalized; - } - - Element* Anm2::element_get(ElementType type) - { - if (type == ElementType::ANIMATED_ACTOR) return &root; - if (type == ElementType::ANIMATIONS) return element_first_get(root, type); - - auto content = child_first_get(root, ElementType::CONTENT); - if (!content) return nullptr; - if (type == ElementType::CONTENT) return content; - if (auto container = child_first_get(*content, type)) return container; - - switch (type) - { - case ElementType::SPRITESHEETS: - case ElementType::SHADERS: - case ElementType::LAYERS: - case ElementType::NULLS: - case ElementType::EVENTS: - case ElementType::SOUNDS: - content->children.push_back(element_make(type)); - return &content->children.back(); - default: - break; - } - - return element_first_get(root, type); - } - - const Element* Anm2::element_get(ElementType type) const - { - if (type == ElementType::ANIMATED_ACTOR) return &root; - if (type == ElementType::ANIMATIONS) return element_first_get(root, type); - - auto content = child_first_get(root, ElementType::CONTENT); - if (!content) return nullptr; - if (type == ElementType::CONTENT) return content; - if (auto container = child_first_get(*content, type)) return container; - return element_first_get(root, type); - } - - Element* Anm2::element_get(ElementType type, int id) - { - if (type == ElementType::ANIMATION) - { - auto animations = element_get(ElementType::ANIMATIONS); - if (!animations || id < 0) return nullptr; - int current{}; - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (current == id) return &animation; - ++current; - } - return nullptr; - } - - auto container = element_get(element_container_type_get(type)); - return container ? child_id_get(*container, type, id) : nullptr; - } - - const Element* Anm2::element_get(ElementType type, int id) const - { - if (type == ElementType::ANIMATION) - { - auto animations = element_get(ElementType::ANIMATIONS); - if (!animations || id < 0) return nullptr; - int current{}; - for (const auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (current == id) return &animation; - ++current; - } - return nullptr; - } - - auto container = element_get(element_container_type_get(type)); - return container ? child_id_get(*container, type, id) : nullptr; - } - - Element* Anm2::element_get(int animationIndex, ItemType type, int id) - { - auto animation = element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, type, id) : nullptr; - } - - const Element* Anm2::element_get(int animationIndex, ItemType type, int id) const - { - auto animation = element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, type, id) : nullptr; - } - - Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId) - { - auto animation = element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr; - } - - const Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId) const - { - auto animation = element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr; - } - - Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id) - { - auto item = element_get(animationIndex, type, id); - return item ? track_frame_get(*item, frameIndex) : nullptr; - } - - const Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id) const - { - auto item = element_get(animationIndex, type, id); - return item ? track_frame_get(*item, frameIndex) : nullptr; - } - - Element* Anm2::element_get(Reference reference) - { - auto itemType = static_cast(reference.itemType); - auto item = - element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId); - if (reference.frameIndex < 0) return item; - return item ? track_frame_get(*item, reference.frameIndex) : nullptr; - } - - const Element* Anm2::element_get(Reference reference) const - { - auto itemType = static_cast(reference.itemType); - auto item = - element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId); - if (reference.frameIndex < 0) return item; - return item ? track_frame_get(*item, reference.frameIndex) : nullptr; - } - - std::set Anm2::element_unused(ElementType type) const - { - std::set used{}; - - if (type == ElementType::SPRITESHEET) - { - if (auto layers = element_get(ElementType::LAYERS)) - for (const auto& layer : layers->children) - if (layer.type == ElementType::LAYER_ELEMENT && layer.spritesheetId != -1) used.insert(layer.spritesheetId); - } - else if (auto animations = element_get(ElementType::ANIMATIONS)) - for (const auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - if (type == ElementType::EVENT_ELEMENT) - { - auto triggers = child_first_get(animation, ElementType::TRIGGERS); - if (!triggers) continue; - for (const auto& trigger : triggers->children) - if (trigger.type == ElementType::TRIGGER && trigger.eventId != -1) used.insert(trigger.eventId); - } - else if (type == ElementType::SOUND_ELEMENT) - { - auto triggers = child_first_get(animation, ElementType::TRIGGERS); - if (!triggers) continue; - for (const auto& trigger : triggers->children) - { - if (trigger.type != ElementType::TRIGGER) continue; - for (auto id : trigger.soundIds) - used.insert(id); - } - } - else if (type == ElementType::SHADER) - { - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](const Element& layerAnimation) - { - for (const auto& frame : layerAnimation.children) - if (frame.type == ElementType::FRAME && frame.shaderId != -1) used.insert(frame.shaderId); - }); - } - else if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) - { - auto containerType = - type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; - auto tracks = child_first_get(animation, containerType); - if (!tracks) continue; - auto trackType = - type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; - tracks_each(*tracks, trackType, - [&](const Element& track) - { - if (track.type == ElementType::LAYER_ANIMATION) - used.insert(track.layerId); - else if (track.type == ElementType::NULL_ANIMATION) - used.insert(track.nullId); - }); - } - } - - std::set unused{}; - if (auto container = element_get(element_container_type_get(type))) - for (const auto& element : container->children) - if (element.type == type && !used.contains(element.id)) unused.insert(element.id); - return unused; - } - - std::set Anm2::element_unused(ElementType type, const Element& animation) const - { - if (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT) return {}; - - std::set used{}; - auto containerType = - type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; - if (auto tracks = child_first_get(animation, containerType)) - { - auto trackType = type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; - tracks_each(*tracks, trackType, - [&](const Element& track) - { - if (track.type == ElementType::LAYER_ANIMATION) - used.insert(track.layerId); - else if (track.type == ElementType::NULL_ANIMATION) - used.insert(track.nullId); - }); - } - - std::set unused{}; - if (auto container = element_get(element_container_type_get(type))) - for (const auto& element : container->children) - if (element.type == type && !used.contains(element.id)) unused.insert(element.id); - return unused; - } - - std::set Anm2::element_unused(ElementType type, int parentId) const - { - if (type != ElementType::REGION) return {}; - - std::set used{}; - auto animations = element_first_get(root, ElementType::ANIMATIONS); - if (animations) - for (const auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](const Element& layerAnimation) - { - auto layer = element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); - if (!layer || layer->spritesheetId != parentId) return; - for (const auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME) continue; - if (frame.regionId != -1) used.insert(frame.regionId); - } - }); - } - - std::set unused{}; - if (auto spritesheet = element_get(ElementType::SPRITESHEET, parentId)) - for (const auto& child : spritesheet->children) - if (child.type == type && !used.contains(child.id)) unused.insert(child.id); - return unused; - } - - bool Anm2::deserialize(ElementType type, const std::string& string, bool isAppend, std::string* errorString, - const std::filesystem::path& directory) - { - 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 = element_container_type_get(type); - auto container = element_get(containerType); - if (!container) - { - if (errorString) *errorString = std::format("No {} container.", element_tag_get(containerType)); - return false; - } - - std::optional workingDirectory{}; - if ((type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET) && !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 (type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET) - element.path = path::backslash_handle(element.path); - container->children.push_back(element); - } - - return true; - } - - bool Anm2::regions_deserialize(int spritesheetId, const std::string& string, bool isAppend, std::string* errorString) - { - XMLDocument document{}; - if (document.Parse(string.c_str()) != XML_SUCCESS) - { - if (errorString) *errorString = document.ErrorStr(); - return false; - } - - if (!document.FirstChildElement("Region")) - { - if (errorString) *errorString = "No valid region(s)."; - return false; - } - - auto spritesheet = element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) - { - if (errorString) *errorString = "No spritesheet."; - return false; - } - - for (auto element = document.FirstChildElement("Region"); element; element = element->NextSiblingElement("Region")) - { - auto region = element_read(element); - if (region.type != ElementType::REGION) continue; - if (isAppend) - region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - else - element_child_id_erase(*spritesheet, ElementType::REGION, region.id); - spritesheet->children.push_back(region); - } - - return true; - } - - 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 = element_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 *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), - rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); - } - - 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 *= math::quad_model_parent_get( - groupRootFrame.position, {}, math::percent_to_unit(groupRootFrame.scale), - groupRootFrame.rotation, math::percent_to_unit(groupRootFrame.shear)); - } - - 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}; - } - - Element* animation_container_get(Element& animation, ElementType type) - { - if (auto container = child_first_get(animation, type)) return container; - animation.children.push_back(element_make(type)); - return &animation.children.back(); - } - - int Anm2::layer_animation_add(int animationIndex, int id, int insertBeforeId, std::string name, int spritesheetId, - types::destination::Type destination) - { - auto layers = element_get(ElementType::LAYERS); - if (!layers) return -1; - - id = id == -1 ? element_child_next_id_get(*layers, ElementType::LAYER_ELEMENT) : id; - auto layer = element_child_id_get(*layers, ElementType::LAYER_ELEMENT, id); - if (!layer) - { - layers->children.push_back(element_make(ElementType::LAYER_ELEMENT)); - layer = &layers->children.back(); - layer->id = id; - } - - if (!name.empty()) layer->name = name; - layer->spritesheetId = element_get(ElementType::SPRITESHEET, spritesheetId) ? spritesheetId : 0; - - auto add = [&](Element& animation) - { - if (animation_item_get(animation, ItemType::LAYER, id)) return; - auto layerAnimations = animation_container_get(animation, ElementType::LAYER_ANIMATIONS); - auto item = element_make(ElementType::LAYER_ANIMATION); - item.layerId = id; - - if (insertBeforeId != -1) - for (auto it = layerAnimations->children.begin(); it != layerAnimations->children.end(); ++it) - if (it->type == ElementType::LAYER_ANIMATION && it->layerId == insertBeforeId) - { - layerAnimations->children.insert(it, item); - return; - } - - layerAnimations->children.push_back(item); - }; - - 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; - } - - int Anm2::null_animation_add(int animationIndex, int id, std::string name, bool isShowRect, - types::destination::Type destination) - { - auto nulls = element_get(ElementType::NULLS); - if (!nulls) return -1; - - id = id == -1 ? element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT) : id; - auto null = element_child_id_get(*nulls, ElementType::NULL_ELEMENT, id); - if (!null) - { - nulls->children.push_back(element_make(ElementType::NULL_ELEMENT)); - null = &nulls->children.back(); - null->id = id; - } - - if (!name.empty()) null->name = name; - null->isShowRect = isShowRect; - - auto add = [&](Element& animation) - { - if (animation_item_get(animation, ItemType::NULL_, id)) return; - auto nullAnimations = animation_container_get(animation, ElementType::NULL_ANIMATIONS); - auto item = element_make(ElementType::NULL_ANIMATION); - item.nullId = id; - nullAnimations->children.push_back(item); - }; - - 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; - } - - 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; - } - - int track_length_get(const Element& track) - { - int length{}; - if (track.type == ElementType::TRIGGERS) - { - for (const auto& trigger : track.children) - if (trigger.type == ElementType::TRIGGER) length = std::max(length, trigger.atFrame); - return length; - } - - for (const auto& frame : track.children) - if (frame.type == ElementType::FRAME) length += frame.duration; - 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)); - if (auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS)) - { - group_roots_length_apply(*layerAnimations); - tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, - [&](const Element& track) { length = std::max(length, track_length_get(track)); }); - } - if (auto nullAnimations = child_first_get(animation, ElementType::NULL_ANIMATIONS)) - { - group_roots_length_apply(*nullAnimations); - tracks_each(*nullAnimations, ElementType::NULL_ANIMATION, - [&](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); - } - - Element* track_get(Element& tracks, const Element& source) - { - for (auto& track : tracks.children) - { - if (track.type == ElementType::GROUP) - if (auto result = track_get(track, source)) return result; - if (track.type != source.type) continue; - if (track.type == ElementType::LAYER_ANIMATION && track.layerId == source.layerId) return &track; - if (track.type == ElementType::NULL_ANIMATION && track.nullId == source.nullId) return &track; - } - return nullptr; - } - - 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_first_get(destination, containerType); - if (!destinationTracks) - { - destination.children.push_back(element_make(containerType)); - destinationTracks = &destination.children.back(); - } - - for (const auto& sourceTrack : sourceTracks->children) - { - if (sourceTrack.type == ElementType::GROUP) - destinationTracks->children.push_back(sourceTrack); - else if (auto destinationTrack = track_get(*destinationTracks, sourceTrack)) - track_merge(*destinationTrack, sourceTrack, type); - else - destinationTracks->children.push_back(sourceTrack); - } - } - - 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; - - if (auto sourceRoot = child_first_get(*source, ElementType::ROOT_ANIMATION)) - { - auto targetRoot = child_first_get(*targetAnimation, ElementType::ROOT_ANIMATION); - if (!targetRoot) - { - targetAnimation->children.push_back(element_make(ElementType::ROOT_ANIMATION)); - targetRoot = &targetAnimation->children.back(); - } - track_merge(*targetRoot, *sourceRoot, type); - } - - animation_tracks_merge(*targetAnimation, *source, ElementType::LAYER_ANIMATIONS, type); - animation_tracks_merge(*targetAnimation, *source, ElementType::NULL_ANIMATIONS, type); - - if (auto sourceTriggers = child_first_get(*source, ElementType::TRIGGERS)) - { - auto targetTriggers = child_first_get(*targetAnimation, ElementType::TRIGGERS); - if (!targetTriggers) - { - targetAnimation->children.push_back(element_make(ElementType::TRIGGERS)); - targetTriggers = &targetAnimation->children.back(); - } - track_merge(*targetTriggers, *sourceTriggers, type); - } - } - - 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; - } } diff --git a/src/anm2/element.cpp b/src/anm2/element.cpp new file mode 100644 index 0000000..b6cedfe --- /dev/null +++ b/src/anm2/element.cpp @@ -0,0 +1,683 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ + constexpr std::array ELEMENT_TAGS = { +#define X(symbol, tag) std::string_view{tag}, + ANM2_ELEMENT_TYPES +#undef X + }; + + + ElementType element_type_get(std::string_view tag) + { + for (std::size_t i = 0; i < ELEMENT_TAGS.size(); ++i) + if (ELEMENT_TAGS[i] == tag) return (ElementType)i; + return ElementType::UNKNOWN; + } + + std::string_view element_tag_get(ElementType type) + { + auto index = (std::size_t)type; + if (index >= ELEMENT_TAGS.size()) return {}; + return ELEMENT_TAGS[index]; + } + + ElementType element_container_type_get(ElementType type) + { + switch (type) + { + case ElementType::SPRITESHEET: + return ElementType::SPRITESHEETS; + case ElementType::SHADER: + return ElementType::SHADERS; + case ElementType::LAYER_ELEMENT: + return ElementType::LAYERS; + case ElementType::NULL_ELEMENT: + return ElementType::NULLS; + case ElementType::EVENT_ELEMENT: + return ElementType::EVENTS; + case ElementType::SOUND_ELEMENT: + return ElementType::SOUNDS; + case ElementType::ANIMATION: + return ElementType::ANIMATIONS; + default: + return ElementType::UNKNOWN; + } + } + + Element element_make(ElementType type) + { + Element element{}; + element.type = type; + element.tag = std::string(element_tag_get(type)); + return element; + } + + Element root_animation_make() + { + auto root = element_make(ElementType::ROOT_ANIMATION); + root.children.push_back(element_make(ElementType::FRAME)); + return root; + } + + Element* child_first_get(Element& element, ElementType type) + { + for (auto& child : element.children) + if (child.type == type) return &child; + return nullptr; + } + + const Element* child_first_get(const Element& element, ElementType type) + { + for (const auto& child : element.children) + if (child.type == type) return &child; + return nullptr; + } + + Element* element_child_first_get(Element& element, ElementType type) { return child_first_get(element, type); } + + const Element* element_child_first_get(const Element& element, ElementType type) + { + return child_first_get(element, type); + } + + Element* shader_uniform_get(Element& shader, std::string_view name, bool isCreate) + { + for (auto& child : shader.children) + if (child.type == ElementType::UNIFORM && child.name == name) return &child; + if (!isCreate) return nullptr; + + shader.children.push_back(element_make(ElementType::UNIFORM)); + shader.children.back().name = std::string(name); + return &shader.children.back(); + } + + const Element* shader_uniform_get(const Element& shader, std::string_view name) + { + for (const auto& child : shader.children) + if (child.type == ElementType::UNIFORM && child.name == name) return &child; + return nullptr; + } + + Element* shader_uniform_component_get(Element& uniform, int index, bool isCreate) + { + for (auto& child : uniform.children) + if (child.type == ElementType::COMPONENT && child.index == index) return &child; + if (!isCreate) return nullptr; + + uniform.children.push_back(element_make(ElementType::COMPONENT)); + uniform.children.back().index = index; + return &uniform.children.back(); + } + + const Element* shader_uniform_component_get(const Element& uniform, int index) + { + for (const auto& child : uniform.children) + if (child.type == ElementType::COMPONENT && child.index == index) return &child; + return nullptr; + } + + Element* child_id_get(Element& element, ElementType type, int id) + { + for (auto& child : element.children) + if (child.type == type && child.id == id) return &child; + return nullptr; + } + + const Element* child_id_get(const Element& element, ElementType type, int id) + { + for (const auto& child : element.children) + if (child.type == type && child.id == id) return &child; + return nullptr; + } + + Element* element_child_id_get(Element& element, ElementType type, int id) { return child_id_get(element, type, id); } + + const Element* element_child_id_get(const Element& element, ElementType type, int id) + { + return child_id_get(element, type, id); + } + + 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) + { + for (auto it = element.children.begin(); it != element.children.end(); ++it) + { + if (it->type != type || it->id != id) continue; + element.children.erase(it); + return true; + } + return false; + } + + Element* element_first_get(Element& element, ElementType type) + { + if (element.type == type) return &element; + for (auto& child : element.children) + if (auto result = element_first_get(child, type); result) return result; + return nullptr; + } + + const Element* element_first_get(const Element& element, ElementType type) + { + if (element.type == type) return &element; + for (const auto& child : element.children) + if (auto result = element_first_get(child, type); result) return result; + return nullptr; + } + + 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(const Element& element) + { + return element.type == ElementType::ROOT_ANIMATION || element.type == ElementType::LAYER_ANIMATION || + element.type == ElementType::NULL_ANIMATION || element.type == ElementType::TRIGGERS; + } + + bool is_track_child_valid(ElementType parentType, ElementType childType) + { + if (parentType == ElementType::CONTENT && childType == ElementType::SHADERS) return true; + if (parentType == ElementType::SHADERS) return childType == ElementType::SHADER; + if (parentType == ElementType::SHADER) return childType == ElementType::UNIFORM; + if (parentType == ElementType::UNIFORM) return childType == ElementType::COMPONENT; + if (childType == ElementType::SHADERS || childType == ElementType::SHADER || childType == ElementType::UNIFORM || + childType == ElementType::COMPONENT) + return false; + if (parentType == ElementType::TRIGGERS) return childType == ElementType::TRIGGER; + if (parentType == ElementType::TRIGGER) return childType == ElementType::SOUND_ELEMENT; + if (parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) + return childType == ElementType::GROUP; + if (parentType == ElementType::ROOT_ANIMATION || parentType == ElementType::LAYER_ANIMATION || + parentType == ElementType::NULL_ANIMATION) + return childType == ElementType::FRAME; + return true; + } + + ElementType track_frame_type_get(const Element& track) + { + return track.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; + } + + ElementType item_type_to_track_type_get(ItemType type) + { + if (type == ItemType::ROOT) return ElementType::ROOT_ANIMATION; + if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATION; + if (type == ItemType::NULL_) return ElementType::NULL_ANIMATION; + if (type == ItemType::TRIGGER) return ElementType::TRIGGERS; + return ElementType::UNKNOWN; + } + + ElementType item_type_to_container_type_get(ItemType type) + { + if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATIONS; + if (type == ItemType::NULL_) return ElementType::NULL_ANIMATIONS; + return ElementType::UNKNOWN; + } + + Element* animation_group_get(Element& animation, int groupType, int groupId) + { + if (groupId < 0) return nullptr; + auto containerType = item_type_to_container_type_get(static_cast(groupType)); + auto container = child_first_get(animation, containerType); + return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; + } + + const Element* animation_group_get(const Element& animation, int groupType, int groupId) + { + if (groupId < 0) return nullptr; + auto containerType = item_type_to_container_type_get(static_cast(groupType)); + auto container = child_first_get(animation, containerType); + return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; + } + + Element* animation_group_root_get(Element& animation, int groupType, int groupId) + { + auto group = animation_group_get(animation, groupType, groupId); + return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; + } + + const Element* animation_group_root_get(const Element& animation, int groupType, int groupId) + { + auto group = animation_group_get(animation, groupType, groupId); + return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; + } + + Element* animation_group_root_ensure(Element& animation, int groupType, int groupId) + { + auto group = animation_group_get(animation, groupType, groupId); + if (!group) return nullptr; + if (auto root = child_first_get(*group, ElementType::ROOT_ANIMATION)) return root; + group->children.push_back(root_animation_make()); + return &group->children.back(); + } + + int track_id_get(const Element& track) + { + if (track.type == ElementType::LAYER_ANIMATION) return track.layerId; + if (track.type == ElementType::NULL_ANIMATION) return track.nullId; + return -1; + } + + Element* track_find(Element& parent, ElementType trackType, int id) + { + for (auto& child : parent.children) + { + if (child.type == trackType && track_id_get(child) == id) return &child; + if (child.type == ElementType::GROUP) + if (auto found = track_find(child, trackType, id)) return found; + } + return nullptr; + } + + const Element* track_find(const Element& parent, ElementType trackType, int id) + { + for (const auto& child : parent.children) + { + if (child.type == trackType && track_id_get(child) == id) return &child; + if (child.type == ElementType::GROUP) + if (auto found = track_find(child, trackType, id)) return found; + } + return nullptr; + } + + Element* track_group_find(Element& parent, ElementType trackType, int id, int groupId) + { + for (auto& child : parent.children) + { + if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child; + if (child.type == ElementType::GROUP) + if (auto found = track_group_find(child, trackType, id, groupId)) return found; + } + return nullptr; + } + + const Element* track_group_find(const Element& parent, ElementType trackType, int id, int groupId) + { + for (const auto& child : parent.children) + { + if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child; + if (child.type == ElementType::GROUP) + if (auto found = track_group_find(child, trackType, id, groupId)) return found; + } + return nullptr; + } + + bool is_track_group_visible(const Element& container, const Element& track) + { + 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; + } + + Element* animation_item_get(Element& animation, ItemType type, int id, int groupType, int groupId) + { + auto trackType = item_type_to_track_type_get(type); + if (type == ItemType::ROOT && groupType != NONE && groupId != -1) + return animation_group_root_get(animation, groupType, groupId); + if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType); + + auto container = child_first_get(animation, item_type_to_container_type_get(type)); + if (!container) return nullptr; + return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId) + : track_find(*container, trackType, id); + } + + Element* animation_item_get(Element& animation, ItemType type, int id) + { + return animation_item_get(animation, type, id, NONE, -1); + } + + const Element* animation_item_get(const Element& animation, ItemType type, int id, int groupType, int groupId) + { + auto trackType = item_type_to_track_type_get(type); + if (type == ItemType::ROOT && groupType != NONE && groupId != -1) + return animation_group_root_get(animation, groupType, groupId); + if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType); + + auto container = child_first_get(animation, item_type_to_container_type_get(type)); + if (!container) return nullptr; + return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId) + : track_find(*container, trackType, id); + } + + const Element* animation_item_get(const Element& animation, ItemType type, int id) + { + return animation_item_get(animation, type, id, NONE, -1); + } + + 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) continue; + if (frameIndex == index) return i; + ++frameIndex; + } + return -1; + } + + int track_frames_count_get(const Element& track) + { + auto frameType = track_frame_type_get(track); + int count{}; + for (const auto& child : track.children) + if (child.type == frameType) ++count; + return count; + } + + int track_frame_insert_child_index_get(const Element& track, int index) + { + auto targetFrameIndex = std::max(0, index); + 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) continue; + if (frameIndex == targetFrameIndex) return i; + ++frameIndex; + } + return (int)track.children.size(); + } + + Element* track_frame_get(Element& track, int index) + { + auto childIndex = track_frame_child_index_get(track, index); + return childIndex == -1 ? nullptr : &track.children[childIndex]; + } + + const Element* track_frame_get(const Element& track, int index) + { + auto childIndex = track_frame_child_index_get(track, index); + return childIndex == -1 ? nullptr : &track.children[childIndex]; + } + + Element* Anm2::element_get(ElementType type) + { + if (type == ElementType::ANIMATED_ACTOR) return &root; + if (type == ElementType::ANIMATIONS) return element_first_get(root, type); + + auto content = child_first_get(root, ElementType::CONTENT); + if (!content) return nullptr; + if (type == ElementType::CONTENT) return content; + if (auto container = child_first_get(*content, type)) return container; + + switch (type) + { + case ElementType::SPRITESHEETS: + case ElementType::SHADERS: + case ElementType::LAYERS: + case ElementType::NULLS: + case ElementType::EVENTS: + case ElementType::SOUNDS: + content->children.push_back(element_make(type)); + return &content->children.back(); + default: + break; + } + + return element_first_get(root, type); + } + + const Element* Anm2::element_get(ElementType type) const + { + if (type == ElementType::ANIMATED_ACTOR) return &root; + if (type == ElementType::ANIMATIONS) return element_first_get(root, type); + + auto content = child_first_get(root, ElementType::CONTENT); + if (!content) return nullptr; + if (type == ElementType::CONTENT) return content; + if (auto container = child_first_get(*content, type)) return container; + return element_first_get(root, type); + } + + Element* Anm2::element_get(ElementType type, int id) + { + if (type == ElementType::ANIMATION) + { + auto animations = element_get(ElementType::ANIMATIONS); + if (!animations || id < 0) return nullptr; + int current{}; + for (auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (current == id) return &animation; + ++current; + } + return nullptr; + } + + auto container = element_get(element_container_type_get(type)); + return container ? child_id_get(*container, type, id) : nullptr; + } + + const Element* Anm2::element_get(ElementType type, int id) const + { + if (type == ElementType::ANIMATION) + { + auto animations = element_get(ElementType::ANIMATIONS); + if (!animations || id < 0) return nullptr; + int current{}; + for (const auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (current == id) return &animation; + ++current; + } + return nullptr; + } + + auto container = element_get(element_container_type_get(type)); + return container ? child_id_get(*container, type, id) : nullptr; + } + + Element* Anm2::element_get(int animationIndex, ItemType type, int id) + { + auto animation = element_get(ElementType::ANIMATION, animationIndex); + return animation ? animation_item_get(*animation, type, id) : nullptr; + } + + const Element* Anm2::element_get(int animationIndex, ItemType type, int id) const + { + auto animation = element_get(ElementType::ANIMATION, animationIndex); + return animation ? animation_item_get(*animation, type, id) : nullptr; + } + + Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId) + { + auto animation = element_get(ElementType::ANIMATION, animationIndex); + return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr; + } + + const Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId) const + { + auto animation = element_get(ElementType::ANIMATION, animationIndex); + return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr; + } + + Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id) + { + auto item = element_get(animationIndex, type, id); + return item ? track_frame_get(*item, frameIndex) : nullptr; + } + + const Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id) const + { + auto item = element_get(animationIndex, type, id); + return item ? track_frame_get(*item, frameIndex) : nullptr; + } + + Element* Anm2::element_get(Reference reference) + { + auto itemType = static_cast(reference.itemType); + auto item = + element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId); + if (reference.frameIndex < 0) return item; + return item ? track_frame_get(*item, reference.frameIndex) : nullptr; + } + + const Element* Anm2::element_get(Reference reference) const + { + auto itemType = static_cast(reference.itemType); + auto item = + element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId); + if (reference.frameIndex < 0) return item; + return item ? track_frame_get(*item, reference.frameIndex) : nullptr; + } + + std::set Anm2::element_unused(ElementType type) const + { + std::set used{}; + + if (type == ElementType::SPRITESHEET) + { + if (auto layers = element_get(ElementType::LAYERS)) + for (const auto& layer : layers->children) + if (layer.type == ElementType::LAYER_ELEMENT && layer.spritesheetId != -1) used.insert(layer.spritesheetId); + } + else if (auto animations = element_get(ElementType::ANIMATIONS)) + for (const auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (type == ElementType::EVENT_ELEMENT) + { + auto triggers = child_first_get(animation, ElementType::TRIGGERS); + if (!triggers) continue; + for (const auto& trigger : triggers->children) + if (trigger.type == ElementType::TRIGGER && trigger.eventId != -1) used.insert(trigger.eventId); + } + else if (type == ElementType::SOUND_ELEMENT) + { + auto triggers = child_first_get(animation, ElementType::TRIGGERS); + if (!triggers) continue; + for (const auto& trigger : triggers->children) + { + if (trigger.type != ElementType::TRIGGER) continue; + for (auto id : trigger.soundIds) + used.insert(id); + } + } + else if (type == ElementType::SHADER) + { + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](const Element& layerAnimation) + { + for (const auto& frame : layerAnimation.children) + if (frame.type == ElementType::FRAME && frame.shaderId != -1) used.insert(frame.shaderId); + }); + } + else if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) + { + auto containerType = + type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; + auto tracks = child_first_get(animation, containerType); + if (!tracks) continue; + auto trackType = + type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; + tracks_each(*tracks, trackType, + [&](const Element& track) + { + if (track.type == ElementType::LAYER_ANIMATION) + used.insert(track.layerId); + else if (track.type == ElementType::NULL_ANIMATION) + used.insert(track.nullId); + }); + } + } + + std::set unused{}; + if (auto container = element_get(element_container_type_get(type))) + for (const auto& element : container->children) + if (element.type == type && !used.contains(element.id)) unused.insert(element.id); + return unused; + } + + std::set Anm2::element_unused(ElementType type, const Element& animation) const + { + if (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT) return {}; + + std::set used{}; + auto containerType = + type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS; + if (auto tracks = child_first_get(animation, containerType)) + { + auto trackType = type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; + tracks_each(*tracks, trackType, + [&](const Element& track) + { + if (track.type == ElementType::LAYER_ANIMATION) + used.insert(track.layerId); + else if (track.type == ElementType::NULL_ANIMATION) + used.insert(track.nullId); + }); + } + + std::set unused{}; + if (auto container = element_get(element_container_type_get(type))) + for (const auto& element : container->children) + if (element.type == type && !used.contains(element.id)) unused.insert(element.id); + return unused; + } + + std::set Anm2::element_unused(ElementType type, int parentId) const + { + if (type != ElementType::REGION) return {}; + + std::set used{}; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (animations) + for (const auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](const Element& layerAnimation) + { + auto layer = element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); + if (!layer || layer->spritesheetId != parentId) return; + for (const auto& frame : layerAnimation.children) + { + if (frame.type != ElementType::FRAME) continue; + if (frame.regionId != -1) used.insert(frame.regionId); + } + }); + } + + std::set unused{}; + if (auto spritesheet = element_get(ElementType::SPRITESHEET, parentId)) + for (const auto& child : spritesheet->children) + if (child.type == type && !used.contains(child.id)) unused.insert(child.id); + return unused; + } +} diff --git a/src/anm2/frames.cpp b/src/anm2/frames.cpp new file mode 100644 index 0000000..6b48d64 --- /dev/null +++ b/src/anm2/frames.cpp @@ -0,0 +1,478 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ + enum class InterpolationBakeType + { + SPECIAL, + ALL + }; + + + Element frame_generate(const Element& track, float time) + { + auto frame = element_make(track_frame_type_get(track)); + frame.isVisible = false; + if (track.children.empty()) return frame; + + time = std::max(time, 0.0f); + + const Element* frameNext = nullptr; + int durationCurrent{}; + int durationNext{}; + auto frameType = track_frame_type_get(track); + + for (int i = 0; i < (int)track.children.size(); ++i) + { + const auto& iFrame = track.children[i]; + if (iFrame.type != frameType) continue; + + if (frameType == ElementType::TRIGGER) + { + if ((int)time == iFrame.atFrame) + { + frame = iFrame; + break; + } + continue; + } + + frame = iFrame; + durationNext += frame.duration; + + if (time >= durationCurrent && time < durationNext) + { + for (int next = i + 1; next < (int)track.children.size(); ++next) + if (track.children[next].type == ElementType::FRAME) + { + frameNext = &track.children[next]; + break; + } + break; + } + + durationCurrent += frame.duration; + } + + if (frameType != ElementType::TRIGGER && frame.interpolation != Interpolation::NONE && frameNext && + frame.duration > 1) + { + auto amount = + interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent)); + frame.rotation = glm::mix(frame.rotation, frameNext->rotation, amount); + frame.position = glm::mix(frame.position, frameNext->position, amount); + frame.scale = glm::mix(frame.scale, frameNext->scale, amount); + frame.shear = glm::mix(frame.shear, frameNext->shear, amount); + frame.colorOffset = glm::mix(frame.colorOffset, frameNext->colorOffset, amount); + frame.tint = glm::mix(frame.tint, frameNext->tint, amount); + } + + 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); + int frameCount{}; + for (const auto& frame : track.children) + if (frame.type == frameType) ++frameCount; + 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 frame = &track.children[childIndex]; + + auto original = *frame; + if (original.duration <= FRAME_DURATION_MIN) + { + frame->interpolation = Interpolation::NONE; + return; + } + + auto nextFrame = track_frame_get(track, index + 1); + auto next = nextFrame ? *nextFrame : original; + int duration{}; + interval = std::max(interval, FRAME_DURATION_MIN); + std::vector bakedFrames{}; + bakedFrames.reserve((original.duration + interval - 1) / interval); + + while (duration < original.duration) + { + auto baked = original; + auto amount = interpolation_factor(original.interpolation, (float)duration / original.duration); + baked.duration = std::min(interval, original.duration - duration); + baked.interpolation = Interpolation::NONE; + baked.rotation = glm::mix(original.rotation, next.rotation, amount); + baked.position = glm::mix(original.position, next.position, amount); + baked.scale = glm::mix(original.scale, next.scale, amount); + baked.shear = glm::mix(original.shear, next.shear, amount); + baked.colorOffset = glm::mix(original.colorOffset, next.colorOffset, amount); + baked.tint = glm::mix(original.tint, next.tint, amount); + if (isRoundScale) baked.scale = glm::round(baked.scale); + if (isRoundRotation) baked.rotation = std::round(baked.rotation); + + bakedFrames.push_back(baked); + duration += baked.duration; + } + + if (bakedFrames.empty()) return; + track.children[childIndex] = std::move(bakedFrames.front()); + track.children.insert(track.children.begin() + childIndex + 1, std::make_move_iterator(bakedFrames.begin() + 1), + std::make_move_iterator(bakedFrames.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 first = + frameType == ElementType::TRIGGER ? document.FirstChildElement("Trigger") : document.FirstChildElement("Frame"); + if (!first) + { + if (errorString) *errorString = frameType == ElementType::TRIGGER ? "No valid trigger(s)." : "No valid frame(s)."; + 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("Frame")) + { + 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("Trigger")) + { + 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) + { + const auto clamp_identity = [](auto value) { return value; }; + const auto clamp_duration = [](int value) { return std::max(FRAME_DURATION_MIN, value); }; + + if (selection.empty()) return; + + auto apply_scalar_with_clamp = [&](auto& target, const auto& optionalValue, auto clampFunc) + { + if (!optionalValue) return; + auto value = *optionalValue; + + switch (changeType) + { + case ChangeType::ADJUST: + target = clampFunc(value); + break; + case ChangeType::ADD: + target = clampFunc(target + value); + break; + case ChangeType::SUBTRACT: + target = clampFunc(target - value); + break; + case ChangeType::MULTIPLY: + target = clampFunc(target * value); + break; + case ChangeType::DIVIDE: + if (value == decltype(value){}) return; + target = clampFunc(target / value); + break; + } + }; + + auto apply_scalar = [&](auto& target, const auto& optionalValue) + { apply_scalar_with_clamp(target, optionalValue, clamp_identity); }; + + 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_scalar(frame->rotation, change.rotation); + apply_scalar_with_clamp(frame->duration, change.duration, clamp_duration); + + if (itemType == ItemType::LAYER) + { + apply_scalar(frame->crop.x, change.cropX); + apply_scalar(frame->crop.y, change.cropY); + apply_scalar(frame->pivot.x, change.pivotX); + apply_scalar(frame->pivot.y, change.pivotY); + apply_scalar(frame->size.x, change.sizeX); + apply_scalar(frame->size.y, change.sizeY); + if (change.regionId) frame->regionId = *change.regionId; + if (change.shaderId) frame->shaderId = *change.shaderId; + } + + apply_scalar(frame->position.x, change.positionX); + apply_scalar(frame->position.y, change.positionY); + apply_scalar(frame->scale.x, change.scaleX); + apply_scalar(frame->scale.y, change.scaleY); + apply_scalar(frame->shear.x, change.shearX); + apply_scalar(frame->shear.y, change.shearY); + apply_scalar(frame->colorOffset.x, change.colorOffsetR); + apply_scalar(frame->colorOffset.y, change.colorOffsetG); + apply_scalar(frame->colorOffset.z, change.colorOffsetB); + apply_scalar(frame->tint.x, change.tintR); + apply_scalar(frame->tint.y, change.tintG); + apply_scalar(frame->tint.z, change.tintB); + apply_scalar(frame->tint.w, change.tintA); + } + } + + 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; + return type == InterpolationBakeType::ALL || frame.interpolation != Interpolation::LINEAR; + } + + void track_frames_bake(Element& track, int interval, bool isRoundScale, bool isRoundRotation, + InterpolationBakeType type) + { + for (int index = (int)track.children.size() - 1; index >= 0; --index) + { + auto original = track.children[index]; + if (original.type != ElementType::FRAME) continue; + if (!is_frame_interpolation_baked(original, type)) continue; + + if (original.duration <= FRAME_DURATION_MIN) + { + track.children[index].interpolation = Interpolation::NONE; + continue; + } + + auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME + ? track.children[index + 1] + : original; + int duration{}; + int insertIndex = index; + + while (duration < original.duration) + { + auto baked = original; + float amount = interpolation_factor(original.interpolation, (float)duration / original.duration); + baked.duration = std::min(interval, original.duration - duration); + baked.interpolation = Interpolation::NONE; + baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); + baked.position = glm::mix(original.position, nextFrame.position, amount); + baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); + baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); + baked.tint = glm::mix(original.tint, nextFrame.tint, amount); + if (isRoundScale) baked.scale = glm::round(baked.scale); + if (isRoundRotation) baked.rotation = std::round(baked.rotation); + + if (insertIndex == index) + track.children[insertIndex] = baked; + else + track.children.insert(track.children.begin() + insertIndex, baked); + + duration += baked.duration; + ++insertIndex; + } + } + } + + void interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation, + InterpolationBakeType type) + { + if (is_track(element)) + { + track_frames_bake(element, interval, isRoundScale, isRoundRotation, type); + return; + } + + for (auto& child : element.children) + 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); + } + + void layer_animation_ids_remap(Element& element, const std::unordered_map& remap) + { + if (element.type == ElementType::LAYER_ANIMATION) + if (auto it = remap.find(element.layerId); it != remap.end()) element.layerId = it->second; + + for (auto& child : element.children) + layer_animation_ids_remap(child, remap); + } + + int track_length_get(const Element& track) + { + int length{}; + if (track.type == ElementType::TRIGGERS) + { + for (const auto& trigger : track.children) + if (trigger.type == ElementType::TRIGGER) length = std::max(length, trigger.atFrame); + return length; + } + + for (const auto& frame : track.children) + if (frame.type == ElementType::FRAME) length += frame.duration; + 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)); + if (auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS)) + { + group_roots_length_apply(*layerAnimations); + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](const Element& track) { length = std::max(length, track_length_get(track)); }); + } + if (auto nullAnimations = child_first_get(animation, ElementType::NULL_ANIMATIONS)) + { + group_roots_length_apply(*nullAnimations); + tracks_each(*nullAnimations, ElementType::NULL_ANIMATION, + [&](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/groups.cpp b/src/anm2/groups.cpp new file mode 100644 index 0000000..7b4672d --- /dev/null +++ b/src/anm2/groups.cpp @@ -0,0 +1,440 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ + constexpr std::string_view ANM2ED_GROUP_FRAME_BACKUP_TAG = "FrameRestore"; + + + bool is_frame_transform_default(const Element& frame) + { + auto base = element_make(ElementType::FRAME); + return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation && + frame.shear == base.shear && frame.tint == base.tint && frame.colorOffset == base.colorOffset; + } + + bool is_root_animation_transform_default(const Element& root) + { + for (const auto& frame : root.children) + if (frame.type == ElementType::FRAME && !is_frame_transform_default(frame)) return false; + return true; + } + + bool is_group_frame_backup(const Element& element) + { + return element.type == ElementType::UNKNOWN && element.tag == ANM2ED_GROUP_FRAME_BACKUP_TAG; + } + + void group_frame_backups_erase(Element& group) + { + std::erase_if(group.children, [](const Element& child) { return is_group_frame_backup(child); }); + } + + Element group_frame_backup_make(const Element& container, const Element& group, ElementType trackType) + { + Element backup{}; + backup.type = ElementType::UNKNOWN; + backup.tag = std::string(ANM2ED_GROUP_FRAME_BACKUP_TAG); + + if (auto root = child_first_get(group, ElementType::ROOT_ANIMATION)) backup.children.push_back(*root); + + for (const auto& item : container.children) + if (item.type == trackType && item.groupId == group.id) backup.children.push_back(item); + + return backup; + } + + void frame_group_root_apply(Element& frame, const Element& rootFrame) + { + auto rootScale = math::percent_to_unit(rootFrame.scale); + auto offset = frame.position * rootScale; + auto radians = glm::radians(rootFrame.rotation); + auto cos = std::cos(radians); + auto sin = std::sin(radians); + + frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); + frame.scale *= rootScale; + frame.rotation += rootFrame.rotation; + frame.tint *= rootFrame.tint; + frame.colorOffset += rootFrame.colorOffset; + } + + void track_group_root_bake(Element& track, const Element& root, int frameNum) + { + auto trackLength = track_length_get(track); + if (trackLength <= 0) return; + + auto length = std::max({trackLength, track_length_get(root), frameNum, FRAME_DURATION_MIN}); + std::vector frames{}; + frames.reserve(length); + + for (int time = 0; time < length; ++time) + { + auto frame = frame_generate(track, (float)time); + auto rootFrame = frame_generate(root, (float)time); + frame_group_root_apply(frame, rootFrame); + frame.duration = FRAME_DURATION_MIN; + frame.interpolation = Interpolation::NONE; + frames.push_back(std::move(frame)); + } + + track.children = std::move(frames); + } + + void group_frames_bake(Element& container, ElementType trackType, int frameNum) + { + for (auto& group : container.children) + { + if (group.type != ElementType::GROUP) continue; + group_frame_backups_erase(group); + auto root = child_first_get(group, ElementType::ROOT_ANIMATION); + if (!root || is_root_animation_transform_default(*root)) continue; + + auto backup = group_frame_backup_make(container, group, trackType); + for (auto& item : container.children) + if (item.type == trackType && item.groupId == group.id) track_group_root_bake(item, *root, frameNum); + + *root = root_animation_make(); + group.children.push_back(std::move(backup)); + } + } + + void group_frames_bake(Element& element) + { + if (element.type == ElementType::ANIMATION) + { + if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS)) + group_frames_bake(*layerAnimations, ElementType::LAYER_ANIMATION, element.frameNum); + if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS)) + group_frames_bake(*nullAnimations, ElementType::NULL_ANIMATION, element.frameNum); + } + + for (auto& child : element.children) + group_frames_bake(child); + } + + void group_frames_restore(Element& container, ElementType trackType) + { + std::set restoredGroupIds{}; + + for (auto& group : container.children) + { + if (group.type != ElementType::GROUP) continue; + if (group.id < 0) continue; + + const Element* backup{}; + for (const auto& child : group.children) + if (is_group_frame_backup(child)) + { + backup = &child; + break; + } + + if (!backup) continue; + + auto root = root_animation_make(); + if (auto currentRoot = child_first_get(group, ElementType::ROOT_ANIMATION)) root = *currentRoot; + + std::vector restoredTracks{}; + bool isRootRestored{}; + for (const auto& child : backup->children) + { + if (child.type == ElementType::ROOT_ANIMATION && !isRootRestored) + { + root = child; + isRootRestored = true; + } + else if (child.type == trackType) + { + auto track = child; + track.groupId = group.id; + restoredTracks.push_back(std::move(track)); + } + } + + if (!isRootRestored && restoredTracks.empty()) continue; + + group.children = {std::move(root)}; + group.children.insert(group.children.end(), std::make_move_iterator(restoredTracks.begin()), + std::make_move_iterator(restoredTracks.end())); + restoredGroupIds.insert(group.id); + } + + if (restoredGroupIds.empty()) return; + + std::erase_if(container.children, [&](const Element& item) + { return item.type == trackType && restoredGroupIds.contains(item.groupId); }); + } + + void group_frames_restore(Element& element) + { + if (element.type == ElementType::ANIMATION) + { + if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS)) + group_frames_restore(*layerAnimations, ElementType::LAYER_ANIMATION); + if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS)) + group_frames_restore(*nullAnimations, ElementType::NULL_ANIMATION); + } + + for (auto& child : element.children) + group_frames_restore(child); + } + + int child_index_get(const Element& element, ElementType type) + { + for (int i = 0; i < (int)element.children.size(); ++i) + if (element.children[i].type == type) return i; + return -1; + } + + ElementType track_container_track_type_get(ElementType containerType) + { + if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION; + if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION; + return ElementType::UNKNOWN; + } + + ElementType track_container_group_container_type_get(ElementType containerType) + { + if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION_GROUPS; + if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION_GROUPS; + return ElementType::UNKNOWN; + } + + int track_group_insert_index_get(const Element& container, ElementType trackType, int groupId) + { + for (int i = 0; i < (int)container.children.size(); ++i) + if (container.children[i].type == trackType && container.children[i].groupId == groupId) return i; + return (int)container.children.size(); + } + + void group_metadata_embed(Element& animation, ElementType trackContainerType) + { + auto groupContainerType = track_container_group_container_type_get(trackContainerType); + auto trackType = track_container_track_type_get(trackContainerType); + auto groupContainerIndex = child_index_get(animation, groupContainerType); + if (groupContainerIndex < 0 || trackType == ElementType::UNKNOWN) return; + + std::vector groups{}; + for (const auto& child : animation.children[groupContainerIndex].children) + if (child.type == ElementType::GROUP) groups.push_back(child); + + if (!groups.empty()) + { + auto trackContainerIndex = child_index_get(animation, trackContainerType); + if (trackContainerIndex < 0) + { + animation.children.push_back(element_make(trackContainerType)); + trackContainerIndex = (int)animation.children.size() - 1; + } + + auto& container = animation.children[trackContainerIndex]; + std::set groupIds{}; + for (const auto& group : groups) + if (group.id >= 0) groupIds.insert(group.id); + std::erase_if(container.children, [&](const Element& child) + { return child.type == ElementType::GROUP && groupIds.contains(child.id); }); + + std::stable_sort(groups.begin(), groups.end(), + [](const Element& left, const Element& right) + { + if (left.index == -1 || right.index == -1) return left.index != -1; + return left.index < right.index; + }); + + for (auto& group : groups) + { + auto insertIndex = group.index >= 0 ? std::min(group.index, (int)container.children.size()) + : track_group_insert_index_get(container, trackType, group.id); + group.index = -1; + container.children.insert(container.children.begin() + insertIndex, std::move(group)); + } + } + + std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; }); + } + + void group_metadata_embed(Element& element) + { + if (element.type == ElementType::ANIMATION) + { + group_metadata_embed(element, ElementType::LAYER_ANIMATIONS); + group_metadata_embed(element, ElementType::NULL_ANIMATIONS); + } + + for (auto& child : element.children) + group_metadata_embed(child); + } + + void group_metadata_extract(Element& animation, ElementType trackContainerType, Flags flags) + { + auto groupContainerType = track_container_group_container_type_get(trackContainerType); + if (groupContainerType == ElementType::UNKNOWN) return; + + std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; }); + if (!has_flag(flags, SERIALIZE_GROUPS)) return; + + auto trackContainerIndex = child_index_get(animation, trackContainerType); + if (trackContainerIndex < 0) return; + + auto& container = animation.children[trackContainerIndex]; + auto groupContainer = element_make(groupContainerType); + std::vector tracks{}; + tracks.reserve(container.children.size()); + + for (int i = 0; i < (int)container.children.size(); ++i) + { + auto child = container.children[i]; + if (child.type == ElementType::GROUP) + { + child.index = i; + groupContainer.children.push_back(std::move(child)); + } + else + tracks.push_back(std::move(child)); + } + + container.children = std::move(tracks); + if (groupContainer.children.empty()) return; + animation.children.insert(animation.children.begin() + trackContainerIndex + 1, std::move(groupContainer)); + } + + void group_metadata_extract(Element& element, Flags flags) + { + if (element.type == ElementType::ANIMATION) + { + group_metadata_extract(element, ElementType::LAYER_ANIMATIONS, flags); + group_metadata_extract(element, ElementType::NULL_ANIMATIONS, flags); + } + + for (auto& child : element.children) + group_metadata_extract(child, flags); + } + + void groups_flatten(Element& element) + { + auto container_flatten = [](Element& container, ElementType childType, bool isRootKept) + { + int nextGroupId{}; + for (const auto& item : container.children) + if (item.type == ElementType::GROUP) nextGroupId = std::max(nextGroupId, item.id + 1); + + std::vector flattened{}; + for (auto item : container.children) + { + if (item.type != ElementType::GROUP) + { + flattened.push_back(item); + continue; + } + + if (item.id < 0) item.id = nextGroupId++; + auto groupId = item.id; + auto children = std::move(item.children); + item.children.clear(); + + if (isRootKept) + { + bool isRootFound{}; + + for (auto child : children) + if (child.type == ElementType::ROOT_ANIMATION) + { + if (isRootFound) continue; + item.children.push_back(child); + isRootFound = true; + } + + if (!isRootFound) item.children.push_back(root_animation_make()); + } + + flattened.push_back(item); + + for (auto child : children) + { + if (child.type != childType) continue; + child.groupId = groupId; + flattened.push_back(child); + } + } + + std::set groupIds{}; + for (const auto& item : flattened) + if (item.type == ElementType::GROUP) groupIds.insert(item.id); + + for (auto& item : flattened) + if (item.type == childType && !groupIds.contains(item.groupId)) item.groupId = -1; + + container.children = std::move(flattened); + }; + + if (element.type == ElementType::ANIMATIONS) + container_flatten(element, ElementType::ANIMATION, false); + else if (element.type == ElementType::LAYER_ANIMATIONS) + container_flatten(element, ElementType::LAYER_ANIMATION, true); + else if (element.type == ElementType::NULL_ANIMATIONS) + container_flatten(element, ElementType::NULL_ANIMATION, true); + + for (auto& child : element.children) + groups_flatten(child); + } + + void group_children_nest(Element& container, ElementType childType) + { + if (childType == ElementType::UNKNOWN) return; + + std::set groupIds{}; + for (const auto& child : container.children) + if (child.type == ElementType::GROUP && child.id >= 0) groupIds.insert(child.id); + if (groupIds.empty()) return; + + std::unordered_map> groupedChildren{}; + for (const auto& child : container.children) + { + if (child.type != childType || !groupIds.contains(child.groupId)) continue; + auto groupedChild = child; + groupedChild.groupId = -1; + groupedChildren[child.groupId].push_back(std::move(groupedChild)); + } + + std::vector nested{}; + nested.reserve(container.children.size()); + for (auto child : container.children) + { + if (child.type == childType && groupIds.contains(child.groupId)) continue; + if (child.type == ElementType::GROUP) + { + auto groupId = child.id; + child.index = -1; + if (auto grouped = groupedChildren.find(groupId); grouped != groupedChildren.end()) + child.children.insert(child.children.end(), std::make_move_iterator(grouped->second.begin()), + std::make_move_iterator(grouped->second.end())); + } + nested.push_back(std::move(child)); + } + + container.children = std::move(nested); + } + + void groups_nest(Element& element) + { + if (element.type == ElementType::ANIMATIONS) + group_children_nest(element, ElementType::ANIMATION); + else if (element.type == ElementType::LAYER_ANIMATIONS) + group_children_nest(element, ElementType::LAYER_ANIMATION); + else if (element.type == ElementType::NULL_ANIMATIONS) + group_children_nest(element, ElementType::NULL_ANIMATION); + + for (auto& child : element.children) + groups_nest(child); + } + + void source_document_erase(Element& element) + { + std::erase_if(element.children, [](const Element& child) { return is_source_document_tag(child.tag); }); + for (auto& child : element.children) + source_document_erase(child); + } +} diff --git a/src/anm2/hash.cpp b/src/anm2/hash.cpp new file mode 100644 index 0000000..94c9035 --- /dev/null +++ b/src/anm2/hash.cpp @@ -0,0 +1,333 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ + constexpr std::uint64_t ANM2_HASH_OFFSET = 14695981039346656037ull; + constexpr std::uint64_t ANM2_HASH_PRIME = 1099511628211ull; + + struct BakeAttributes + { + Interpolation interpolation{Interpolation::NONE}; + int delay{FRAME_DURATION_MIN}; + }; + + void element_hash_append(std::uint64_t&, const Element&, ElementType, Flags, + std::optional = std::nullopt); + + + void hash_byte_append(std::uint64_t& hash, unsigned char value) + { + hash ^= value; + hash *= ANM2_HASH_PRIME; + } + + void hash_bytes_append(std::uint64_t& hash, const char* data, std::size_t size) + { + for (std::size_t i = 0; i < size; ++i) + hash_byte_append(hash, (unsigned char)data[i]); + } + + void hash_string_append(std::uint64_t& hash, std::string_view value) + { + auto size = (std::uint64_t)value.size(); + hash_bytes_append(hash, reinterpret_cast(&size), sizeof(size)); + hash_bytes_append(hash, value.data(), value.size()); + } + + void hash_attr_append(std::uint64_t& hash, std::string_view name, std::string_view value) + { + hash_byte_append(hash, 'A'); + hash_string_append(hash, name); + hash_string_append(hash, value); + } + + void hash_attr_append(std::uint64_t& hash, std::string_view name, int value) + { + char buffer[32]{}; + XMLUtil::ToStr(value, buffer, sizeof(buffer)); + hash_attr_append(hash, name, std::string_view(buffer)); + } + + void hash_attr_append(std::uint64_t& hash, std::string_view name, bool isValue) + { + char buffer[8]{}; + XMLUtil::ToStr(isValue, buffer, sizeof(buffer)); + hash_attr_append(hash, name, std::string_view(buffer)); + } + + void hash_attr_append(std::uint64_t& hash, std::string_view name, float value) + { + char buffer[64]{}; + XMLUtil::ToStr(value, buffer, sizeof(buffer)); + hash_attr_append(hash, name, std::string_view(buffer)); + } + + void hash_path_attr_append(std::uint64_t& hash, std::string_view name, const std::filesystem::path& pathValue) + { + if (pathValue.empty()) return; + auto value = path::to_utf8(pathValue); + hash_attr_append(hash, name, value); + } + + void hash_interpolation_attr_append(std::uint64_t& hash, Interpolation interpolation) + { + if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) + { + hash_attr_append(hash, "Interpolated", interpolation == Interpolation::LINEAR); + return; + } + + auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; + if (!value.empty()) hash_attr_append(hash, "Interpolated", value); + } + + void hash_origin_attr_append(std::uint64_t& hash, const Element& element) + { + auto origin = ORIGIN_VALUES[(std::size_t)element.origin]; + if (!origin.empty()) + { + hash_attr_append(hash, "Origin", origin); + return; + } + + hash_attr_append(hash, "XPivot", element.pivot.x); + hash_attr_append(hash, "YPivot", element.pivot.y); + } + + void frame_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags) + { + if (parentType == ElementType::LAYER_ANIMATION) + { + bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1; + bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion; + + if (isHasValidRegion) hash_attr_append(hash, "RegionId", element.regionId); + if (isWriteRegionValues) + { + hash_attr_append(hash, "XPivot", element.pivot.x); + hash_attr_append(hash, "YPivot", element.pivot.y); + hash_attr_append(hash, "XCrop", element.crop.x); + hash_attr_append(hash, "YCrop", element.crop.y); + hash_attr_append(hash, "Width", element.size.x); + hash_attr_append(hash, "Height", element.size.y); + } + } + + hash_attr_append(hash, "XPosition", element.position.x); + hash_attr_append(hash, "YPosition", element.position.y); + hash_attr_append(hash, "Delay", element.duration); + hash_attr_append(hash, "Visible", element.isVisible); + hash_attr_append(hash, "XScale", element.scale.x); + hash_attr_append(hash, "YScale", element.scale.y); + if (has_flag(flags, SERIALIZE_EXTENSIONS)) + { + hash_attr_append(hash, "ShearX", element.shear.x); + hash_attr_append(hash, "ShearY", element.shear.y); + } + hash_attr_append(hash, "RedTint", color_write(element.tint.r)); + hash_attr_append(hash, "GreenTint", color_write(element.tint.g)); + hash_attr_append(hash, "BlueTint", color_write(element.tint.b)); + hash_attr_append(hash, "AlphaTint", color_write(element.tint.a)); + hash_attr_append(hash, "RedOffset", color_write(element.colorOffset.r)); + hash_attr_append(hash, "GreenOffset", color_write(element.colorOffset.g)); + hash_attr_append(hash, "BlueOffset", color_write(element.colorOffset.b)); + hash_attr_append(hash, "Rotation", element.rotation); + hash_interpolation_attr_append(hash, element.interpolation); + if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) + hash_attr_append(hash, "ShaderId", element.shaderId); + } + + void bake_attributes_hash_append(std::uint64_t& hash, Interpolation interpolation, int bakeDelay) + { + auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; + if (!value.empty()) hash_attr_append(hash, "BakeInterpolation", value); + hash_attr_append(hash, "BakeDelay", bakeDelay); + } + + void element_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags) + { + if (element.type == ElementType::INFO) + { + hash_attr_append(hash, "CreatedBy", element.createdBy); + hash_attr_append(hash, "CreatedOn", element.createdOn); + hash_attr_append(hash, "Fps", element.fps); + hash_attr_append(hash, "Version", element.version); + } + else if (element.type == ElementType::ANIMATIONS) + hash_attr_append(hash, "DefaultAnimation", element.defaultAnimation); + else if (element.type == ElementType::SPRITESHEET) + { + hash_attr_append(hash, "Id", element.id); + hash_path_attr_append(hash, "Path", element.path); + } + else if (element.type == ElementType::SHADER) + { + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + hash_path_attr_append(hash, "Vertex", element.vertex); + hash_path_attr_append(hash, "Fragment", element.fragment); + } + else if (element.type == ElementType::UNIFORM) + { + hash_attr_append(hash, "Name", element.name); + if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding); + if (!element.value.empty()) hash_attr_append(hash, "Value", element.value); + } + else if (element.type == ElementType::COMPONENT) + { + hash_attr_append(hash, "Index", element.index); + if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding); + if (!element.value.empty()) hash_attr_append(hash, "Value", element.value); + } + else if (element.type == ElementType::REGION) + { + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + hash_attr_append(hash, "XCrop", element.crop.x); + hash_attr_append(hash, "YCrop", element.crop.y); + hash_attr_append(hash, "Width", element.size.x); + hash_attr_append(hash, "Height", element.size.y); + hash_origin_attr_append(hash, element); + } + else if (element.type == ElementType::LAYER_ELEMENT) + { + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + hash_attr_append(hash, "SpritesheetId", element.spritesheetId); + } + else if (element.type == ElementType::NULL_ELEMENT) + { + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + if (element.isShowRect) hash_attr_append(hash, "ShowRect", element.isShowRect); + } + else if (element.type == ElementType::GROUP) + { + if (!is_nested_group_parent(parentType, flags)) hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + hash_attr_append(hash, "IsExpanded", element.isExpanded); + hash_attr_append(hash, "Visible", element.isVisible); + if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) && + element.index != -1) + hash_attr_append(hash, "Index", element.index); + } + else if (element.type == ElementType::EVENT_ELEMENT) + { + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); + } + else if (element.type == ElementType::SOUND_ELEMENT) + { + hash_attr_append(hash, "Id", element.id); + if (parentType != ElementType::TRIGGER) hash_path_attr_append(hash, "Path", element.path); + } + else if (element.type == ElementType::ANIMATION) + { + hash_attr_append(hash, "Name", element.name); + hash_attr_append(hash, "FrameNum", element.frameNum); + hash_attr_append(hash, "Loop", element.isLoop); + if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); + } + else if (element.type == ElementType::LAYER_ANIMATION) + { + hash_attr_append(hash, "LayerId", element.layerId); + hash_attr_append(hash, "Visible", element.isVisible); + if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); + } + else if (element.type == ElementType::NULL_ANIMATION) + { + hash_attr_append(hash, "NullId", element.nullId); + hash_attr_append(hash, "Visible", element.isVisible); + if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId); + } + else if (element.type == ElementType::FRAME) + frame_attributes_hash_append(hash, element, parentType, flags); + else if (element.type == ElementType::TRIGGER) + { + if (element.eventId != -1) hash_attr_append(hash, "EventId", element.eventId); + hash_attr_append(hash, "AtFrame", element.atFrame); + } + } + + void trigger_sounds_hash_append(std::uint64_t& hash, const Element& element, Flags flags) + { + if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return; + + for (auto soundId : element.soundIds) + { + if (soundId == -1) continue; + auto sound = element_make(ElementType::SOUND_ELEMENT); + sound.id = soundId; + element_hash_append(hash, sound, ElementType::TRIGGER, flags); + } + } + + void baked_frames_hash_append(std::uint64_t& hash, const Element& track, int index, Flags flags) + { + const auto& original = track.children[index]; + auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME + ? track.children[index + 1] + : original; + auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN); + + for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex) + { + auto baked = original; + auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay); + baked.duration = FRAME_DURATION_MIN; + baked.interpolation = Interpolation::NONE; + baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); + baked.position = glm::mix(original.position, nextFrame.position, amount); + baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); + baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); + baked.tint = glm::mix(original.tint, nextFrame.tint, amount); + element_hash_append(hash, baked, track.type, flags, + bakeIndex == 0 ? std::optional({original.interpolation, bakeDelay}) + : std::nullopt); + } + } + + void element_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags, + std::optional bakeAttributes) + { + auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type); + hash_byte_append(hash, 'E'); + hash_string_append(hash, tag.empty() ? std::string_view(element.tag) : tag); + + element_attributes_hash_append(hash, element, parentType, flags); + if (bakeAttributes) bake_attributes_hash_append(hash, bakeAttributes->interpolation, bakeAttributes->delay); + + hash_byte_append(hash, '['); + trigger_sounds_hash_append(hash, element, flags); + for (int i = 0; i < (int)element.children.size(); ++i) + { + const auto& child = element.children[i]; + if (element_write_skip(child, element.type, flags)) continue; + + if (is_track(element) && is_frame_bake_serialized(child, flags)) + baked_frames_hash_append(hash, element, i, flags); + else + element_hash_append(hash, child, element.type, flags); + } + hash_byte_append(hash, ']'); + } + + std::uint64_t element_hash(const Element& element, Flags flags) + { + auto hash = ANM2_HASH_OFFSET; + element_hash_append(hash, element, ElementType::UNKNOWN, flags); + return hash; + } + + std::uint64_t anm2_hash_get(const Element& root, Options options) + { + auto hash = ANM2_HASH_OFFSET; + hash_byte_append(hash, options.isExtendedFormat ? 'E' : 'A'); + element_hash_append(hash, root, ElementType::UNKNOWN, SERIALIZE_ANM2ED_DEFAULT); + return hash; + } +} diff --git a/src/anm2/internal.hpp b/src/anm2/internal.hpp new file mode 100644 index 0000000..8db765c --- /dev/null +++ b/src/anm2/internal.hpp @@ -0,0 +1,106 @@ +#pragma once + +#include "anm2.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "file.hpp" +#include "math.hpp" +#include "path.hpp" +#include "time.hpp" +#include "working_directory.hpp" +#include "xml.hpp" + +namespace anm2ed +{ + inline constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; + inline constexpr std::array INTERPOLATION_VALUES = { + "", "", "EaseIn", "EaseOut", "EaseInOut"}; + inline constexpr std::array ORIGIN_VALUES = {"", "TopLeft", "Center"}; + inline constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; + + bool is_source_document_tag(std::string_view); + ElementType element_type_get(std::string_view); + std::string_view element_tag_get(ElementType); + ElementType element_container_type_get(ElementType); + 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(); + void group_frames_bake(Element&); + void group_frames_restore(Element&); + void group_metadata_embed(Element&); + void group_metadata_extract(Element&, Flags); + void groups_flatten(Element&); + void groups_nest(Element&); + void source_document_erase(Element&); + void shader_ids_repair(Element&); + void shader_frame_ids_repair(Element&); + void shader_ids_remap(Element&); + void region_ids_remap(Element&); + void region_frame_ids_repair(Element&); + void layer_animation_ids_remap(Element&, const std::unordered_map&); + Element* child_first_get(Element&, ElementType); + const Element* child_first_get(const Element&, ElementType); + Element* child_id_get(Element&, ElementType, int); + const Element* child_id_get(const Element&, ElementType, int); + bool is_track(const 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&); + void special_interpolated_frames_bake(Element&, int, bool, bool); + void all_interpolated_frames_bake(Element&, int, bool, bool); + float interpolation_factor(Interpolation, float); + int color_write(float); + std::uint64_t anm2_hash_get(const Element&, Options); + std::uint64_t element_hash(const Element&, Flags); + ElementType track_frame_type_get(const Element&); + ElementType item_type_to_container_type_get(ItemType); + int track_id_get(const Element&); + int track_frame_child_index_get(const Element&, int); + int track_frames_count_get(const Element&); + int track_frame_insert_child_index_get(const Element&, int); + Element* track_find(Element&, ElementType, int); + const Element* track_find(const Element&, ElementType, int); + Element* track_group_find(Element&, ElementType, int, int); + const Element* track_group_find(const Element&, ElementType, int, int); + Element* animation_container_get(Element&, ElementType); + + template void tracks_each(Element& parent, ElementType trackType, Callback&& callback) + { + for (auto& child : parent.children) + if (child.type == trackType) + callback(child); + else if (child.type == ElementType::GROUP) + tracks_each(child, trackType, callback); + } + + template void tracks_each(const Element& parent, ElementType trackType, Callback&& callback) + { + for (const auto& child : parent.children) + if (child.type == trackType) + callback(child); + else if (child.type == ElementType::GROUP) + tracks_each(child, trackType, callback); + } +} diff --git a/src/anm2/merge.cpp b/src/anm2/merge.cpp new file mode 100644 index 0000000..676fa34 --- /dev/null +++ b/src/anm2/merge.cpp @@ -0,0 +1,213 @@ +#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_first_get(destination, containerType); + if (!destinationTracks) + { + destination.children.push_back(element_make(containerType)); + destinationTracks = &destination.children.back(); + } + + 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)) + { + auto destinationRoot = child_first_get(*destinationGroup, ElementType::ROOT_ANIMATION); + if (!destinationRoot) + { + destinationGroup->children.push_back(root_animation_make()); + destinationRoot = &destinationGroup->children.back(); + } + track_merge(*destinationRoot, *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_group_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; + + if (auto sourceRoot = child_first_get(*source, ElementType::ROOT_ANIMATION)) + { + auto targetRoot = child_first_get(*targetAnimation, ElementType::ROOT_ANIMATION); + if (!targetRoot) + { + targetAnimation->children.push_back(element_make(ElementType::ROOT_ANIMATION)); + targetRoot = &targetAnimation->children.back(); + } + track_merge(*targetRoot, *sourceRoot, type); + } + + animation_tracks_merge(*targetAnimation, *source, ElementType::LAYER_ANIMATIONS, type); + animation_tracks_merge(*targetAnimation, *source, ElementType::NULL_ANIMATIONS, type); + + if (auto sourceTriggers = child_first_get(*source, ElementType::TRIGGERS)) + { + auto targetTriggers = child_first_get(*targetAnimation, ElementType::TRIGGERS); + if (!targetTriggers) + { + targetAnimation->children.push_back(element_make(ElementType::TRIGGERS)); + targetTriggers = &targetAnimation->children.back(); + } + track_merge(*targetTriggers, *sourceTriggers, type); + } + } + + 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; + } +} diff --git a/src/anm2/normalize.cpp b/src/anm2/normalize.cpp new file mode 100644 index 0000000..f7f37cd --- /dev/null +++ b/src/anm2/normalize.cpp @@ -0,0 +1,260 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ + void shader_ids_repair(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + if (!shaders) return; + + std::set usedIds{}; + int nextId{}; + for (auto& shader : shaders->children) + { + if (shader.type != ElementType::SHADER) continue; + + while (usedIds.contains(nextId)) + ++nextId; + if (shader.id < 0 || usedIds.contains(shader.id)) shader.id = nextId++; + usedIds.insert(shader.id); + if (shader.name.empty()) shader.name = "New Shader"; + } + } + + void shader_frame_ids_repair(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (!animations) return; + + std::set shaderIds{}; + if (shaders) + for (const auto& shader : shaders->children) + if (shader.type == ElementType::SHADER) shaderIds.insert(shader.id); + + auto frame_repair = [&](auto&& self, Element& element) -> void + { + if (element.type == ElementType::FRAME && element.shaderId != -1 && !shaderIds.contains(element.shaderId)) + element.shaderId = -1; + for (auto& child : element.children) + self(self, child); + }; + frame_repair(frame_repair, *animations); + } + + void region_frame_ids_repair(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; + auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (!layers || !spritesheets || !animations) return; + + for (auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](Element& layerAnimation) + { + auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId); + auto spritesheet = + layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (!spritesheet) return; + + for (auto& frame : layerAnimation.children) + { + if (frame.type != ElementType::FRAME) continue; + + auto frameCrop = glm::ivec2(frame.crop); + auto frameSize = glm::ivec2(frame.size); + auto framePivot = glm::ivec2(frame.pivot); + auto is_region_match = [&](const Element& region) + { + return region.type == ElementType::REGION && glm::ivec2(region.crop) == frameCrop && + glm::ivec2(region.size) == frameSize && glm::ivec2(region.pivot) == framePivot; + }; + + auto region = frame.regionId == -1 + ? nullptr + : child_id_get(*spritesheet, ElementType::REGION, frame.regionId); + if (region && is_region_match(*region)) continue; + + for (const auto& candidate : spritesheet->children) + if (is_region_match(candidate)) + { + frame.regionId = candidate.id; + break; + } + } + }); + } + } + + void region_ids_remap(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; + auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (!spritesheets) return; + + std::unordered_map> remaps{}; + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + + std::unordered_map remap{}; + int nextId{}; + for (auto& region : spritesheet.children) + { + if (region.type != ElementType::REGION) continue; + remap[region.id] = nextId; + region.id = nextId++; + } + if (!remap.empty()) remaps[spritesheet.id] = std::move(remap); + } + + if (!layers || !animations || remaps.empty()) return; + + std::unordered_map layerSpritesheets{}; + for (const auto& layer : layers->children) + if (layer.type == ElementType::LAYER_ELEMENT) layerSpritesheets[layer.id] = layer.spritesheetId; + + for (auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](Element& layerAnimation) + { + auto layer = layerSpritesheets.find(layerAnimation.layerId); + if (layer == layerSpritesheets.end()) return; + auto remap = remaps.find(layer->second); + if (remap == remaps.end()) return; + + for (auto& frame : layerAnimation.children) + { + if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; + if (auto it = remap->second.find(frame.regionId); it != remap->second.end()) + frame.regionId = it->second; + else + frame.regionId = -1; + } + }); + } + } + + void shader_ids_remap(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + + std::unordered_map remap{}; + int nextId{}; + if (shaders) + for (auto& shader : shaders->children) + { + if (shader.type != ElementType::SHADER) continue; + remap[shader.id] = nextId; + shader.id = nextId++; + } + + auto frame_remap = [&](auto&& self, Element& element) -> void + { + if (element.type == ElementType::FRAME && element.shaderId != -1) + { + if (auto it = remap.find(element.shaderId); it != remap.end()) + element.shaderId = it->second; + else + element.shaderId = -1; + } + for (auto& child : element.children) + self(self, child); + }; + frame_remap(frame_remap, root); + } + + void Anm2::region_frames_sync(bool isClearInvalid) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; + auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (!layers || !spritesheets || !animations) return; + + for (auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](Element& layerAnimation) + { + auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId); + auto spritesheet = + layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (!spritesheet) return; + + for (auto& frame : layerAnimation.children) + { + if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; + auto region = child_id_get(*spritesheet, ElementType::REGION, frame.regionId); + if (!region) + { + if (isClearInvalid) frame.regionId = -1; + continue; + } + + frame.crop = region->crop; + frame.size = region->size; + frame.pivot = region->pivot; + } + }); + } + } + + Anm2 Anm2::normalized_for_serialize(Flags flags) const + { + auto normalized = *this; + source_document_erase(normalized.root); + group_frames_restore(normalized.root); + groups_flatten(normalized.root); + if (has_flag(flags, SERIALIZE_BAKE_GROUP_FRAMES)) group_frames_bake(normalized.root); + if (has_flag(flags, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)) + all_interpolated_frames_bake(normalized.root, FRAME_DURATION_MIN, false, false); + region_ids_remap(normalized.root); + shader_ids_remap(normalized.root); + if (has_flag(flags, SERIALIZE_GROUPS) && has_flag(flags, SERIALIZE_NESTED_GROUPS)) + groups_nest(normalized.root); + else + group_metadata_extract(normalized.root, flags); + + auto content = child_first_get(normalized.root, ElementType::CONTENT); + if (content) std::erase_if(content->children, [](const Element& element) { return element.tag == "Groups"; }); + if (auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr) + { + std::unordered_map remap{}; + int nextId{}; + for (auto& layer : layers->children) + { + if (layer.type != ElementType::LAYER_ELEMENT) continue; + remap[layer.id] = nextId; + layer.id = nextId++; + } + layer_animation_ids_remap(normalized.root, remap); + } + + return normalized; + } +} diff --git a/src/anm2/xml.cpp b/src/anm2/xml.cpp new file mode 100644 index 0000000..220c124 --- /dev/null +++ b/src/anm2/xml.cpp @@ -0,0 +1,618 @@ +#include "internal.hpp" + +using namespace anm2ed::util; +using namespace tinyxml2; + +namespace anm2ed +{ +#define ANM2_STRING_ATTRIBUTES \ + X("Name", name) \ + X("CreatedBy", createdBy) \ + X("CreatedOn", createdOn) \ + X("Binding", binding) \ + X("Value", value) \ + X("DefaultAnimation", defaultAnimation) + +#define ANM2_PATH_ATTRIBUTES \ + X("Path", path) \ + X("Vertex", vertex) \ + X("Fragment", fragment) + +#define ANM2_INT_ATTRIBUTES \ + X("Id", id) \ + X("LayerId", layerId) \ + X("NullId", nullId) \ + X("SpritesheetId", spritesheetId) \ + X("Fps", fps) \ + X("Version", version) \ + X("FrameNum", frameNum) \ + X("Delay", duration) \ + X("AtFrame", atFrame) \ + X("EventId", eventId) \ + X("RegionId", regionId) \ + X("ShaderId", shaderId) \ + X("SoundId", soundId) \ + X("GroupId", groupId) \ + X("Index", index) + +#define ANM2_BOOL_ATTRIBUTES \ + X("Loop", isLoop) \ + X("Visible", isVisible) \ + X("ShowRect", isShowRect) \ + X("IsExpanded", isExpanded) \ + X("Enabled", isEnabled) + +#define ANM2_FLOAT_ATTRIBUTES \ + X("Rotation", rotation) \ + X("XPivot", pivot.x) \ + X("YPivot", pivot.y) \ + X("XCrop", crop.x) \ + X("YCrop", crop.y) \ + X("XPosition", position.x) \ + X("YPosition", position.y) \ + X("Width", size.x) \ + X("Height", size.y) \ + X("XScale", scale.x) \ + X("YScale", scale.y) \ + X("ShearX", shear.x) \ + X("ShearY", shear.y) + +#define ANM2_COLOR_ATTRIBUTES \ + X("RedTint", tint.r) \ + X("GreenTint", tint.g) \ + X("BlueTint", tint.b) \ + X("AlphaTint", tint.a) \ + X("RedOffset", colorOffset.r) \ + X("GreenOffset", colorOffset.g) \ + X("BlueOffset", colorOffset.b) + + constexpr std::string_view LEGACY_OVERLAY_TAG = "Overlay"; + + + bool string_query(const XMLElement* element, const char* name, std::string& out) + { + if (!element) return false; + if (auto value = element->Attribute(name); value) + { + out = value; + return true; + } + return false; + } + + bool path_query(const XMLElement* element, const char* name, std::filesystem::path& out) + { + std::string value{}; + if (!string_query(element, name, value)) return false; + out = path::from_utf8(value); + return true; + } + + void path_set(XMLElement* element, const char* name, const std::filesystem::path& value) + { + if (!element || value.empty()) return; + auto valueUtf8 = path::to_utf8(value); + element->SetAttribute(name, valueUtf8.c_str()); + } + + float color_read(const XMLElement* element, const char* name, float fallback) + { + int value{}; + if (!element || element->QueryIntAttribute(name, &value) != XML_SUCCESS) return fallback; + return math::uint8_to_float(value); + } + + int color_write(float value) { return math::float_to_uint8(value); } + + Interpolation interpolation_read(const XMLElement* element, const char* attribute) + { + bool isFallback{}; + if (element) element->QueryBoolAttribute(attribute, &isFallback); + + auto value = element ? element->Attribute(attribute) : nullptr; + if (!value) return Interpolation::NONE; + + for (std::size_t i = 0; i < INTERPOLATION_VALUES.size(); ++i) + if (!INTERPOLATION_VALUES[i].empty() && INTERPOLATION_VALUES[i] == value) return (Interpolation)i; + + return isFallback ? Interpolation::LINEAR : Interpolation::NONE; + } + + Interpolation interpolation_read(const XMLElement* element) { return interpolation_read(element, "Interpolated"); } + + void interpolation_write(XMLElement* element, Interpolation interpolation) + { + if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) + { + element->SetAttribute("Interpolated", interpolation == Interpolation::LINEAR); + return; + } + + auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; + if (!value.empty()) element->SetAttribute("Interpolated", value.data()); + } + + Origin origin_read(const XMLElement* element) + { + auto value = element ? element->Attribute("Origin") : nullptr; + if (!value) return Origin::CUSTOM; + + for (std::size_t i = 0; i < ORIGIN_VALUES.size(); ++i) + if (!ORIGIN_VALUES[i].empty() && ORIGIN_VALUES[i] == value) return (Origin)i; + + return Origin::CUSTOM; + } + + void origin_write(XMLElement* out, const Element& element) + { + auto origin = ORIGIN_VALUES[(std::size_t)element.origin]; + if (!origin.empty()) + { + out->SetAttribute("Origin", origin.data()); + return; + } + + out->SetAttribute("XPivot", element.pivot.x); + out->SetAttribute("YPivot", element.pivot.y); + } + + void element_attributes_read(Element& out, const XMLElement* element) + { +#define X(attribute, member) string_query(element, attribute, out.member); + ANM2_STRING_ATTRIBUTES +#undef X +#define X(attribute, member) path_query(element, attribute, out.member); + ANM2_PATH_ATTRIBUTES +#undef X +#define X(attribute, member) element->QueryIntAttribute(attribute, &out.member); + ANM2_INT_ATTRIBUTES +#undef X +#define X(attribute, member) element->QueryBoolAttribute(attribute, &out.member); + ANM2_BOOL_ATTRIBUTES +#undef X +#define X(attribute, member) element->QueryFloatAttribute(attribute, &out.member); + ANM2_FLOAT_ATTRIBUTES +#undef X +#define X(attribute, member) out.member = color_read(element, attribute, out.member); + ANM2_COLOR_ATTRIBUTES +#undef X + + out.interpolation = interpolation_read(element); + out.origin = origin_read(element); + if (out.type == ElementType::REGION && out.origin == Origin::TOP_LEFT) out.pivot = {}; + if (out.type == ElementType::REGION && out.origin == Origin::CENTER) out.pivot = out.size * 0.5f; + } + + bool bake_attributes_read(const XMLElement* element, Interpolation& interpolation, int& bakeDelay) + { + if (!element || !element->Attribute("BakeInterpolation")) return false; + + interpolation = interpolation_read(element, "BakeInterpolation"); + element->QueryIntAttribute("BakeDelay", &bakeDelay); + return bakeDelay >= FRAME_DURATION_MIN; + } + + const XMLElement* bake_frames_skip(const XMLElement* element, int bakeDelay) + { + for (int i = 0; element && i < bakeDelay; ++i) + element = element->NextSiblingElement(); + return element; + } + + void element_children_read(Element& out, const XMLElement* element) + { + auto child = element->FirstChildElement(); + while (child) + { + auto childName = std::string_view(child->Name() ? child->Name() : ""); + if (childName == LEGACY_OVERLAY_TAG) + { + child = child->NextSiblingElement(); + continue; + } + + auto childType = element_type_get(childName); + if (childType == ElementType::FRAME && is_track(out)) + { + Interpolation bakeInterpolation{}; + int bakeDelay{}; + if (bake_attributes_read(child, bakeInterpolation, bakeDelay)) + { + auto restored = element_read(child); + restored.interpolation = bakeInterpolation; + restored.duration = bakeDelay; + if (is_track_child_valid(out.type, restored.type)) out.children.push_back(std::move(restored)); + child = bake_frames_skip(child, bakeDelay); + continue; + } + } + + auto childElement = element_read(child); + if (is_track_child_valid(out.type, childElement.type)) out.children.push_back(std::move(childElement)); + child = child->NextSiblingElement(); + } + } + + Element element_read(const XMLElement* element) + { + Element out{}; + if (!element) return out; + + out.tag = element->Name() ? element->Name() : ""; + out.type = element_type_get(out.tag); + element_attributes_read(out, element); + + element_children_read(out, element); + + if (out.type == ElementType::TRIGGER && out.soundId != -1) + { + bool isSoundFound{}; + for (const auto& child : out.children) + if (child.type == ElementType::SOUND_ELEMENT && child.id == out.soundId) isSoundFound = true; + + if (!isSoundFound) + { + auto sound = element_make(ElementType::SOUND_ELEMENT); + sound.id = out.soundId; + out.children.insert(out.children.begin(), sound); + } + } + + if (out.type == ElementType::TRIGGER) + for (const auto& child : out.children) + if (child.type == ElementType::SOUND_ELEMENT && child.id != -1) out.soundIds.push_back(child.id); + + return out; + } + + bool is_nested_group_parent(ElementType parentType, Flags flags) + { + return has_flag(flags, SERIALIZE_NESTED_GROUPS) && + (parentType == ElementType::ANIMATIONS || parentType == ElementType::LAYER_ANIMATIONS || + parentType == ElementType::NULL_ANIMATIONS); + } + + bool is_group_id_serialized(Flags flags) + { + return has_flag(flags, SERIALIZE_GROUPS) && !has_flag(flags, SERIALIZE_NESTED_GROUPS); + } + + bool element_write_skip(const Element& element, ElementType parentType, Flags flags) + { + if (!is_track_child_valid(parentType, element.type)) return true; + if ((element.type == ElementType::SHADERS || element.type == ElementType::SHADER || + element.type == ElementType::UNIFORM || element.type == ElementType::COMPONENT) && + !has_flag(flags, SERIALIZE_EXTENSIONS)) + return true; + if (element.type == ElementType::SHADERS && element.children.empty()) return true; + if (element.type == ElementType::SOUNDS && (!has_flag(flags, SERIALIZE_SOUNDS) || element.children.empty())) + return true; + if ((element.type == ElementType::LAYER_ANIMATION_GROUPS || element.type == ElementType::NULL_ANIMATION_GROUPS) && + (!has_flag(flags, SERIALIZE_GROUPS) || element.children.empty())) + return true; + if (element.type == ElementType::SOUND_ELEMENT && parentType == ElementType::TRIGGER) return true; + if (element.type == ElementType::REGION && !has_flag(flags, SERIALIZE_REGIONS)) return true; + if (element.type == ElementType::GROUP && !has_flag(flags, SERIALIZE_GROUPS)) return true; + return false; + } + + void frame_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags) + { + if (parentType == ElementType::LAYER_ANIMATION) + { + bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1; + bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion; + + if (isHasValidRegion) out->SetAttribute("RegionId", element.regionId); + if (isWriteRegionValues) + { + out->SetAttribute("XPivot", element.pivot.x); + out->SetAttribute("YPivot", element.pivot.y); + out->SetAttribute("XCrop", element.crop.x); + out->SetAttribute("YCrop", element.crop.y); + out->SetAttribute("Width", element.size.x); + out->SetAttribute("Height", element.size.y); + } + } + + out->SetAttribute("XPosition", element.position.x); + out->SetAttribute("YPosition", element.position.y); + out->SetAttribute("Delay", element.duration); + out->SetAttribute("Visible", element.isVisible); + out->SetAttribute("XScale", element.scale.x); + out->SetAttribute("YScale", element.scale.y); + if (has_flag(flags, SERIALIZE_EXTENSIONS)) + { + out->SetAttribute("ShearX", element.shear.x); + out->SetAttribute("ShearY", element.shear.y); + } + out->SetAttribute("RedTint", color_write(element.tint.r)); + out->SetAttribute("GreenTint", color_write(element.tint.g)); + out->SetAttribute("BlueTint", color_write(element.tint.b)); + out->SetAttribute("AlphaTint", color_write(element.tint.a)); + out->SetAttribute("RedOffset", color_write(element.colorOffset.r)); + out->SetAttribute("GreenOffset", color_write(element.colorOffset.g)); + out->SetAttribute("BlueOffset", color_write(element.colorOffset.b)); + out->SetAttribute("Rotation", element.rotation); + interpolation_write(out, element.interpolation); + if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) + out->SetAttribute("ShaderId", element.shaderId); + } + + void element_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags) + { + if (element.type == ElementType::INFO) + { + out->SetAttribute("CreatedBy", element.createdBy.c_str()); + out->SetAttribute("CreatedOn", element.createdOn.c_str()); + out->SetAttribute("Fps", element.fps); + out->SetAttribute("Version", element.version); + } + else if (element.type == ElementType::ANIMATIONS) + out->SetAttribute("DefaultAnimation", element.defaultAnimation.c_str()); + else if (element.type == ElementType::SPRITESHEET) + { + out->SetAttribute("Id", element.id); + path_set(out, "Path", element.path); + } + else if (element.type == ElementType::SHADER) + { + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + path_set(out, "Vertex", element.vertex); + path_set(out, "Fragment", element.fragment); + } + else if (element.type == ElementType::UNIFORM) + { + out->SetAttribute("Name", element.name.c_str()); + if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str()); + if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str()); + } + else if (element.type == ElementType::COMPONENT) + { + out->SetAttribute("Index", element.index); + if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str()); + if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str()); + } + else if (element.type == ElementType::REGION) + { + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + out->SetAttribute("XCrop", element.crop.x); + out->SetAttribute("YCrop", element.crop.y); + out->SetAttribute("Width", element.size.x); + out->SetAttribute("Height", element.size.y); + origin_write(out, element); + } + else if (element.type == ElementType::LAYER_ELEMENT) + { + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + out->SetAttribute("SpritesheetId", element.spritesheetId); + } + else if (element.type == ElementType::NULL_ELEMENT) + { + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + if (element.isShowRect) out->SetAttribute("ShowRect", element.isShowRect); + } + else if (element.type == ElementType::GROUP) + { + if (!is_nested_group_parent(parentType, flags)) out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + out->SetAttribute("IsExpanded", element.isExpanded); + out->SetAttribute("Visible", element.isVisible); + if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) && + element.index != -1) + out->SetAttribute("Index", element.index); + } + else if (element.type == ElementType::EVENT_ELEMENT) + { + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); + } + else if (element.type == ElementType::SOUND_ELEMENT) + { + out->SetAttribute("Id", element.id); + if (parentType != ElementType::TRIGGER) path_set(out, "Path", element.path); + } + else if (element.type == ElementType::ANIMATION) + { + out->SetAttribute("Name", element.name.c_str()); + out->SetAttribute("FrameNum", element.frameNum); + out->SetAttribute("Loop", element.isLoop); + if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); + } + else if (element.type == ElementType::LAYER_ANIMATION) + { + out->SetAttribute("LayerId", element.layerId); + out->SetAttribute("Visible", element.isVisible); + if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); + } + else if (element.type == ElementType::NULL_ANIMATION) + { + out->SetAttribute("NullId", element.nullId); + out->SetAttribute("Visible", element.isVisible); + if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId); + } + else if (element.type == ElementType::FRAME) + frame_attributes_write(out, element, parentType, flags); + else if (element.type == ElementType::TRIGGER) + { + if (element.eventId != -1) out->SetAttribute("EventId", element.eventId); + out->SetAttribute("AtFrame", element.atFrame); + } + } + + void bake_attributes_write(XMLElement* out, Interpolation interpolation, int bakeDelay) + { + auto value = INTERPOLATION_VALUES[(std::size_t)interpolation]; + if (!value.empty()) out->SetAttribute("BakeInterpolation", value.data()); + out->SetAttribute("BakeDelay", bakeDelay); + } + + bool is_frame_bake_serialized(const Element& frame, Flags flags) + { + return has_flag(flags, SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES) && frame.type == ElementType::FRAME && + frame.interpolation != Interpolation::NONE && frame.interpolation != Interpolation::LINEAR; + } + + void baked_frames_insert(XMLDocument& document, XMLElement* out, const Element& track, int index, Flags flags) + { + const auto& original = track.children[index]; + auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME + ? track.children[index + 1] + : original; + auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN); + + for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex) + { + auto baked = original; + auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay); + baked.duration = FRAME_DURATION_MIN; + baked.interpolation = Interpolation::NONE; + baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); + baked.position = glm::mix(original.position, nextFrame.position, amount); + baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); + baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); + baked.tint = glm::mix(original.tint, nextFrame.tint, amount); + auto frame = element_to_xml(document, baked, track.type, flags); + if (bakeIndex == 0) bake_attributes_write(frame, original.interpolation, bakeDelay); + out->InsertEndChild(frame); + } + } + + void trigger_sounds_xml_insert(XMLDocument& document, XMLElement* out, const Element& element, Flags flags) + { + if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return; + + for (auto soundId : element.soundIds) + { + if (soundId == -1) continue; + auto sound = document.NewElement(element_tag_get(ElementType::SOUND_ELEMENT).data()); + sound->SetAttribute("Id", soundId); + out->InsertEndChild(sound); + } + } + + XMLElement* element_to_xml(XMLDocument& document, const Element& element, ElementType parentType, Flags flags) + { + auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type); + auto out = document.NewElement(tag.empty() ? element.tag.c_str() : tag.data()); + element_attributes_write(out, element, parentType, flags); + trigger_sounds_xml_insert(document, out, element, flags); + + for (int i = 0; i < (int)element.children.size(); ++i) + { + const auto& child = element.children[i]; + if (element_write_skip(child, element.type, flags)) continue; + + if (is_track(element) && is_frame_bake_serialized(child, flags)) + baked_frames_insert(document, out, element, i, flags); + else + out->InsertEndChild(element_to_xml(document, child, element.type, flags)); + } + + return out; + } + + 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{}; + document.InsertEndChild(element_to_xml(document, element, parentType, flags)); + return xml::document_to_string(document); + } + + std::string element_to_string(const Element& element, Flags flags) + { + 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) + { + 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 = element_container_type_get(type); + auto container = element_get(containerType); + if (!container) + { + if (errorString) *errorString = std::format("No {} container.", element_tag_get(containerType)); + return false; + } + + std::optional workingDirectory{}; + if ((type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET) && !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 (type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET) + element.path = path::backslash_handle(element.path); + container->children.push_back(element); + } + + return true; + } + + bool Anm2::regions_deserialize(int spritesheetId, const std::string& string, bool isAppend, std::string* errorString) + { + XMLDocument document{}; + if (document.Parse(string.c_str()) != XML_SUCCESS) + { + if (errorString) *errorString = document.ErrorStr(); + return false; + } + + if (!document.FirstChildElement("Region")) + { + if (errorString) *errorString = "No valid region(s)."; + return false; + } + + auto spritesheet = element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) + { + if (errorString) *errorString = "No spritesheet."; + return false; + } + + for (auto element = document.FirstChildElement("Region"); element; element = element->NextSiblingElement("Region")) + { + auto region = element_read(element); + if (region.type != ElementType::REGION) continue; + if (isAppend) + region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); + else + element_child_id_erase(*spritesheet, ElementType::REGION, region.id); + spritesheet->children.push_back(region); + } + + return true; + } +} diff --git a/src/imgui/dockspace.hpp b/src/imgui/dockspace.hpp index 0d3b462..b1e8287 100644 --- a/src/imgui/dockspace.hpp +++ b/src/imgui/dockspace.hpp @@ -8,7 +8,7 @@ #include "window/onionskin.hpp" #include "window/shaders.hpp" #include "window/spritesheet_editor.hpp" -#include "window/timeline.hpp" +#include "window/timeline/timeline.hpp" #include "window/tools.hpp" #include "window/welcome.hpp" #include "window/window.hpp" diff --git a/src/imgui/window/timeline.cpp b/src/imgui/window/timeline.cpp deleted file mode 100644 index 465be20..0000000 --- a/src/imgui/window/timeline.cpp +++ /dev/null @@ -1,4231 +0,0 @@ -#include "timeline.hpp" - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "actions.hpp" -#include "log.hpp" -#include "math.hpp" -#include "toast.hpp" -#include "util/imgui/draw.hpp" -#include "util/imgui/input.hpp" -#include "util/imgui/layout.hpp" -#include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" - -#include "vector.hpp" - -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; -using namespace glm; - -namespace anm2ed::imgui -{ - - constexpr auto WIDTH_MULTIPLIER = 1.25f; - - constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f); - constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); - constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f); - constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f); - constexpr auto FRAME_BORDER_COLOR_REFERENCED_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.60f); - constexpr auto FRAME_BORDER_THICKNESS = 1.0f; - constexpr auto FRAME_BORDER_THICKNESS_REFERENCED = 2.0f; - constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.05f); - constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.1f); - constexpr auto FRAME_ROUNDING = 3.0f; - constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(color::WHITE); - constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f); - constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(color::WHITE); - constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f); - constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f; - constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(color::WHITE); - constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); - constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f); - constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT = ImVec4(0.8353f, 0.8353f, 0.7294f, 1.0f); - constexpr auto TIMELINE_TICK_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto TIMELINE_CHILD_BG_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); - constexpr auto TIMELINE_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - - enum class DropZone - { - BEFORE, - INSIDE, - AFTER - }; - - constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f}, - {0.5216f, 0.7333f, 1.0f, 1.0f}, - {1.0f, 0.9961f, 0.5882f, 1.0f}, - {0.6157f, 1.0f, 0.5882f, 1.0f}, - {1.0f, 0.5882f, 0.8314f, 1.0f}}; - constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f}, - {0.0980f, 0.3765f, 0.6431f, 1.0f}, - {1.0f, 0.5255f, 0.3333f, 1.0f}, - {0.3686f, 0.5765f, 0.2353f, 1.0f}, - {0.6118f, 0.2039f, 0.2745f, 1.0f}}; - constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f}, - {0.0752f, 0.2887f, 0.4931f, 1.0f}, - {0.85f, 0.4467f, 0.2833f, 1.0f}, - {0.2727f, 0.4265f, 0.1741f, 1.0f}, - {0.4618f, 0.1539f, 0.2072f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f}, - {0.3333f, 0.5725f, 0.8392f, 1.0f}, - {1.0f, 0.5412f, 0.3412f, 1.0f}, - {0.5255f, 0.8471f, 0.4588f, 1.0f}, - {0.7961f, 0.3882f, 0.5412f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f}, - {0.3733f, 0.6125f, 0.8792f, 1.0f}, - {0.9106f, 0.4949f, 0.2753f, 1.0f}, - {0.5655f, 0.8871f, 0.4988f, 1.0f}, - {0.8361f, 0.4282f, 0.5812f, 1.0f}}; - constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f}, - {0.2039f, 0.4549f, 0.7176f, 1.0f}, - {0.8745f, 0.4392f, 0.2275f, 1.0f}, - {0.3765f, 0.6784f, 0.2980f, 1.0f}, - {0.6353f, 0.2235f, 0.3647f, 1.0f}}; - - constexpr auto FRAME_MULTIPLE = 5; - constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; - constexpr auto DRAG_DROP_SOURCE_FLAGS = - ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; - -#define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5 - - struct TimelineItemRow - { - int type{NONE}; - int id{-1}; - int index{-1}; - int groupId{-1}; - int rootGroupType{NONE}; - int rootGroupId{-1}; - int depth{}; - bool isGroup{}; - }; - - struct RootFrameSpan - { - int start{}; - int end{}; - }; - - void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) - { - auto& document = *manager.get(); - auto& anm2 = document.anm2; - auto& playback = document.playback; - auto& reference = document.reference; - auto& frames = document.frames; - auto& region = document.region; - auto animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); - auto rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f; - - style = ImGui::GetStyle(); - auto isLightTheme = settings.theme == theme::LIGHT; - bool isTextPushed = false; - if (isLightTheme) - { - ImGui::PushStyleColor(ImGuiCol_Text, TIMELINE_TEXT_COLOR_LIGHT); - isTextPushed = true; - } - - auto type_index = [](int type) { return std::clamp(type, 0, (int)TRIGGER); }; - auto item_type_get = [](int type) { return static_cast(type); }; - auto item_get = [&](int type, int id = -1, int groupType = NONE, int groupId = -1) - { return animation ? animation_item_get(*animation, item_type_get(type), id, groupType, groupId) : nullptr; }; - auto frame_get = [&]() - { - if (reference.frameIndex < 0) return (Element*)nullptr; - return anm2.element_get(reference); - }; - auto selected_item_get = [&]() - { - auto itemReference = reference; - itemReference.frameIndex = -1; - return anm2.element_get(itemReference); - }; - auto item_frame_type_get = [](const Element& item) - { return item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; }; - auto item_frames_count = [](const Element* item) - { - if (!item) return 0; - auto frameType = item->type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int count{}; - for (const auto& child : item->children) - if (child.type == frameType) ++count; - return count; - }; - auto item_frame_child_index_get = [](const Element& item, int frameIndex) - { - if (frameIndex < 0) return -1; - auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int currentFrameIndex{}; - for (int i = 0; i < (int)item.children.size(); ++i) - { - if (item.children[i].type != frameType) continue; - if (currentFrameIndex == frameIndex) return i; - ++currentFrameIndex; - } - return -1; - }; - auto item_frame_insert_index_get = [](const Element& item, int frameIndex) - { - auto targetFrameIndex = glm::max(0, frameIndex); - auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int currentFrameIndex{}; - for (int i = 0; i < (int)item.children.size(); ++i) - { - if (item.children[i].type != frameType) continue; - if (currentFrameIndex == targetFrameIndex) return i; - ++currentFrameIndex; - } - return (int)item.children.size(); - }; - auto layer_get = [&](int id) { return anm2.element_get(ElementType::LAYER_ELEMENT, id); }; - auto null_get = [&](int id) - { - auto nulls = anm2.element_get(ElementType::NULLS); - return nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; - }; - auto spritesheet_get = [&](int id) { return anm2.element_get(ElementType::SPRITESHEET, id); }; - auto info_get = [&]() { return element_first_get(anm2.root, ElementType::INFO); }; - auto container_type_get = [](int type) - { - if (type == LAYER) return ElementType::LAYER_ANIMATIONS; - if (type == NULL_) return ElementType::NULL_ANIMATIONS; - return ElementType::UNKNOWN; - }; - auto track_type_get = [](int type) - { - if (type == LAYER) return ElementType::LAYER_ANIMATION; - if (type == NULL_) return ElementType::NULL_ANIMATION; - return ElementType::UNKNOWN; - }; - auto track_id_get = [](const Element& track, int type) - { - if (type == LAYER) return track.layerId; - if (type == NULL_) return track.nullId; - return -1; - }; - auto track_container_get = [&](int type) - { - return animation ? element_child_first_get(*animation, container_type_get(type)) : nullptr; - }; - auto track_group_get = [&](int type, int groupId) - { - auto container = track_container_get(type); - return container ? element_child_id_get(*container, ElementType::GROUP, groupId) : nullptr; - }; - auto is_track_group_visible = [&](int type, int groupId) - { - if (groupId == -1) return true; - auto group = track_group_get(type, groupId); - return !group || group->isVisible; - }; - auto row_group_get = [&](const TimelineItemRow& row) -> Element* - { - return row.isGroup ? track_group_get(row.type, row.id) : nullptr; - }; - auto group_items_count_get = [&](int type, int groupId) - { - auto container = track_container_get(type); - auto trackType = track_type_get(type); - int count{}; - if (!container) return count; - for (auto& item : container->children) - if (item.type == trackType && item.groupId == groupId) ++count; - return count; - }; - - auto command_animation_get = [](Document& document, int animationIndex) - { return document.anm2.element_get(ElementType::ANIMATION, animationIndex); }; - auto command_item_get = [](Document& document, int animationIndex, int type, int id, int groupType = NONE, - int groupId = -1) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, static_cast(type), id, groupType, groupId) : nullptr; - }; - auto command_item_reference_get = [](Document& document, Reference itemReference) - { - itemReference.frameIndex = -1; - return document.anm2.element_get(itemReference); - }; - auto command_frame_get = [](Document& document, const Reference& targetReference) - { - if (targetReference.frameIndex < 0) return (Element*)nullptr; - return document.anm2.element_get(targetReference); - }; - auto command_layer_get = [](Document& document, int id) - { return document.anm2.element_get(ElementType::LAYER_ELEMENT, id); }; - auto command_spritesheet_get = [](Document& document, int id) - { return document.anm2.element_get(ElementType::SPRITESHEET, id); }; - auto command_info_get = [](Document& document) - { return element_first_get(document.anm2.root, ElementType::INFO); }; - auto item_reference_get = [&](int type, int id, int groupType = NONE, int groupId = -1) - { return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; }; - auto item_reference_from_frame_get = [](Reference frameReference) - { - frameReference.frameIndex = -1; - return frameReference; - }; - auto is_same_item = [](const Reference& left, const Reference& right) - { - return left.animationIndex == right.animationIndex && left.itemType == right.itemType && - left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; - }; - auto is_frame_reference_valid_for = [&](Document& targetDocument, const Reference& frameReference) - { return targetDocument.is_frame_reference_valid(frameReference); }; - auto group_selection_reset_for = [this](Document& targetDocument) - { - targetDocument.groupReferences.clear(); - isRowSelectionAnchorSet = false; - }; - auto frame_references_for_current_get = [&]() - { return document.frame_references_get(Document::FrameReferenceFallback::NONE); }; - auto item_references_for_current_get = [&]() - { - std::set result = document.items.references; - if (result.empty() && reference.itemType != NONE) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - result.insert(itemReference); - } - return result; - }; - auto frames_selection_sync_for = [&](Document& targetDocument) - { - auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - targetDocument.frame_references_set(std::move(selectedFrames)); - frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); - frameSelectionSnapshotReference = targetDocument.reference; - }; - auto item_selection_set_for = [&](Document& targetDocument, Reference itemReference) - { - itemReference.frameIndex = -1; - targetDocument.items.references = {itemReference}; - }; - auto frame_selection_set_for = [&](Document& targetDocument, Reference frameReference) - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - targetDocument.frame_references_set({frameReference}); - frames_selection_sync_for(targetDocument); - }; - auto frame_selection_toggle_for = [&](Document& targetDocument, Reference frameReference) - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - auto selection = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - auto itemReference = item_reference_from_frame_get(frameReference); - if (selection.contains(frameReference)) - { - if (selection.size() > 1) selection.erase(frameReference); - bool isItemStillSelected{}; - for (const auto& selectedFrame : selection) - if (is_same_item(selectedFrame, itemReference)) isItemStillSelected = true; - if (!isItemStillSelected && targetDocument.items.references.size() > 1) - targetDocument.items.references.erase(itemReference); - } - else - { - selection.insert(frameReference); - targetDocument.items.references.insert(itemReference); - } - targetDocument.reference = frameReference; - targetDocument.frame_references_set(std::move(selection)); - frames_selection_sync_for(targetDocument); - }; - auto frame_selection_range_set_for = [&](Document& targetDocument, Reference firstReference, - Reference lastReference, bool isAdditive) -> bool - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - if (!is_same_item(firstReference, lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) - return false; - - auto item = command_item_reference_get(targetDocument, lastReference); - if (!item) return false; - if (firstReference.frameIndex >= (int)item->children.size() || - lastReference.frameIndex >= (int)item->children.size()) - return false; - - auto firstIndex = firstReference.frameIndex; - auto lastIndex = lastReference.frameIndex; - if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); - auto selectedFrames = isAdditive ? targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE) - : std::set{}; - - for (int i = firstIndex; i <= lastIndex; ++i) - { - auto frameReference = lastReference; - frameReference.frameIndex = i; - selectedFrames.insert(frameReference); - } - - targetDocument.reference = lastReference; - targetDocument.frame_references_set(std::move(selectedFrames)); - frames_selection_sync_for(targetDocument); - return true; - }; - auto all_frame_references_for_items_get = [&]() - { return document.selected_item_frame_references_get(); }; - auto is_frame_copy_item = [](const Reference& itemReference) - { return itemReference.itemType == ROOT || itemReference.itemType == LAYER || itemReference.itemType == NULL_; }; - auto copy_frame_references_get = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (!selectedFrames.empty()) return selectedFrames; - - auto selectedItems = document.items.references; - if (selectedItems.empty() && reference.itemType != NONE && reference.frameIndex < 0) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - selectedItems.insert(itemReference); - } - - std::set result{}; - for (auto itemReference : selectedItems) - { - itemReference.frameIndex = -1; - if (!is_frame_copy_item(itemReference)) continue; - auto itemFrames = document.item_frame_references_get(itemReference); - result.insert(itemFrames.begin(), itemFrames.end()); - } - return result; - }; - auto frames_selection_reset_for = [this](Document& targetDocument) - { - targetDocument.frame_references_clear(); - frameSelectionSnapshot.clear(); - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusRequested = false; - frameFocusIndex = -1; - frameSelectionSnapshotReference = targetDocument.reference; - }; - auto frames_selection_set_reference_for = [this](Document& targetDocument) - { - auto& targetReference = targetDocument.reference; - if (targetReference.frameIndex >= 0) - { - targetDocument.editTarget = Document::EditTarget::FRAME; - targetDocument.frame_references_set({targetReference}); - } - else - targetDocument.frame_references_clear(); - frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); - frameSelectionSnapshotReference = targetReference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = targetReference.frameIndex; - frameFocusRequested = targetReference.frameIndex >= 0; - }; - auto frames_reference_normalize_for = [&](Document& targetDocument) - { - auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - if (!selectedFrames.empty()) - { - targetDocument.frame_references_set(std::move(selectedFrames)); - frames_selection_sync_for(targetDocument); - return; - } - - if (targetDocument.reference.frameIndex >= 0 && - !is_frame_reference_valid_for(targetDocument, targetDocument.reference)) - targetDocument.reference.frameIndex = -1; - }; - frames_reference_normalize_for(document); - auto reference_clear_for = [=](Document& targetDocument) - { - targetDocument.reference = {targetDocument.reference.animationIndex}; - frames_selection_reset_for(targetDocument); - targetDocument.items.references.clear(); - }; - auto reference_set_item_reference_for = [=](Document& targetDocument, Reference itemReference) - { - itemReference.frameIndex = -1; - targetDocument.reference = itemReference; - frames_selection_reset_for(targetDocument); - item_selection_set_for(targetDocument, itemReference); - }; - auto reference_set_timeline_item_reference_for = [=](Document& targetDocument, Reference itemReference) - { - if (itemReference.itemType == LAYER) - if (auto layer = command_layer_get(targetDocument, itemReference.itemID)) - targetDocument.spritesheet.reference = layer->spritesheetId; - reference_set_item_reference_for(targetDocument, itemReference); - }; - auto command_push = [&](auto run) - { - manager.command_push({manager.selected, - [run](Manager& manager, Document& document) mutable { run(manager, document); }}); - }; - auto track_references_from_frame_references_get = [](std::set frameReferences) - { - std::set result{}; - for (auto frameReference : frameReferences) - { - frameReference.frameIndex = -1; - result.insert(frameReference); - } - return result; - }; - auto tracks_snapshot_command_push = [&](StringType messageType, const std::set& trackReferences) - { - auto message = std::string(localize.get(messageType)); - auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, - [message, queuedTrackReferences](Manager&, Document& document) - { document.tracks_snapshot(message, queuedTrackReferences); }}); - }; - auto frames_snapshot_command_push = [&](StringType messageType, const std::set& frameReferences) - { - auto message = std::string(localize.get(messageType)); - auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, - [message, queuedFrameReferences](Manager&, Document& document) - { document.frames_snapshot(message, queuedFrameReferences); }}); - }; - auto frames_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& frameReferences, auto run) - { - auto message = std::string(localize.get(messageType)); - auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, - [=](Manager& manager, Document& document) mutable - { - (void)changeType; - document.frames_snapshot(message, queuedFrameReferences); - run(manager, document); - document.anm2_change(changeType); - }}); - }; - auto tracks_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& trackReferences, auto run) - { - auto message = std::string(localize.get(messageType)); - auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, - [=](Manager& manager, Document& document) mutable - { - (void)changeType; - document.tracks_snapshot(message, queuedTrackReferences); - run(manager, document); - document.anm2_change(changeType); - }}); - }; - auto edit_command_push = [&](StringType messageType, Document::ChangeType changeType, auto run) - { - auto message = std::string(localize.get(messageType)); - manager.command_push({manager.selected, - [=](Manager& manager, Document& document) mutable - { - (void)changeType; - document.anm2_snapshot(message); - run(manager, document); - document.anm2_change(changeType); - }}); - }; - auto type_color_base_vec = [&](int type) - { return isLightTheme ? FRAME_COLOR_LIGHT_BASE[type_index(type)] : TYPE_COLOR[type]; }; - - auto type_color_active_vec = [&](int type) - { - if (isLightTheme) return FRAME_COLOR_LIGHT_ACTIVE[type_index(type)]; - return TYPE_COLOR_ACTIVE[type]; - }; - - auto type_color_hovered_vec = [&](int type) - { - if (isLightTheme) return FRAME_COLOR_LIGHT_HOVERED[type_index(type)]; - return TYPE_COLOR_HOVERED[type]; - }; - - auto item_color_vec = [&](int type) - { - if (!isLightTheme) return TYPE_COLOR[type]; - return ITEM_COLOR_LIGHT_BASE[type_index(type)]; - }; - - auto item_color_active_vec = [&](int type) - { - if (!isLightTheme) return TYPE_COLOR_ACTIVE[type]; - return ITEM_COLOR_LIGHT_ACTIVE[type_index(type)]; - }; - - auto iconTintDefault = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : ICON_TINT_DEFAULT_DARK; - auto itemIconTint = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : iconTintDefault; - auto frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; - auto frameBorderColorReferenced = - isLightTheme ? FRAME_BORDER_COLOR_REFERENCED_LIGHT : FRAME_BORDER_COLOR_REFERENCED_DARK; - auto frameMultipleOverlayColor = - isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; - auto textMultipleColor = isLightTheme ? TEXT_MULTIPLE_COLOR_LIGHT : TEXT_MULTIPLE_COLOR_DARK; - auto playheadLineColor = isLightTheme ? PLAYHEAD_LINE_COLOR_LIGHT : PLAYHEAD_LINE_COLOR_DARK; - auto playheadIconTint = isLightTheme ? PLAYHEAD_ICON_TINT_LIGHT : iconTintDefault; - auto timelineBackgroundColor = - isLightTheme ? TIMELINE_BACKGROUND_COLOR_LIGHT : ImGui::GetStyleColorVec4(ImGuiCol_Header); - auto timelinePlayheadRectColor = - isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; - auto timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; - auto itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; - - auto overlay_icon = [&](GLuint textureId, ImVec4 tint, bool isForced = false) - { - if (!isForced && !isLightTheme) return; - auto min = ImGui::GetItemRectMin(); - auto max = ImGui::GetItemRectMax(); - ImGui::GetWindowDrawList()->AddImage((ImTextureID)(intptr_t)textureId, min, max, ImVec2(0, 0), ImVec2(1, 1), - ImGui::GetColorU32(tint)); - }; - - auto frames_selection_set_reference = [&]() - { - frames_selection_set_reference_for(document); - }; - - auto playback_stop = [&]() - { - playback.isPlaying = false; - playback.isFinished = false; - playback.timing_reset(); - }; - - auto frame_insert = [&]() - { - auto targetReference = reference; - auto targetFrameTime = document.frameTime; - if (!animation || !command_item_reference_get(document, targetReference)) - return; - - tracks_edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetReference.animationIndex); - auto item = command_item_reference_get(document, targetReference); - if (!animation || !item) return; - - auto newReference = targetReference; - - if (targetReference.itemType == TRIGGER) - { - for (auto& trigger : item->children) - if (targetFrameTime == trigger.atFrame) return; - - auto addFrame = element_make(ElementType::TRIGGER); - addFrame.atFrame = targetFrameTime; - item->children.push_back(addFrame); - frames_sort_by_at_frame(*item); - newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); - } - else - { - auto frame = command_frame_get(document, targetReference); - auto framesCount = item_frames_count(item); - if (frame) - { - auto addFrame = *frame; - auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, addFrame); - newReference.frameIndex = insertIndex; - } - else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) - { - item->children.emplace_back(*lastFrame); - newReference.frameIndex = framesCount; - } - else - { - item->children.emplace_back(element_make(ElementType::FRAME)); - newReference.frameIndex = 0; - } - } - - document.reference = newReference; - frames_selection_set_reference_for(document); - if (newReference.itemType != TRIGGER) - document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); - }); - }; - - auto frames_delete_for = [=](Document& document, std::set selectedFrames) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - } - - auto item = command_item_reference_get(document, document.reference); - if (!item || item->children.empty()) - { - document.reference.frameIndex = -1; - frames_selection_reset_for(document); - return; - } - - document.reference.frameIndex = glm::clamp(document.reference.frameIndex, 0, (int)item->children.size() - 1); - frames_selection_set_reference_for(document); - }; - - auto frames_delete_action = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.empty()) return; - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_DELETE_FRAMES, Document::FRAMES, trackReferences, - [=](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }); - }; - - auto frames_duplicate = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set duplicatedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - std::vector validIndices{}; - std::vector duplicatedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - duplicatedFrames.push_back(*frame); - } - if (validIndices.empty()) continue; - - auto insertIndex = validIndices.back() + 1; - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(duplicatedFrames.begin()), - std::make_move_iterator(duplicatedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - duplicatedSelection.insert(targetReference); - auto sourceReference = itemReference; - sourceReference.frameIndex = validIndices[offset]; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (duplicatedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); - document.frame_references_set(std::move(duplicatedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - auto is_frames_reverse_available = [&](std::set selectedFrames) - { - std::map counts{}; - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - ++counts[itemReference]; - } - return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); - }; - - auto frames_reverse = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (!is_frames_reverse_available(selectedFrames)) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_REVERSE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set reversedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item || indices.size() < 2) continue; - - std::vector validIndices{}; - std::vector reversedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - reversedFrames.push_back(std::move(*frame)); - } - if (validIndices.size() < 2) continue; - - auto insertIndex = validIndices.front(); - for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - - std::ranges::reverse(reversedFrames); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(reversedFrames.begin()), - std::make_move_iterator(reversedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - reversedSelection.insert(targetReference); - auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; - auto sourceReference = itemReference; - sourceReference.frameIndex = sourceIndex; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (reversedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); - document.frame_references_set(std::move(reversedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - auto frames_bake = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - auto bakeInterval = settings.bakeInterval; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_BAKE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set bakedSelection{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - int insertedBefore = 0; - for (auto originalIndex : indices) - { - auto i = originalIndex + insertedBefore; - auto frame = track_frame_get(*item, i); - if (!frame) continue; - - auto originalDuration = frame->duration; - frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); - - auto bakedCount = originalDuration <= FRAME_DURATION_MIN - ? 1 - : (int)std::ceil((float)originalDuration / bakeInterval); - for (int offset = 0; offset < bakedCount; ++offset) - { - auto frameReference = itemReference; - frameReference.frameIndex = i + offset; - bakedSelection.insert(frameReference); - } - - insertedBefore += bakedCount - 1; - } - } - - document.frame_references_set(std::move(bakedSelection)); - if (!document.frames.references.empty()) - { - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - } - else - frames_selection_reset_for(document); - }); - }; - - auto selected_root_frame_references_get = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); - return selectedFrames; - }; - - auto item_references_for_bake_into_other_frames_get = [](const Document& targetDocument, - const Element& targetAnimation, - BakeIntoOtherFramesTarget target, bool isLayers, - bool isNulls) - { - std::set result{}; - auto animationIndex = targetDocument.reference.animationIndex; - if (target == BakeIntoOtherFramesTarget::CURRENT_SELECTION) - { - for (auto itemReference : targetDocument.items.references) - { - itemReference.frameIndex = -1; - if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) result.insert(itemReference); - } - return result; - } - - auto add_items = [&](const Element& container, int itemType) - { - auto trackType = item_type_to_track_type_get(static_cast(itemType)); - auto add_item = [&](auto&& self, const Element& item) -> void - { - if (item.type == ElementType::GROUP) - { - for (const auto& child : item.children) - self(self, child); - return; - } - if (item.type != trackType) return; - auto itemID = itemType == LAYER ? item.layerId : item.nullId; - auto groupType = item.groupId == -1 ? NONE : itemType; - result.insert({animationIndex, itemType, itemID, -1, groupType, item.groupId}); - }; - for (const auto& item : container.children) - add_item(add_item, item); - }; - - if (isLayers) - if (auto layerAnimations = element_child_first_get(targetAnimation, ElementType::LAYER_ANIMATIONS)) - add_items(*layerAnimations, LAYER); - if (isNulls) - if (auto nullAnimations = element_child_first_get(targetAnimation, ElementType::NULL_ANIMATIONS)) - add_items(*nullAnimations, NULL_); - return result; - }; - - auto is_bake_into_other_frames_ready = [&]() - { - auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty() || !animation) return false; - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - return !targetItems.empty(); - }; - - auto frame_root_transform_apply = [](Element& frame, const Element& rootFrame, bool isRoundScale, - bool isRoundRotation, bool isUseRootPivot) - { - auto rootScale = math::percent_to_unit(rootFrame.scale); - auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); - auto offset = (frame.position - pivot) * rootScale; - auto radians = glm::radians(rootFrame.rotation); - auto cos = std::cos(radians); - auto sin = std::sin(radians); - - frame.position = - rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); - frame.scale *= rootScale; - frame.rotation += rootFrame.rotation; - frame.tint *= rootFrame.tint; - frame.colorOffset += rootFrame.colorOffset; - - if (isRoundScale) frame.scale = glm::round(frame.scale); - if (isRoundRotation) frame.rotation = std::round(frame.rotation); - }; - - auto bake_into_other_frames = [&]() - { - auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty()) return; - if (!animation) return; - auto target = bakeIntoOtherFramesTarget; - auto isLayers = isBakeIntoOtherFramesLayers; - auto isNulls = isBakeIntoOtherFramesNulls; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; - auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto isUseRootPivot = settings.bakeIsUseRootPivot; - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); - trackReferences.insert(targetItems.begin(), targetItems.end()); - tracks_edit_command_push(EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, document.reference.animationIndex); - if (!animation) return; - auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); - for (auto rootReference : selectedRootFrames) - if (!is_same_item(rootReference, rootItemReference)) return; - auto root = command_item_reference_get(document, rootItemReference); - if (!root) return; - - std::vector spans{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); - spans.push_back({start, start + rootFrame->duration}); - } - if (spans.empty()) return; - - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, target, isLayers, isNulls); - if (targetItems.empty()) return; - - for (auto itemReference : targetItems) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - if (isMatchRootInterpolation) - { - std::vector bakeIndices{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - bakeIndices.push_back(frameIndex); - break; - } - ++frameIndex; - } - for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) - frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); - } - - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - bool isInsideSpan{}; - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - isInsideSpan = true; - break; - } - if (!isInsideSpan) - { - ++frameIndex; - continue; - } - auto rootFrame = frame_generate(*root, (float)frameStart); - frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, - isUseRootPivot); - ++frameIndex; - } - } - - std::set selectedRootFrameIndices{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - selectedRootFrameIndices.insert(rootReference.frameIndex); - } - if (selectedRootFrameIndices.empty()) return; - - std::vector rootFrames{}; - std::set defaultRootSelection{}; - int frameIndex{}; - int rewrittenFrameIndex{}; - int defaultDuration{}; - auto default_root_frame_push = [&]() - { - if (defaultDuration <= 0) return; - auto frame = element_make(ElementType::FRAME); - frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); - auto defaultRootReference = rootItemReference; - defaultRootReference.frameIndex = rewrittenFrameIndex; - defaultRootSelection.insert(defaultRootReference); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - defaultDuration = 0; - }; - - for (const auto& frame : root->children) - { - if (frame.type != ElementType::FRAME) - { - default_root_frame_push(); - rootFrames.push_back(frame); - continue; - } - - if (selectedRootFrameIndices.contains(frameIndex)) - defaultDuration += frame.duration; - else - { - default_root_frame_push(); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - } - ++frameIndex; - } - default_root_frame_push(); - - root->children = std::move(rootFrames); - document.frame_references_set(std::move(defaultRootSelection)); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - std::optional frameSplitTimeAtCursor; - - auto frame_split = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.size() != 1) return; - auto targetReference = *selectedFrames.begin(); - auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); - if (targetReference.itemType == TRIGGER) return; - - tracks_edit_command_push(EDIT_SPLIT_FRAME, Document::FRAMES, {targetReference}, - [=](Manager&, Document& document) mutable - { - if (targetReference.itemType == TRIGGER) return; - - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - - if (!item || !frame) return; - - auto originalDuration = frame->duration; - if (originalDuration <= 1) return; - - auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); - int frameStart = (int)std::round(frameStartTime); - int firstDuration = splitTime - frameStart + 1; - - if (firstDuration <= 0 || firstDuration >= originalDuration) return; - - int secondDuration = originalDuration - firstDuration; - auto splitFrame = *frame; - splitFrame.duration = secondDuration; - - auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); - if (frame->interpolation != Interpolation::NONE && nextFrame) - { - float interpolation = (float)firstDuration / (float)originalDuration; - switch (frame->interpolation) - { - case Interpolation::EASE_IN: - interpolation *= interpolation; - break; - case Interpolation::EASE_OUT: - interpolation = 1.0f - ((1.0f - interpolation) * (1.0f - interpolation)); - break; - case Interpolation::EASE_IN_OUT: - interpolation = interpolation < 0.5f - ? (2.0f * interpolation * interpolation) - : (1.0f - std::pow(-2.0f * interpolation + 2.0f, 2.0f) * 0.5f); - break; - case Interpolation::LINEAR: - case Interpolation::NONE: - default: - break; - } - - splitFrame.rotation = glm::mix(frame->rotation, nextFrame->rotation, interpolation); - splitFrame.position = glm::mix(frame->position, nextFrame->position, interpolation); - splitFrame.scale = glm::mix(frame->scale, nextFrame->scale, interpolation); - splitFrame.colorOffset = glm::mix(frame->colorOffset, nextFrame->colorOffset, interpolation); - splitFrame.tint = glm::mix(frame->tint, nextFrame->tint, interpolation); - } - - frame->duration = firstDuration; - auto insertIndex = item_frame_insert_index_get(*item, targetReference.frameIndex + 1); - item->children.insert(item->children.begin() + insertIndex, splitFrame); - document.reference = targetReference; - frames_selection_set_reference_for(document); - }); - }; - - auto reference_clear = [&]() - { - group_selection_reset_for(document); - reference_clear_for(document); - }; - - auto reference_set_timeline_item_reference = [&](Reference itemReference) - { - group_selection_reset_for(document); - reference_set_timeline_item_reference_for(document, itemReference); - }; - - auto timeline_item_rows_get = [&]() - { - std::vector rows{}; - if (!animation) return rows; - - auto track_row_push = [&](const Element& item, int type, int index, int depth = 0) - { - auto rootGroupType = item.groupId == -1 ? NONE : type; - rows.push_back({.type = type, - .id = track_id_get(item, type), - .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; - }; - - rows.push_back({.type = ROOT}); - - if (auto layerAnimations = element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) - { - auto groupIds = group_ids_get(*layerAnimations); - auto layer_track_push = [&](int groupId, int depth) - { - for (int j = (int)layerAnimations->children.size() - 1; j >= 0; --j) - { - auto& item = layerAnimations->children[j]; - if (item.type != ElementType::LAYER_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, LAYER, j, depth); - } - }; - - for (int i = (int)layerAnimations->children.size() - 1; i >= 0; --i) - { - auto& item = layerAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, LAYER, i); - if (item.isExpanded) - { - group_root_row_push(item, LAYER); - layer_track_push(item.id, 1); - } - } - else if (item.type == ElementType::LAYER_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, LAYER, i); - } - } - - if (auto nullAnimations = element_child_first_get(*animation, ElementType::NULL_ANIMATIONS)) - { - auto groupIds = group_ids_get(*nullAnimations); - auto null_track_push = [&](int groupId, int depth) - { - for (int j = 0; j < (int)nullAnimations->children.size(); ++j) - { - auto& item = nullAnimations->children[j]; - if (item.type != ElementType::NULL_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, NULL_, j, depth); - } - }; - - for (int i = 0; i < (int)nullAnimations->children.size(); ++i) - { - auto& item = nullAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, NULL_, i); - if (item.isExpanded) - { - group_root_row_push(item, NULL_); - null_track_push(item.id, 1); - } - } - else if (item.type == ElementType::NULL_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, NULL_, i); - } - } - - rows.push_back({.type = TRIGGER}); - return rows; - }; - - auto timeline_item_references_get = [&]() - { - std::vector itemReferences; - for (const auto& row : timeline_item_rows_get()) - { - if (row.isGroup) continue; - itemReferences.push_back( - {reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); - } - return itemReferences; - }; - - auto group_reference_get = [&](const TimelineItemRow& row) - { return Reference{reference.animationIndex, row.type, row.id}; }; - - auto row_reference_get = [&](const TimelineItemRow& row) - { - return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, row.index, - row.rootGroupType, row.rootGroupId, row.isGroup}; - }; - - auto row_item_reference_get = [](const TimelineRowReference& row) - { return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; }; - - auto timeline_row_references_get = [&]() - { - std::vector rowReferences; - for (const auto& row : timeline_item_rows_get()) - { - if (row.type == NONE) continue; - rowReferences.push_back(row_reference_get(row)); - } - return rowReferences; - }; - - auto is_group_selected = [&](const TimelineItemRow& row) - { - return document.groupReferences.contains(group_reference_get(row)); - }; - - auto is_row_selected = [&](const TimelineItemRow& row) - { - if (row.isGroup) return is_group_selected(row); - auto itemReference = item_reference_get(row.type, row.id, row.rootGroupType, row.rootGroupId); - auto isReferenced = is_same_item(reference, itemReference); - return document.items.references.contains(itemReference) || - (document.items.references.empty() && document.groupReferences.empty() && isReferenced); - }; - - auto row_selection_clear = [&]() - { - document.items.references.clear(); - document.groupReferences.clear(); - }; - - auto row_selection_insert = [&](const TimelineRowReference& row) - { - if (row.isGroup) - document.groupReferences.insert({row.animationIndex, row.type, row.id}); - else - document.items.references.insert(row_item_reference_get(row)); - }; - - auto row_selection_erase = [&](const TimelineRowReference& row) - { - if (row.isGroup) - document.groupReferences.erase({row.animationIndex, row.type, row.id}); - else - document.items.references.erase(row_item_reference_get(row)); - }; - - auto is_row_reference_selected = [&](const TimelineRowReference& row) - { - if (row.isGroup) return document.groupReferences.contains({row.animationIndex, row.type, row.id}); - return document.items.references.contains(row_item_reference_get(row)); - }; - - auto row_selection_count_get = [&]() { return document.items.references.size() + document.groupReferences.size(); }; - - auto row_selection_set = [&](const TimelineItemRow& row) - { - auto rowReference = row_reference_get(row); - auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); - auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); - - if (row.isGroup) - reference = {reference.animationIndex}; - else - { - if (row.type == LAYER) - if (auto layer = layer_get(row.id)) document.spritesheet.reference = layer->spritesheetId; - reference = row_item_reference_get(rowReference); - } - frames_selection_reset_for(document); - - if (isShiftDown) - { - auto rowSelection = timeline_row_references_get(); - auto anchor = isRowSelectionAnchorSet ? rowSelectionAnchor : rowReference; - auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); - auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); - if (first == rowSelection.end() || last == rowSelection.end()) - { - if (!isCtrlDown) row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - else - { - auto firstIndex = (int)std::distance(rowSelection.begin(), first); - auto lastIndex = (int)std::distance(rowSelection.begin(), last); - if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); - if (!isCtrlDown) row_selection_clear(); - for (int i = firstIndex; i <= lastIndex; ++i) - row_selection_insert(rowSelection[i]); - if (!isRowSelectionAnchorSet) rowSelectionAnchor = rowReference; - } - } - else if (isCtrlDown) - { - if (is_row_reference_selected(rowReference) && row_selection_count_get() > 1) - row_selection_erase(rowReference); - else - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - else - { - row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - - isRowSelectionAnchorSet = true; - }; - - auto reference_set_adjacent_item = [&](int direction) - { - auto itemReferences = timeline_item_references_get(); - if (itemReferences.empty()) return; - - auto it = std::find_if( - itemReferences.begin(), itemReferences.end(), [&](const Reference& itemReference) - { return is_same_item(itemReference, reference); }); - - int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; - if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; - index = std::clamp(index, 0, (int)itemReferences.size() - 1); - - auto& itemReference = itemReferences[index]; - reference_set_timeline_item_reference(itemReference); - }; - - auto selected_row_references_get = [&]() - { - std::vector result{}; - for (const auto& row : timeline_item_rows_get()) - if (is_row_selected(row)) result.push_back(row_reference_get(row)); - return result; - }; - - auto row_drag_references_get = [&](const TimelineItemRow& row) - { - auto clicked = row_reference_get(row); - if (clicked.type != LAYER && clicked.type != NULL_) return std::vector{clicked}; - - auto rows = selected_row_references_get(); - if (!is_row_reference_selected(clicked)) rows = {clicked}; - if (rows.empty()) rows = {clicked}; - - std::erase_if(rows, [&](const TimelineRowReference& rowReference) { return rowReference.type != clicked.type; }); - if (rows.empty()) rows = {clicked}; - return rows; - }; - - auto item_remove = [&]() - { - auto targetRows = selected_row_references_get(); - std::map> targetIds{}; - std::map> targetGroupIds{}; - for (auto row : targetRows) - { - if (row.type != LAYER && row.type != NULL_) continue; - if (row.isGroup) - targetGroupIds[row.type].insert(row.id); - else - targetIds[row.type].insert(row.id); - } - auto animationIndex = reference.animationIndex; - if (!animation) return; - if (targetIds.empty() && targetGroupIds.empty()) return; - edit_command_push(EDIT_REMOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - for (auto targetType : {LAYER, NULL_}) - { - auto containerType = container_type_get(targetType); - auto targetTrackType = track_type_get(targetType); - auto container = element_child_first_get(*animation, containerType); - if (!container) continue; - auto ids = targetIds.contains(targetType) ? targetIds.at(targetType) : std::set{}; - auto groupIds = - targetGroupIds.contains(targetType) ? targetGroupIds.at(targetType) : std::set{}; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && groupIds.contains(item.id)) - { - container->children.erase(container->children.begin() + i); - continue; - } - if (item.type == targetTrackType && - (ids.contains(track_id_get(item, targetType)) || groupIds.contains(item.groupId))) - container->children.erase(container->children.begin() + i); - } - } - reference_clear_for(document); - group_selection_reset_for(document); - }); - }; - - auto item_references_groupable_get = [&]() - { - if (!document.groupReferences.empty()) return std::vector{}; - auto selectedItems = item_references_for_current_get(); - std::erase_if(selectedItems, [](const Reference& itemReference) - { return itemReference.itemType != LAYER && itemReference.itemType != NULL_; }); - if (selectedItems.empty()) return std::vector{}; - auto itemType = selectedItems.begin()->itemType; - for (const auto& itemReference : selectedItems) - if (itemReference.itemType != itemType) return std::vector{}; - - std::vector result{}; - for (const auto& row : timeline_item_rows_get()) - { - if (row.isGroup || row.type != itemType) continue; - auto itemReference = item_reference_get(row.type, row.id); - if (!selectedItems.contains(itemReference)) continue; - if (row.groupId != -1) return std::vector{}; - result.push_back(itemReference); - } - return result; - }; - - auto item_group = [&]() - { - auto targetReferences = item_references_groupable_get(); - if (targetReferences.empty()) return; - auto targetType = targetReferences.front().itemType; - auto animationIndex = reference.animationIndex; - auto groupName = std::string(localize.get(TEXT_NEW_GROUP)); - - edit_command_push(EDIT_GROUP_ITEMS, Document::ITEMS, - [=](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - - auto containerType = container_type_get(targetType); - auto targetTrackType = track_type_get(targetType); - auto container = element_child_first_get(*animation, containerType); - if (!container) return; - - std::set targetIds{}; - for (auto itemReference : targetReferences) - targetIds.insert(itemReference.itemID); - - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*container, ElementType::GROUP); - group.name = groupName; - group.isExpanded = true; - auto root = element_make(ElementType::ROOT_ANIMATION); - root.children.push_back(element_make(ElementType::FRAME)); - group.children.push_back(root); - int insertIndex = (int)container->children.size(); - - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == targetTrackType && targetIds.contains(track_id_get(item, targetType))) - { - insertIndex = std::min(insertIndex, i); - item.groupId = group.id; - } - } - - if (insertIndex == (int)container->children.size()) return; - insertIndex = std::clamp(insertIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + insertIndex, group); - - document.items.references.clear(); - for (auto itemReference : targetReferences) - document.items.references.insert(itemReference); - document.reference = targetReferences.front(); - frames_selection_reset_for(document); - }); - }; - - auto rows_move_to_row = [&](std::vector draggedRows, TimelineItemRow targetRow, - bool isDropAfter, bool isDropIntoGroup = false) - { - if (draggedRows.empty()) return; - auto targetType = draggedRows.front().type; - if (targetType != LAYER && targetType != NULL_) return; - for (const auto& draggedRow : draggedRows) - if (draggedRow.type != targetType) return; - - if (targetRow.isGroup && targetRow.type != targetType) return; - if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && - targetRow.type != TRIGGER) - return; - - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_MOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - auto container = element_child_first_get(*animation, container_type_get(targetType)); - if (!container) return; - auto targetTrackType = track_type_get(targetType); - - std::set draggedIds{}; - std::set draggedGroupIds{}; - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - draggedGroupIds.insert(draggedRow.id); - else - draggedIds.insert(draggedRow.id); - } - - if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; - - std::vector movedItems{}; - for (const auto& item : container->children) - { - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || - draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) movedItems.push_back(item); - } - if (movedItems.empty()) return; - - if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; - - auto row_index_get = [&](const TimelineItemRow& row) - { - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; - if (!row.isGroup && row.type == targetType && item.type == targetTrackType && - track_id_get(item, targetType) == row.id) - return i; - } - return -1; - }; - auto group_end_index_get = [&](int groupId) - { - int result = -1; - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); - if (item.type == targetTrackType && item.groupId == groupId) - result = std::max(result, i); - } - return result; - }; - - int targetIndex = (int)container->children.size(); - if (targetRow.isGroup || targetRow.type == targetType) - { - auto rowIndex = row_index_get(targetRow); - if (rowIndex == -1) return; - if (targetRow.isGroup) - { - auto groupEndIndex = group_end_index_get(targetRow.id); - if (targetType == LAYER) - targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; - else - targetIndex = rowIndex + isDropAfter; - } - else - targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); - } - - int removedBeforeTarget = 0; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || - draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) - { - if (i < targetIndex) ++removedBeforeTarget; - container->children.erase(container->children.begin() + i); - } - } - - auto targetGroupId = -1; - if (targetRow.isGroup && isDropIntoGroup) - targetGroupId = targetRow.id; - else if (targetRow.type == targetType) - targetGroupId = targetRow.groupId; - - for (auto& item : movedItems) - if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) - item.groupId = targetGroupId; - - targetIndex -= removedBeforeTarget; - targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), - movedItems.end()); - - document.items.references.clear(); - document.groupReferences.clear(); - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - document.groupReferences.insert( - {draggedRow.animationIndex, draggedRow.type, draggedRow.id}); - else - document.items.references.insert(row_item_reference_get(draggedRow)); - } - if (!document.items.references.empty()) - document.reference = *document.items.references.begin(); - else - document.reference = {animationIndex}; - frames_selection_reset_for(document); - }); - }; - - auto fit_animation_length = [&]() - { - if (!animation) return; - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->frameNum = animation_length_get(*animation); - }); - }; - - auto frame_references_copy = [&](const std::set& selectedFrames) - { - if (!animation || selectedFrames.empty()) return; - - 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; - if (!frame) continue; - auto parentType = item_type_to_track_type_get(item_type_get(frameReference.itemType)); - clipboardString += element_to_string(*frame, parentType); - } - if (!clipboardString.empty()) clipboard.set(clipboardString); - }; - - auto copy = [&]() - { - auto selectedFrames = copy_frame_references_get(); - if (selectedFrames.empty()) return; - - frame_references_copy(selectedFrames); - }; - - auto cut = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.empty()) return; - frame_references_copy(selectedFrames); - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_CUT_FRAMES, Document::FRAMES, trackReferences, - [=](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }); - }; - - auto paste = [&]() - { - auto targetReference = reference; - auto selectedFrames = frame_references_for_current_get(); - auto clipboardString = clipboard.get(); - if (clipboardString.empty()) return; - auto targetHoveredTime = hoveredTime; - auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); - command_push([=](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetReference.animationIndex); - if (!animation) return; - if (auto item = command_item_reference_get(document, targetReference)) - { - document.tracks_snapshot(message, {targetReference}); - std::set indices{}; - std::string errorString{}; - int insertIndex = (int)item->children.size(); - std::set selectedIndices{}; - for (auto frameReference : selectedFrames) - if (is_same_item(frameReference, targetReference)) - selectedIndices.insert(frameReference.frameIndex); - - if (!selectedIndices.empty()) - insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); - else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) - insertIndex = targetReference.frameIndex + 1; - - auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; - if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) - { - if (targetReference.itemType != LAYER) - { - for (auto i : indices) - if (auto frame = track_frame_get(*item, i); frame) - { - frame->regionId = -1; - frame->crop = {}; - frame->size = {}; - frame->pivot = {}; - } - } - else if (targetReference.itemID != -1) - { - auto layer = command_layer_get(document, targetReference.itemID); - auto spritesheet = layer ? command_spritesheet_get(document, layer->spritesheetId) : nullptr; - - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame || frame->regionId == -1) continue; - auto region = - spritesheet ? element_child_id_get(*spritesheet, ElementType::REGION, frame->regionId) - : nullptr; - if (!region) frame->regionId = -1; - } - } - - std::set pastedSelection{}; - for (auto i : indices) - { - auto pastedReference = targetReference; - pastedReference.frameIndex = i; - pastedSelection.insert(pastedReference); - } - document.reference = targetReference; - document.reference.frameIndex = *indices.begin(); - document.frame_references_set(std::move(pastedSelection)); - document.anm2_change(Document::FRAMES); - } - else - { - document.snapshots.pendingStep.reset(); - toasts.push( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); - logger.error(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, - anm2ed::ENGLISH), - errorString)); - } - } - else - { - toasts.push(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION)); - logger.warning(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION, anm2ed::ENGLISH)); - } - }); - }; - - auto context_menu = [&]() - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED)) cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED)) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED)) paste(); - if (shortcut(manager.chords[SHORTCUT_SPLIT], shortcut::FOCUSED)) frame_split(); - if (shortcut(manager.chords[SHORTCUT_BAKE], shortcut::FOCUSED)) frames_bake(); - if (shortcut(manager.chords[SHORTCUT_FIT], shortcut::FOCUSED)) fit_animation_length(); - - auto make_region = [&]() - { - auto targetReference = reference; - auto frame = frame_get(); - if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; - if (frame->regionId != -1) return; - auto layer = layer_get(targetReference.itemID); - if (!layer) return; - - auto spritesheetID = layer->spritesheetId; - if (!spritesheet_get(spritesheetID)) return; - - auto settingsPtr = &settings; - command_push([=](Manager& manager, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame || frame->regionId != -1) return; - auto layer = command_layer_get(document, targetReference.itemID); - if (!layer) return; - - auto spritesheetID = layer->spritesheetId; - if (!command_spritesheet_get(document, spritesheetID)) return; - - auto region = element_make(ElementType::REGION); - region.crop = frame->crop; - region.size = frame->size; - region.pivot = frame->pivot; - region.origin = Origin::CUSTOM; - - document.spritesheet.reference = spritesheetID; - settingsPtr->windowIsRegions = true; - manager.makeRegionSpritesheetId = spritesheetID; - manager.makeRegion = region; - manager.isMakeRegionRequested = true; - }); - }; - - auto make_many_regions = [&]() - { - auto targetFrames = frame_references_for_current_get(); - std::erase_if(targetFrames, - [&](const Reference& frameReference) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, - frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; - auto layer = layer_get(frameReference.itemID); - return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); - }); - if (targetFrames.size() < 2) return; - - makeManyRegionReferences = targetFrames; - makeManyRegionsPopup.open(); - }; - - auto item = selected_item_get(); - auto frame = frame_get(); - auto selectedFrames = frame_references_for_current_get(); - auto copyFrames = copy_frame_references_get(); - auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - auto isReverseFrames = is_frames_reverse_available(selectedFrames); - auto selectedRegionFrames = selectedFrames; - std::erase_if(selectedRegionFrames, - [&](const Reference& frameReference) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, - frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; - auto layer = layer_get(frameReference.itemID); - return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); - }); - bool isMakeManyRegions = selectedRegionFrames.size() > 1; - auto selectedRootFrames = selected_root_frame_references_get(); - bool isMakeRegion = frame && reference.itemType == LAYER && reference.itemID != -1 && frame->regionId == -1 && - layer_get(reference.itemID) && spritesheet_get(layer_get(reference.itemID)->spritesheetId); - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add({.label = playback.isPlaying ? LABEL_PAUSE : LABEL_PLAY, - .shortcut = SHORTCUT_PLAY_PAUSE, - .isEnabled = []() { return true; }, - .run = [&]() { playback.toggle(); }}); - actions.add({.label = LABEL_INSERT, - .shortcut = SHORTCUT_INSERT_FRAME, - .isEnabled = [&]() { return item; }, - .run = [&]() { frame_insert(); }}); - actions.add(ACTION_DUPLICATE, [=]() { return !selectedBakeFrames.empty(); }, [&]() { frames_duplicate(); }); - actions.add({.label = LABEL_SPLIT, - .shortcut = SHORTCUT_SPLIT, - .isEnabled = [=]() { return selectedBakeFrames.size() == 1; }, - .run = [&]() { frame_split(); }}); - actions.add(ACTION_REVERSE, [=]() { return isReverseFrames; }, [&]() { frames_reverse(); }); - actions.separator(); - actions.add({.label = LABEL_BAKE, - .shortcut = SHORTCUT_BAKE, - .isEnabled = [=]() { return !selectedBakeFrames.empty(); }, - .run = [&]() { frames_bake(); }}); - actions.add({.label = LABEL_BAKE_INTO_OTHER_FRAMES, - .shortcut = -1, - .isEnabled = [=]() { 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.separator(); - actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, - .shortcut = -1, - .isEnabled = [=]() { return isMakeManyRegions || isMakeRegion; }, - .run = [&]() - { - if (isMakeManyRegions) - make_many_regions(); - else - make_region(); - }}); - actions.separator(); - actions.add({.label = LABEL_DELETE, - .shortcut = SHORTCUT_REMOVE, - .isEnabled = [=]() { return !selectedFrames.empty(); }, - .run = [&]() { frames_delete_action(); }}); - actions.separator(); - actions.add(ACTION_CUT, [=]() { return !selectedFrames.empty(); }, cut); - actions.add(ACTION_COPY, [=]() { return !copyFrames.empty(); }, copy); - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, paste); - actions_context_window_draw("##Context Menu", actions, settings); - - ImGui::PopStyleVar(2); - }; - - auto item_base_properties_open = [&](int type, int id) - { - switch (type) - { - case LAYER: - manager.layer_properties_open(id); - break; - case NULL_: - manager.null_properties_open(id); - default: - break; - }; - }; - - auto group_properties_close = [&]() - { - groupName.clear(); - groupAnimationIndex = -1; - groupType = NONE; - groupId = -1; - groupPropertiesPopup.close(); - }; - - auto group_properties_open = [&](const TimelineItemRow& row, const Element& group) - { - groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; - groupAnimationIndex = reference.animationIndex; - groupType = row.type; - groupId = row.id; - groupPropertiesPopup.open(); - }; - - auto group_properties_update = [&]() - { - groupPropertiesPopup.trigger(); - - if (ImGui::BeginPopupModal(groupPropertiesPopup.label(), &groupPropertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto childSize = child_size_get(1); - if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) - { - if (groupPropertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &groupName); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(BASIC_CONFIRM), widgetSize)) - { - auto targetName = groupName; - auto targetAnimationIndex = groupAnimationIndex; - auto targetType = groupType; - auto targetId = groupId; - edit_command_push(EDIT_RENAME_GROUP, Document::ITEMS, - [=](Manager&, Document& document) - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? element_child_first_get(*animation, container_type_get(targetType)) - : nullptr; - auto group = container ? element_child_id_get(*container, ElementType::GROUP, targetId) - : nullptr; - if (!group) return; - group->name = targetName; - }); - group_properties_close(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) group_properties_close(); - - ImGui::EndPopup(); - } - - groupPropertiesPopup.end(); - }; - - auto item_context_menu = [&]() - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - auto& type = reference.itemType; - auto& id = reference.itemID; - auto item = selected_item_get(); - auto selectedRows = selected_row_references_get(); - auto selectedGroupableItems = item_references_groupable_get(); - auto copyFrames = copy_frame_references_get(); - TimelineItemRow selectedGroupRow{}; - Element* selectedGroup{}; - if (selectedRows.size() == 1 && selectedRows.front().isGroup) - { - auto row = selectedRows.front(); - selectedGroupRow = {.type = row.type, .id = row.id, .index = row.index, .isGroup = true}; - selectedGroup = row_group_get(selectedGroupRow); - } - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) - { return row.type == LAYER || row.type == NULL_; }); - auto item_cut = [&]() - { - if (copyFrames.empty() || !isRemoveAvailable) return; - frame_references_copy(copyFrames); - item_remove(); - }; - - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && - ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Items Context Menu"); - - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add(ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, - [&]() - { - if (selectedGroup) - group_properties_open(selectedGroupRow, *selectedGroup); - else - item_base_properties_open(type, id); - }); - actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); - actions.add(ACTION_REMOVE, [=]() { return isRemoveAvailable; }, [&]() { item_remove(); }); - actions.add(ACTION_GROUP, [=]() { return !selectedGroupableItems.empty(); }, [&]() { item_group(); }); - actions.separator(); - actions.add(ACTION_CUT, [=]() { return !copyFrames.empty() && isRemoveAvailable; }, item_cut); - actions.add(ACTION_COPY, [=]() { return !copyFrames.empty(); }, copy); - actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, paste); - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED) && !copyFrames.empty() && isRemoveAvailable) - item_cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && !copyFrames.empty()) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && item && !clipboard.is_empty()) paste(); - actions_popup_draw("##Items Context Menu", actions, settings); - - ImGui::PopStyleVar(2); - }; - - auto item_child = [&](const TimelineItemRow& row, int index) - { - ImGui::PushID(index); - - auto type = row.type; - auto id = row.id; - auto row_reference_make = [&]() - { return Reference{reference.animationIndex, type, id, -1, row.rootGroupType, row.rootGroupId}; }; - if (row.isGroup) - { - auto group = row_group_get(row); - if (!group) - { - ImGui::PopID(); - return; - } - - auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; - auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); - auto isGroupVisible = group->isVisible; - auto colorVec = item_color_vec(type); - if (is_group_selected(row)) - { - if (isLightTheme) - colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; - else - colorVec = item_color_active_vec(type); - } - auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); - ImGui::PushStyleColor(ImGuiCol_ChildBg, color); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) - { - auto cursorPos = ImGui::GetCursorPos(); - auto groupChildMin = ImGui::GetWindowPos(); - auto groupChildMax = ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, - groupChildMin.y + ImGui::GetWindowSize().y); - - auto toggle_group = [&]() - { - auto targetRow = row; - auto targetAnimationIndex = reference.animationIndex; - edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, - [=](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? element_child_first_get(*animation, container_type_get(targetRow.type)) - : nullptr; - auto group = container ? element_child_id_get(*container, ElementType::GROUP, - targetRow.id) - : nullptr; - if (!group) return; - group->isExpanded = !group->isExpanded; - }); - }; - - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::InvisibleButton("##Group Button", itemSize); - auto groupButtonMin = ImGui::GetItemRectMin(); - auto groupButtonMax = ImGui::GetItemRectMax(); - auto mousePos = ImGui::GetIO().MousePos; - auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) - { return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; }; - auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); - bool isGroupTooltipDelayed{}; - if (isGroupHovered) - { - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - isGroupTooltipDelayed = - ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); - imguiStyle.HoverDelayNormal = previousTooltipDelay; - } - - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - rowDragReferences = row_drag_references_get(row); - ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), - (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); - ImGui::EndDragDropSource(); - } - - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = ImGui::AcceptDragDropPayload( - "Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) - { - auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; - auto dropZone = DropZone::BEFORE; - if (mousePos.y >= groupButtonMax.y - groupDropThird) - dropZone = DropZone::AFTER; - else if (mousePos.y >= groupButtonMin.y + groupDropThird) - dropZone = DropZone::INSIDE; - auto isDropAfter = dropZone != DropZone::BEFORE; - auto payloadRows = (TimelineRowReference*)payload->Data; - auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); - std::vector draggedRows(payloadRows, payloadRows + payloadCount); - auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); - for (auto draggedRow : draggedRows) - if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false; - - if (isDropIntoGroup) - drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); - else - drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); - - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); - } - ImGui::EndDragDropTarget(); - } - - ImGui::SetCursorPos(cursorPos); - auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; - ImGui::Image(resources.icons[folderIcon].id, icon_size_get()); - auto iconMin = ImGui::GetItemRectMin(); - auto iconMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[folderIcon].id, itemIconTint); - ImGui::SameLine(); - - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) - { - auto targetAnimationIndex = reference.animationIndex; - auto targetType = type; - auto targetGroupId = group->id; - auto targetVisible = !isGroupVisible; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=](Manager&, Document& document) - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? element_child_first_get(*animation, container_type_get(targetType)) - : nullptr; - if (!container) return; - auto group = element_child_id_get(*container, ElementType::GROUP, targetGroupId); - if (!group) return; - group->isVisible = targetVisible; - }); - } - auto visibleButtonMin = ImGui::GetItemRectMin(); - auto visibleButtonMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[visibleIcon].id, itemIconTint); - ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - - auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); - auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); - if (isGroupTooltipDelayed && !isVisibleButtonHovered) - { - ImGui::BeginTooltip(); - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - 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); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); - ImGui::EndTooltip(); - } - if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - toggle_group(); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - group_properties_open(row, *group); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); - } - ImGui::EndChild(); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(); - ImGui::PopID(); - return; - } - - auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); - if (type != NONE && !item) - { - ImGui::PopID(); - return; - } - auto isItemVisible = item ? item->isVisible : false; - auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; - if (item && type == ROOT && row.rootGroupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); - auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; - auto isReferenced = is_same_item(reference, row_reference_make()); - auto isItemSelected = is_row_selected(row); - - auto label = [&]() -> std::string - { - if (type == LAYER) - { - auto layer = layer_get(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 = null_get(id); - if (!null) return localize.get(TYPE_STRINGS[type]); - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); - } - return localize.get(TYPE_STRINGS[type]); - }(); - auto icon = TYPE_ICONS[type]; - auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint; - auto baseColorVec = item_color_vec(type); - auto activeColorVec = item_color_active_vec(type); - auto colorVec = baseColorVec; - if (isItemSelected && type != NONE) - { - if (isLightTheme) - colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; - else - colorVec = activeColorVec; - } - auto color = to_imvec4(colorVec); - color = !isVisible ? to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER) : color; - ImGui::PushStyleColor(ImGuiCol_ChildBg, color); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); - - if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) - { - auto cursorPos = ImGui::GetCursorPos(); - auto itemChildMin = ImGui::GetWindowPos(); - auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); - - if (type != NONE) - { - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::SetNextItemStorageID(id); - ImGui::InvisibleButton("##Item Button", itemSize); - auto itemButtonMin = ImGui::GetItemRectMin(); - auto itemButtonMax = ImGui::GetItemRectMax(); - auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - - if (type == LAYER || type == NULL_) - { - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - rowDragReferences = row_drag_references_get(row); - ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), - (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); - ImGui::EndDragDropSource(); - } - - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = ImGui::AcceptDragDropPayload( - "Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) - { - auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); - drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); - - auto payloadRows = (TimelineRowReference*)payload->Data; - auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); - std::vector draggedRows(payloadRows, payloadRows + payloadCount); - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter); - } - ImGui::EndDragDropTarget(); - } - } - - if (isItemButtonHovered) - { - if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) item_base_properties_open(type, id); - else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); - - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | - ImGuiHoveredFlags_NoSharedDelay; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - bool showItemTooltip = ImGui::BeginItemTooltip(); - imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; - imguiStyle.HoverDelayNormal = previousTooltipDelay; - - if (showItemTooltip) - { - auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); }; - auto visibleLabel = yesNoLabel(isVisible); - auto framesCount = item_frames_count(item); - - switch (type) - { - case ROOT: - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_ROOT)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - auto transformLabel = yesNoLabel(settings.previewIsRootTransform); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case LAYER: - { - auto layer = layer_get(id); - if (!layer) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(layer->name.c_str()); - ImGui::PopFont(); - - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)) - .c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case NULL_: - { - auto nullInfo = null_get(id); - if (!nullInfo) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(nullInfo->name.c_str()); - ImGui::PopFont(); - - auto rectLabel = yesNoLabel(nullInfo->isShowRect); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case TRIGGER: - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - default: - break; - } - - ImGui::EndTooltip(); - } - } - - auto contentCursorPos = cursorPos; - contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); - ImGui::SetCursorPos(contentCursorPos); - - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintCurrent); - ImGui::SameLine(); - if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); - if (isReferenced) ImGui::PopFont(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) - { - auto animationIndex = reference.animationIndex; - auto targetType = type; - auto targetID = id; - auto targetGroupType = row.rootGroupType; - auto targetGroupId = row.rootGroupId; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=](Manager&, Document& document) - { - auto item = command_item_get(document, animationIndex, targetType, targetID, - targetGroupType, targetGroupId); - if (!item) return; - item->isVisible = !item->isVisible; - }); - } - overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent); - ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); - - if (type == NULL_) - { - if (auto null = null_get(id)) - { - auto& isShowRect = null->isShowRect; - auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; - ImGui::SetCursorPos( - ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get())) - { - auto nullID = id; - edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, - [=](Manager&, Document& document) - { - auto nulls = document.anm2.element_get(ElementType::NULLS); - auto null = nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) - : nullptr; - if (!null) return; - null->isShowRect = !null->isShowRect; - }); - } - overlay_icon(resources.icons[rectIcon].id, iconTintCurrent); - ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) - : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); - } - } - - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - } - else - { - auto cursorPos = ImGui::GetCursorPos(); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - - auto& isShowUnused = settings.timelineIsShowUnused; - auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; - if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get())) - isShowUnused = !isShowUnused; - overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent); - ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) - : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); - - auto& showLayersOnly = settings.timelineIsOnlyShowLayers; - auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS; - ImGui::SetCursorPos( - ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get())) - showLayersOnly = !showLayersOnly; - overlay_icon(resources.icons[layersIcon].id, iconTintCurrent); - ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) - : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - - ImGui::SetCursorPos(cursorPos); - - ImGui::BeginDisabled(); - ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - ImGui::Text("(?)"); - ImGui::PopStyleColor(); - auto tooltipShortcuts = std::vformat( - localize.get(TOOLTIP_TIMELINE_SHORTCUTS), - std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, - settings.shortcutShortenFrame, settings.shortcutExtendFrame, - settings.shortcutPreviousFrame, settings.shortcutNextFrame, - settings.shortcutPreviousItem, settings.shortcutNextItem)); - ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); - ImGui::EndDisabled(); - } - } - ImGui::EndChild(); - ImGui::PopStyleColor(); - ImGui::PopStyleVar(2); - - ImGui::PopID(); - }; - - auto items_child = [&]() - { - auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - bool isItemsChildOpen = ImGui::BeginChild("##Items Child", itemsChildSize, ImGuiChildFlags_Borders); - ImGui::PopStyleVar(); - if (isItemsChildOpen) - { - auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - - ImGui::GetTextLineHeightWithSpacing() - - ImGui::GetStyle().ItemSpacing.y * 2); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) - { - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - auto rowReferences = timeline_row_references_get(); - row_selection_clear(); - for (auto rowReference : rowReferences) - row_selection_insert(rowReference); - if (!rowReferences.empty()) - { - rowSelectionAnchor = rowReferences.front(); - isRowSelectionAnchorSet = true; - } - frames_selection_reset_for(document); - } - - if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) && - !item_references_groupable_get().empty()) - item_group(); - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); - if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) - { - ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::SetScrollY(scroll.y); - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Items"); - - auto item_child_row = [&](const TimelineItemRow& row, int index) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - item_child(row, index); - }; - - int index{}; - item_child_row({.type = NONE}, index++); - if (animation) - for (const auto& row : timeline_item_rows_get()) - item_child_row(row, index++); - - if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); - } - - ImGui::EndTable(); - } - ImGui::PopStyleVar(2); - - item_context_menu(); - } - ImGui::PopStyleVar(2); - ImGui::EndChild(); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); - auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); - - ImGui::BeginDisabled(!animation); - { - shortcut(manager.chords[SHORTCUT_ADD]); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); - ImGui::SameLine(); - - auto selectedRows = selected_row_references_get(); - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) - { return row.type == LAYER || row.type == NULL_; }); - ImGui::BeginDisabled(!isRemoveAvailable); - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); - ImGui::EndDisabled(); - } - ImGui::EndDisabled(); - - ImGui::PopStyleVar(); - } - ImGui::EndChild(); - }; - - int frameMoveDropType = NONE; - int frameMoveDropItemID = -1; - int frameMoveDropGroupType = NONE; - int frameMoveDropGroupId = -1; - int frameMoveDropIndex = -1; - bool isFrameMoveDropTarget = false; - - auto frame_move_drag_clear = [&]() - { - frameMoveDrag = {}; - frameSelectionLocked.clear(); - frameMoveDropType = NONE; - frameMoveDropItemID = -1; - frameMoveDropGroupType = NONE; - frameMoveDropGroupId = -1; - frameMoveDropIndex = -1; - isFrameMoveDropTarget = false; - }; - - auto frames_move_to = [&](int targetType, int targetID, int targetGroupType, int targetGroupId, int insertIndex) - { - if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) return; - if (targetType == TRIGGER) return; - - auto drag = frameMoveDrag; - std::erase_if(drag.references, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); - if (drag.references.empty() && drag.frameIndex >= 0) - drag.references.push_back( - {drag.animationIndex, drag.type, drag.itemID, drag.frameIndex, drag.groupType, drag.groupId}); - std::erase_if(drag.references, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); - if (drag.references.empty()) return; - - auto trackReferences = track_references_from_frame_references_get( - std::set(drag.references.begin(), drag.references.end())); - trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); - tracks_edit_command_push(EDIT_MOVE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - auto targetItem = - command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, - targetGroupId); - if (!targetItem) return; - - std::map> groupedFrames{}; - for (auto frameReference : drag.references) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - int removedBeforeTarget = 0; - std::vector movedFrames; - for (auto& [itemReference, indices] : groupedFrames) - { - auto sourceItem = command_item_reference_get(document, itemReference); - if (!sourceItem) continue; - - for (auto i : indices) - { - auto childIndex = item_frame_child_index_get(*sourceItem, i); - if (childIndex == -1) continue; - movedFrames.push_back(std::move(sourceItem->children[childIndex])); - if (itemReference.itemType == targetType && itemReference.itemID == targetID && - itemReference.groupType == targetGroupType && itemReference.groupId == targetGroupId && - i < insertIndex) - ++removedBeforeTarget; - } - - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*sourceItem, *it); - if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); - } - } - - if (movedFrames.empty()) return; - - int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); - desired -= removedBeforeTarget; - desired = std::clamp(desired, 0, item_frames_count(targetItem)); - - auto insertPosResult = desired; - auto insertedCount = (int)movedFrames.size(); - auto childIndex = item_frame_insert_index_get(*targetItem, insertPosResult); - targetItem->children.insert(targetItem->children.begin() + childIndex, - std::make_move_iterator(movedFrames.begin()), - std::make_move_iterator(movedFrames.end())); - - if (insertedCount <= 0) return; - - std::set movedSelection{}; - for (int offset = 0; offset < insertedCount; ++offset) - movedSelection.insert({drag.animationIndex, targetType, targetID, insertPosResult + offset, - targetGroupType, targetGroupId}); - - document.reference = {drag.animationIndex, targetType, targetID, insertPosResult, - targetGroupType, targetGroupId}; - document.frame_references_set(std::move(movedSelection)); - document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); - frameSelectionSnapshot.assign(document.frames.selection.begin(), - document.frames.selection.end()); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - if (targetType == LAYER) - if (auto layer = command_layer_get(document, targetID)) - document.spritesheet.reference = layer->spritesheetId; - }); - }; - - float playheadLineCenterX{}; - float playheadLineTopY{}; - bool isPlayheadLineSet{}; - ImVec2 frameBoxClipMin{}; - ImVec2 frameBoxClipMax{}; - bool isFrameBoxClipSet{}; - auto frame_box_content_point_get = [&]() - { - auto mousePos = ImGui::GetIO().MousePos; - return ImVec2(mousePos.x + scroll.x - frameBoxClipMin.x, mousePos.y + scroll.y - frameBoxClipMin.y); - }; - auto frame_box_screen_point_get = [&](ImVec2 point) - { return ImVec2(point.x - scroll.x + frameBoxClipMin.x, point.y - scroll.y + frameBoxClipMin.y); }; - auto is_frame_box_overlapping = [](ImVec2 leftMin, ImVec2 leftMax, ImVec2 rightMin, ImVec2 rightMax) - { - return leftMin.x <= rightMax.x && leftMax.x >= rightMin.x && leftMin.y <= rightMax.y && - leftMax.y >= rightMin.y; - }; - auto frame_overlay_draw = [&](ImDrawList* drawList, ImVec2 clipMin, ImVec2 clipMax) - { - if (isFrameBoxSelecting && isFrameBoxClipSet) - { - auto boxContentMin = - ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxContentMax = - ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto boxMin = frame_box_screen_point_get(boxContentMin); - auto boxMax = frame_box_screen_point_get(boxContentMax); - auto boxClipMin = clipMin; - if (isPlayheadLineSet) boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); - drawList->PushClipRect(boxClipMin, clipMax, true); - drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); - drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); - drawList->PopClipRect(); - } - - if (isPlayheadLineSet) - { - auto lineTopY = std::max(clipMin.y, playheadLineTopY); - if (clipMax.y > lineTopY) - { - auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); - auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); - drawList->PushClipRect(clipMin, clipMax, true); - drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), - ImGui::GetColorU32(playheadLineColor)); - drawList->PopClipRect(); - } - } - }; - - auto frame_child = [&](const TimelineItemRow& row, int& index, float width) - { - auto type = row.type; - auto id = row.id; - auto row_reference_make = [&](int frameIndex = -1) - { return Reference{reference.animationIndex, type, id, frameIndex, row.rootGroupType, row.rootGroupId}; }; - auto childSize = ImVec2(width, rowFrameChildHeight); - if (row.isGroup) - { - auto group = row_group_get(row); - if (!group) return; - - ImGui::PushID(index); - ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); - ImGui::EndChild(); - index++; - ImGui::PopID(); - return; - } - - auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); - if (type != NONE && !item) return; - - auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; - if (item && type == ROOT && row.rootGroupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); - auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; - - auto colorVec = type_color_base_vec(type); - auto colorActiveVec = type_color_active_vec(type); - auto colorHoveredVec = type_color_hovered_vec(type); - auto color = to_imvec4(colorVec); - auto colorActive = to_imvec4(colorActiveVec); - auto colorHovered = to_imvec4(colorHoveredVec); - auto colorHidden = to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER); - auto colorActiveHidden = to_imvec4(colorActiveVec * COLOR_HIDDEN_MULTIPLIER); - auto colorHoveredHidden = to_imvec4(colorHoveredVec * COLOR_HIDDEN_MULTIPLIER); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::PopStyleVar(2); - - ImGui::PushID(index); - - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - bool isDefaultChild = type == NONE; - if (isLightTheme && isDefaultChild) ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); - - bool isFramesChildVisible = ImGui::BeginChild("##Frames Child", childSize, ImGuiChildFlags_Borders); - auto drawList = ImGui::GetWindowDrawList(); - auto clipMax = drawList->GetClipRectMax(); - auto length = animation ? animation->frameNum : 0; - auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); - auto framesSize = ImVec2(frameSize.x * length, frameSize.y); - auto cursorPos = ImGui::GetCursorPos(); - auto cursorScreenPos = ImGui::GetCursorScreenPos(); - if (frameSize.x > 0.0f && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) - { - auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; - frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); - } - auto border = glm::max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f); - auto borderLineLength = frameSize.y / 5; - auto frameMin = std::max(0, (int)std::floor(scroll.x / frameSize.x) - 1); - auto frameMax = std::min(FRAME_NUM_MAX, (int)std::ceil((scroll.x + clipMax.x) / frameSize.x) + 1); - - if (isFrameBoxSelecting && isFrameBoxClipSet && type != NONE && animation && item) - { - auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; - auto rowMaxY = rowMinY + childSize.y; - float selectionFrameTime{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (const auto& frame : item->children) - { - 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; - auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); - auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); - if (is_frame_box_overlapping(frameContentMin, frameContentMax, boxMin, boxMax)) - frameBoxSelection.insert(frameReference); - if (type != TRIGGER) selectionFrameTime += frame.duration; - ++frameIndex; - } - } - - if (isFramesChildVisible) - { - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) - { - if (!frames.references.empty() || !frames.selection.empty()) - { - reference.frameIndex = -1; - frames_selection_reset_for(document); - } - else if (reference.itemType != NONE || reference.itemID != -1) - reference_clear(); - } - - if (type == NONE) - { - if (length > 0) - { - if (isLightTheme) - { - auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); - drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); - float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(timelinePlayheadRectColor)); - } - else - { - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); - } - } - - for (int i = frameMin; i < frameMax; i++) - { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - - drawList->AddRect(frameScreenPos, ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); - - drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), - ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); - - if (i % FRAME_MULTIPLE == 0) - { - auto string = std::to_string(i); - auto textSize = ImGui::CalcTextSize(string.c_str()); - auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, - frameScreenPos.y + (frameSize.y - textSize.y) / 2); - - drawList->AddRectFilled(frameScreenPos, - ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(frameMultipleOverlayColor)); - - drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); - } - } - - if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left)) - { - playback_stop(); - isDragging = true; - } - - auto childPos = ImGui::GetWindowPos(); - auto mousePos = ImGui::GetIO().MousePos; - auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); - hoveredTime = floorf(localMousePos.x / frameSize.x); - - if (isDragging) - { - playback.time = hoveredTime; - playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - if (!playback.isPlaying) playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; - - if (length > 0) - { - ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); - ImGui::Image(resources.icons[icon::PLAYHEAD].id, frameSize); - auto playheadMin = ImGui::GetItemRectMin(); - auto playheadMax = ImGui::GetItemRectMax(); - playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; - playheadLineTopY = playheadMax.y; - isPlayheadLineSet = true; - overlay_icon(resources.icons[icon::PLAYHEAD].id, playheadIconTint, true); - } - } - else if (animation) - { - float frameTime{}; - - for (int i = frameMin; i < frameMax; i++) - { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); - - drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); - - if (i % FRAME_MULTIPLE == 0) - drawList->AddRectFilled(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameMultipleOverlayColor)); - } - - if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && - ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) - { - isFrameBoxPending = true; - isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); - frameBoxStart = frame_box_content_point_get(); - frameBoxEnd = frameBoxStart; - frameBoxSelection.clear(); - } - - bool isFrameMovePreview = false; - ImVec2 frameMovePreviewMin{}; - ImVec2 frameMovePreviewMax{}; - bool isFrameMoveHoveredFrame = false; - ImVec2 frameMoveHoveredFrameMin{}; - ImVec2 frameMoveHoveredFrameMax{}; - - if (frameMoveDrag.isActive && type != TRIGGER) - { - auto mousePos = ImGui::GetIO().MousePos; - auto rowMin = cursorScreenPos; - auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); - if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) - { - auto mouseX = mousePos.x - cursorScreenPos.x; - auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = item_frames_count(item); - float dropFrameTime{}; - float frameTime{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = frameTime; - auto frameEnd = frameStart + frame.duration; - if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) - { - isFrameMoveHoveredFrame = true; - frameMoveHoveredFrameMin = ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); - frameMoveHoveredFrameMax = - ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); - } - - auto midpoint = frameStart + ((float)frame.duration * 0.5f); - if (targetTime < midpoint) - { - dropIndex = frameIndex; - dropFrameTime = frameStart; - break; - } - - frameTime = frameEnd; - dropFrameTime = frameTime; - ++frameIndex; - } - - frameMoveDropType = type; - frameMoveDropItemID = id; - frameMoveDropGroupType = row.rootGroupType; - frameMoveDropGroupId = row.rootGroupId; - frameMoveDropIndex = dropIndex; - isFrameMoveDropTarget = true; - - auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; - auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); - frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); - frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); - isFrameMovePreview = true; - } - } - - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) - { - auto& frame = item->children[childIndex]; - if (frame.type != frameType) continue; - ImGui::PushID(childIndex); - - auto frameReference = row_reference_make(frameIndex); - auto isFrameVisible = isVisible && frame.isVisible; - auto isReferenced = reference == frameReference; - auto isSelected = frames.references.contains(frameReference) || - (frames.references.empty() && frames.selection.contains(frameIndex) && - reference.itemType == type && reference.itemID == id && - reference.groupType == row.rootGroupType && reference.groupId == row.rootGroupId); - - if (type == TRIGGER) frameTime = frame.atFrame; - - auto buttonSize = type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); - auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; - auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; - if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) - { - if (type != TRIGGER) frameTime += frame.duration; - ImGui::PopID(); - ++frameIndex; - continue; - } - auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); - - if (frameFocusRequested && frameFocusIndex == frameIndex && reference == frameReference) - frameFocusRequested = false; - - ImGui::SetCursorPos(buttonPos); - - auto buttonScreenPos = ImGui::GetCursorScreenPos(); - auto fillColor = isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) - : (isFrameVisible ? color : colorHidden); - drawList->AddRectFilled(buttonScreenPos, - ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), - ImGui::GetColorU32(fillColor), FRAME_ROUNDING); - - ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); - ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); - - ImGui::SetNextItemAllowOverlap(); - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); - ImGui::SetNextItemSelectionUserData(frameIndex); - bool isDifferentItem = !is_same_item(reference, frameReference); - if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) - { - if (type == LAYER) - if (auto layer = layer_get(id)) document.spritesheet.reference = layer->spritesheetId; - - if (type != TRIGGER) - { - if (ImGui::IsKeyDown(ImGuiMod_Alt)) - { - auto targetReference = frameReference; - frames_edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, {targetReference}, - [=](Manager&, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame) return; - frame->interpolation = frame->interpolation == Interpolation::NONE - ? Interpolation::LINEAR - : Interpolation::NONE; - }); - } - - document.frameTime = frameTime; - } - - auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); - auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); - if (isShiftDown) - { - auto isHadAnchor = isFrameSelectionAnchorSet; - auto anchorReference = isHadAnchor ? frameSelectionAnchor : frameReference; - auto isRangeSelected = - frame_selection_range_set_for(document, anchorReference, frameReference, isCtrlDown); - if (!isRangeSelected) frame_selection_set_for(document, frameReference); - if (!isHadAnchor || !isRangeSelected) frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - else if (isCtrlDown) - { - frame_selection_toggle_for(document, frameReference); - frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - else - { - frame_selection_set_for(document, frameReference); - frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - reference = frameReference; - isReferenced = true; - region.reference = -1; - region.selection.clear(); - if (isDifferentItem) frames_selection_sync_for(document); - } - ImGui::PopStyleVar(); - - ImGui::PopStyleColor(4); - - if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) - { - if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) - { - if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) - { - isDraggedFrameActive = true; - draggedFrameReference = frameReference; - draggedFrameType = type; - draggedFrameIndex = frameIndex; - draggedFrameStart = hoveredTime; - if (type != TRIGGER) draggedFrameStartDuration = frame.duration; - draggedFrameStartDurations.clear(); - if (type != TRIGGER) - { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, [](const Reference& selectedReference) - { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; - for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) - draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); - } - } - draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; - draggedFrameWidth = frameSize.x; - } - } - } - - if (type != TRIGGER) - { - if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && - ImGui::IsMouseDragging(ImGuiMouseButton_Left)) - { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, [](const Reference& selectedReference) - { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; - int dragDuration = 0; - for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) dragDuration += selectedFrame->duration; - } - dragDuration = glm::max(1, dragDuration); - - frameMoveDrag = { - .type = type, - .itemID = id, - .animationIndex = reference.animationIndex, - .groupType = row.rootGroupType, - .groupId = row.rootGroupId, - .frameIndex = frameIndex, - .duration = dragDuration, - .indices = {}, - .references = {selectedReferences.begin(), selectedReferences.end()}, - .isActive = true, - }; - } - } - - auto rectMin = ImGui::GetItemRectMin(); - auto rectMax = ImGui::GetItemRectMax(); - auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; - auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; - drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); - - auto icon = icon::UNINTERPOLATED; - if (type == TRIGGER) - icon = icon::TRIGGER; - else - { - switch (frame.interpolation) - { - case Interpolation::NONE: - icon = icon::UNINTERPOLATED; - break; - case Interpolation::LINEAR: - icon = icon::INTERPOLATED; - break; - case Interpolation::EASE_IN: - icon = icon::EASE_IN; - break; - case Interpolation::EASE_OUT: - icon = icon::EASE_OUT; - break; - case Interpolation::EASE_IN_OUT: - icon = icon::EASE_IN_OUT; - break; - default: - icon = icon::UNINTERPOLATED; - break; - } - } - auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), - cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); - ImGui::SetCursorPos(iconPos); - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintDefault); - - if (type != TRIGGER) frameTime += frame.duration; - - ImGui::PopID(); - ++frameIndex; - } - - if (isFrameMovePreview) - { - drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, - ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); - drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), - FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); - } - - if (isFrameMoveHoveredFrame) - drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, - ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, - ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); - - if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && - (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && - !ImGui::IsAnyItemHovered()) - row_selection_set(row); - - if (isFrameSelectionLocked) - { - std::set lockedSelection{}; - for (int idx : frameSelectionLocked) - lockedSelection.insert(row_reference_make(idx)); - document.frame_references_set(std::move(lockedSelection)); - isFrameSelectionLocked = false; - frameSelectionLocked.clear(); - } - if (reference.itemType == type && reference.itemID == id && reference.groupType == row.rootGroupType && - reference.groupId == row.rootGroupId) - { - frameSelectionSnapshot.assign(frames.selection.begin(), frames.selection.end()); - frameSelectionSnapshotReference = reference; - } - } - - } - - if (isDraggedFrameActive) - { - ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); - auto durationDelta = draggedFrameWidth > 0.0f - ? static_cast((ImGui::GetIO().MousePos.x - draggedFrameStartMouseX) / - draggedFrameWidth) - : hoveredTime - draggedFrameStart; - auto isDraggedFrameChanged = - draggedFrameType == TRIGGER ? hoveredTime != draggedFrameStart : durationDelta != 0; - - if (!isDraggedFrameSnapshot && isDraggedFrameChanged) - { - isDraggedFrameSnapshot = true; - if (draggedFrameType == TRIGGER) - tracks_snapshot_command_push(EDIT_TRIGGER_AT_FRAME, {item_reference_from_frame_get(draggedFrameReference)}); - else - { - std::set draggedFrameReferences{}; - if (draggedFrameStartDurations.empty()) - draggedFrameReferences.insert(draggedFrameReference); - else - for (auto& frameDuration : draggedFrameStartDurations) - draggedFrameReferences.insert(frameDuration.reference); - frames_snapshot_command_push(EDIT_FRAME_DURATION, draggedFrameReferences); - } - } - - if (isDraggedFrameSnapshot) - { - auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - auto targetIndex = draggedFrameIndex; - auto targetStartDuration = draggedFrameStartDuration; - auto targetStartDurations = draggedFrameStartDurations; - auto targetHoveredTime = hoveredTime; - auto targetDurationDelta = durationDelta; - auto isPlaybackClamp = settings.playbackIsClamp; - auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; - command_push([=](Manager&, Document& document) - { - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - if (!item || !frame) return; - - if (targetType == TRIGGER) - { - frame->atFrame = - glm::clamp(targetHoveredTime, 0, - isPlaybackClamp ? animationLength - 1 : FRAME_NUM_MAX - 1); - - for (auto [i, trigger] : std::views::enumerate(item->children)) - { - if ((int)i == targetIndex) continue; - if (trigger.atFrame == frame->atFrame) frame->atFrame--; - } - } - else - { - if (targetStartDurations.empty()) - { - frame->duration = glm::clamp(targetStartDuration + targetDurationDelta, - FRAME_DURATION_MIN, FRAME_DURATION_MAX); - return; - } - - for (auto frameDuration : targetStartDurations) - { - auto targetFrame = command_frame_get(document, frameDuration.reference); - if (!targetFrame) continue; - targetFrame->duration = glm::clamp(frameDuration.duration + targetDurationDelta, - FRAME_DURATION_MIN, FRAME_DURATION_MAX); - } - } - }); - } - - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - command_push([=](Manager&, Document& document) - { - auto item = command_item_reference_get(document, targetReference); - if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); - document.anm2_change(Document::FRAMES); - }); - isDraggedFrameActive = false; - draggedFrameReference = {}; - draggedFrameType = NONE; - draggedFrameIndex = -1; - draggedFrameStart = -1; - draggedFrameStartDuration = -1; - draggedFrameStartDurations.clear(); - draggedFrameStartMouseX = 0.0f; - draggedFrameWidth = 0.0f; - isDraggedFrameSnapshot = false; - frameSelectionLocked.clear(); - } - } - - context_menu(); - - ImGui::EndChild(); - if (isLightTheme && isDefaultChild) ImGui::PopStyleColor(); - ImGui::PopStyleVar(); - - index++; - ImGui::PopID(); - }; - - auto frames_child = [&]() - { - auto cursorPos = ImGui::GetCursorPos(); - ImGui::SetCursorPos(ImVec2(cursorPos.x + ITEM_CHILD_WIDTH, cursorPos.y)); - - auto framesChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y); - - if (ImGui::BeginChild("##Frames Child", framesChildSize, ImGuiChildFlags_Borders)) - { - auto viewListChildSize = - ImVec2(ImGui::GetContentRegionAvail().x, - ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); - - 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)); - return length; - }(); - auto childWidth = animationsLength * ImGui::GetTextLineHeight(); - if (animation && animation->frameNum > animationsLength) - childWidth = animation->frameNum * ImGui::GetTextLineHeight(); - childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); - - childWidth *= WIDTH_MULTIPLIER; - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) - { - playheadLineCenterX = 0.0f; - playheadLineTopY = 0.0f; - isPlayheadLineSet = false; - isFrameBoxClipSet = false; - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) - { - group_selection_reset_for(document); - document.frame_references_set(all_frame_references_for_items_get()); - if (!document.frames.references.empty()) - frames_selection_sync_for(document); - } - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - if (ImGui::BeginTable("##Frames List Table", 1, - ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) - { - ImGuiWindow* window = ImGui::GetCurrentWindow(); - window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - - scroll.x = ImGui::GetScrollX(); - scroll.y = ImGui::GetScrollY(); - - isHorizontalScroll = window->ScrollbarX; - - if (isWindowHovered) - { - auto& io = ImGui::GetIO(); - auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; - - scroll.x -= io.MouseWheelH * lineHeight; - scroll.y -= io.MouseWheel * lineHeight; - } - - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - - auto frameBoxDrawList = ImGui::GetWindowDrawList(); - frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); - frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); - isFrameBoxClipSet = true; - if (isFrameBoxPending || isFrameBoxSelecting) - { - auto& io = ImGui::GetIO(); - auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; - frameBoxEnd = frame_box_content_point_get(); - auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); - if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) - { - isFrameBoxPending = false; - isFrameBoxSelecting = true; - } - auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); - auto scrollStep = edgeSize * 0.5f; - if (isFrameBoxSelecting) - { - if (io.MousePos.x < frameBoxClipMin.x + edgeSize) - scroll.x -= scrollStep; - else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) - scroll.x += scrollStep; - if (io.MousePos.y < frameBoxClipMin.y + edgeSize) - scroll.y -= scrollStep; - else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) - scroll.y += scrollStep; - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - frameBoxEnd = frame_box_content_point_get(); - frameBoxSelection.clear(); - } - } - - int index{}; - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Frames"); - - auto frames_child_row = [&](const TimelineItemRow& row) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - frame_child(row, index, childWidth); - }; - - frames_child_row({.type = NONE}); - - if (animation) - { - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); - - for (const auto& row : timeline_item_rows_get()) - frames_child_row(row); - - ImGui::PopStyleVar(); - } - ImGui::EndTable(); - } - - if (isFrameBoxClipSet) - { - auto overlayCursor = ImGui::GetCursorScreenPos(); - auto overlayPos = ImGui::GetWindowPos(); - auto overlaySize = ImGui::GetWindowSize(); - ImGui::SetCursorScreenPos(overlayPos); - if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) - frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); - ImGui::EndChild(); - ImGui::SetCursorScreenPos(overlayCursor); - } - - if (isFrameBoxPending || isFrameBoxSelecting) - { - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - if (isFrameBoxSelecting) - { - group_selection_reset_for(document); - if (isFrameBoxAdditive) - { - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); - document.frame_references_set(std::move(selectedFrames)); - } - else - document.frame_references_set(frameBoxSelection); - frames_selection_sync_for(document); - } - isFrameBoxPending = false; - isFrameBoxSelecting = false; - frameBoxSelection.clear(); - } - } - - ImGui::PopStyleVar(); - } - ImGui::EndChild(); - ImGui::PopStyleVar(); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::SetCursorPos( - ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); - - auto widgetSize = widget_size_with_row_get(10); - - ImGui::BeginDisabled(!animation); - { - auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); - auto tooltip = - playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); - - shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); - if (ImGui::Button(label, widgetSize)) playback.toggle(); - set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); - - ImGui::SameLine(); - - auto item = selected_item_get(); - auto selectedFrames = frame_references_for_current_get(); - auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER; }); - - ImGui::BeginDisabled(!item); - { - shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); - if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) frame_insert(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selectedFrames.empty()); - { - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) frames_delete_action(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selectedBakeFrames.empty()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) bakePopup.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); - ImGui::EndDisabled(); - } - ImGui::EndDisabled(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - - ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); - shortcut(manager.chords[SHORTCUT_FIT]); - if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) fit_animation_length(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); - ImGui::EndDisabled(); - - ImGui::SameLine(); - - auto frameNum = animation ? animation->frameNum : dummy_value(); - auto currentAnimationIndex = reference.animationIndex; - ImGui::SetNextItemWidth(widgetSize.x); - auto isLengthChanged = input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, - FRAME_NUM_MAX, STEP, STEP_FAST, - !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); - if (ImGui::IsItemActivated()) animationLengthEditIndex = currentAnimationIndex; - if (isLengthChanged && animation) - { - auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; - edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->frameNum = frameNum; - }); - } - if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); - - ImGui::SameLine(); - - auto isLoop = animation ? animation->isLoop : dummy_value(); - ImGui::SetNextItemWidth(widgetSize.x); - if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) - { - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_LOOP, Document::ANIMATIONS, - [=](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->isLoop = isLoop; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - - auto info = info_get(); - auto fps = info ? info->fps : 30; - ImGui::SetNextItemWidth(widgetSize.x); - if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) - { - edit_command_push(EDIT_FPS, Document::INFO, - [=](Manager&, Document& document) - { - auto info = command_info_get(document); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->fps = fps; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); - - ImGui::SameLine(); - - info = info_get(); - auto createdBy = info ? info->createdBy : std::string{}; - ImGui::SetNextItemWidth(widgetSize.x); - if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) - { - edit_command_push(EDIT_AUTHOR, Document::INFO, - [=](Manager&, Document& document) - { - auto info = command_info_get(document); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->createdBy = createdBy; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); - - ImGui::SameLine(); - - ImGui::SetNextItemWidth(widgetSize.x); - ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); - - ImGui::PopStyleVar(); - } - ImGui::EndChild(); - - ImGui::SetCursorPos(cursorPos); - }; - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline)) - { - isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | - ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - frames_child(); - if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - if (isFrameMoveDropTarget) - frames_move_to(frameMoveDropType, frameMoveDropItemID, frameMoveDropGroupType, frameMoveDropGroupId, - frameMoveDropIndex); - frame_move_drag_clear(); - } - items_child(); - } - ImGui::PopStyleVar(); - ImGui::End(); - - if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document); - group_properties_update(); - - makeManyRegionsPopup.trigger(); - if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); - ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); - - auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(LABEL_MAKE_MANY_REGIONS), widgetSize)) - { - auto targetFrames = makeManyRegionReferences; - auto format = settings.generateRegionNameFormat; - auto mapping = isMakeManyRegionsMapFrames ? Document::RegionFrameMapping::SET - : Document::RegionFrameMapping::PRESERVE; - edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, - [=](Manager&, Document& document) mutable - { document.regions_generate_from_frames(targetFrames, format, mapping); }); - makeManyRegionsPopup.close(); - } - - ImGui::SameLine(); - - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) makeManyRegionsPopup.close(); - - ImGui::EndPopup(); - } - makeManyRegionsPopup.end(); - - bakePopup.trigger(); - - if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto& interval = settings.bakeInterval; - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; - - auto frame = frame_get(); - - input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, - frame ? frame->duration : FRAME_DURATION_MIN); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - frames_bake(); - bakePopup.close(); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - - ImGui::EndPopup(); - } - - bakeIntoOtherFramesPopup.trigger(); - - if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen, - ImGuiWindowFlags_NoResize)) - { - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; - auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto& isUseRootPivot = settings.bakeIsUseRootPivot; - int target = (int)bakeIntoOtherFramesTarget; - ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, - (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); - bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; - - auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; - ImGui::BeginDisabled(isCurrentSelection); - ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); - ImGui::EndDisabled(); - - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - - ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); - - ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - bake_into_other_frames(); - bakeIntoOtherFramesPopup.close(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - - ImGui::EndPopup(); - } - - if (animation) - { - if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); - - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) - { - playback_stop(); - playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL)) - { - playback_stop(); - playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - static bool isShortenChordHeld = false; - auto isShortenFrame = shortcut(manager.chords[SHORTCUT_SHORTEN_FRAME], shortcut::GLOBAL); - - if (isShortenFrame) - { - - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (!selectedFrames.empty()) - { - if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames); - command_push([=](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); - } - document.anm2_change(Document::FRAMES); - }); - } - } - isShortenChordHeld = isShortenFrame; - - static bool isExtendChordHeld = false; - auto isExtendFrame = shortcut(manager.chords[SHORTCUT_EXTEND_FRAME], shortcut::GLOBAL); - if (isExtendFrame) - { - - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (!selectedFrames.empty()) - { - if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames); - command_push([=](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); - } - document.anm2_change(Document::FRAMES); - }); - } - } - isExtendChordHeld = isExtendFrame; - - auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], shortcut::GLOBAL); - auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], shortcut::GLOBAL); - auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], shortcut::GLOBAL); - auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL); - - if (isPreviousFrame) - if (auto item = selected_item_get(); item && !item->children.empty()) - reference.frameIndex = glm::clamp(--reference.frameIndex, 0, (int)item->children.size() - 1); - - if (isNextFrame) - if (auto item = selected_item_get(); item && !item->children.empty()) - reference.frameIndex = glm::clamp(++reference.frameIndex, 0, (int)item->children.size() - 1); - - if (isPreviousFrame || isNextFrame) - { - if (auto item = selected_item_get(); item && !item->children.empty()) - { - frames_selection_set_reference(); - document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); - } - } - - if (isPreviousItem) reference_set_adjacent_item(-1); - if (isNextItem) reference_set_adjacent_item(1); - } - - if (isTextPushed) ImGui::PopStyleColor(); - } -} diff --git a/src/imgui/window/timeline/commands.cpp b/src/imgui/window/timeline/commands.cpp new file mode 100644 index 0000000..fb50fe7 --- /dev/null +++ b/src/imgui/window/timeline/commands.cpp @@ -0,0 +1,2086 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::commands_bind() + { + type_index = [](int type) { return std::clamp(type, 0, (int)TRIGGER); }; + item_type_get = [](int type) { return static_cast(type); }; + item_get = [&](int type, int id = -1, int groupType = NONE, int groupId = -1) + { return animation ? animation_item_get(*animation, item_type_get(type), id, groupType, groupId) : nullptr; }; + frame_get = [&]() + { + if (reference.frameIndex < 0) return (Element*)nullptr; + return anm2.element_get(reference); + }; + selected_item_get = [&]() + { + auto itemReference = reference; + itemReference.frameIndex = -1; + return anm2.element_get(itemReference); + }; + item_frame_type_get = [](const Element& item) + { return item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; }; + item_frames_count = [](const Element* item) + { + if (!item) return 0; + auto frameType = item->type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; + int count{}; + for (const auto& child : item->children) + if (child.type == frameType) ++count; + return count; + }; + item_frame_child_index_get = [](const Element& item, int frameIndex) + { + if (frameIndex < 0) return -1; + auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; + int currentFrameIndex{}; + for (int i = 0; i < (int)item.children.size(); ++i) + { + if (item.children[i].type != frameType) continue; + if (currentFrameIndex == frameIndex) return i; + ++currentFrameIndex; + } + return -1; + }; + item_frame_insert_index_get = [](const Element& item, int frameIndex) + { + auto targetFrameIndex = glm::max(0, frameIndex); + auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; + int currentFrameIndex{}; + for (int i = 0; i < (int)item.children.size(); ++i) + { + if (item.children[i].type != frameType) continue; + if (currentFrameIndex == targetFrameIndex) return i; + ++currentFrameIndex; + } + return (int)item.children.size(); + }; + layer_get = [&](int id) { return anm2.element_get(ElementType::LAYER_ELEMENT, id); }; + null_get = [&](int id) + { + auto nulls = anm2.element_get(ElementType::NULLS); + return nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; + }; + spritesheet_get = [&](int id) { return anm2.element_get(ElementType::SPRITESHEET, id); }; + info_get = [&]() { return element_first_get(anm2.root, ElementType::INFO); }; + container_type_get = [](int type) + { + if (type == LAYER) return ElementType::LAYER_ANIMATIONS; + if (type == NULL_) return ElementType::NULL_ANIMATIONS; + return ElementType::UNKNOWN; + }; + track_type_get = [](int type) + { + if (type == LAYER) return ElementType::LAYER_ANIMATION; + if (type == NULL_) return ElementType::NULL_ANIMATION; + return ElementType::UNKNOWN; + }; + track_id_get = [](const Element& track, int type) + { + if (type == LAYER) return track.layerId; + if (type == NULL_) return track.nullId; + return -1; + }; + track_container_get = [&](int type) + { + return animation ? element_child_first_get(*animation, container_type_get(type)) : nullptr; + }; + track_group_get = [&](int type, int groupId) + { + auto container = track_container_get(type); + return container ? element_child_id_get(*container, ElementType::GROUP, groupId) : nullptr; + }; + is_track_group_visible = [&](int type, int groupId) + { + if (groupId == -1) return true; + auto group = track_group_get(type, groupId); + return !group || group->isVisible; + }; + row_group_get = [&](const TimelineItemRow& row) -> Element* + { + return row.isGroup ? track_group_get(row.type, row.id) : nullptr; + }; + group_items_count_get = [&](int type, int groupId) + { + auto container = track_container_get(type); + auto trackType = track_type_get(type); + int count{}; + if (!container) return count; + for (auto& item : container->children) + if (item.type == trackType && item.groupId == groupId) ++count; + return count; + }; + + command_animation_get = [](Document& document, int animationIndex) + { return document.anm2.element_get(ElementType::ANIMATION, animationIndex); }; + command_item_get = [](Document& document, int animationIndex, int type, int id, int groupType = NONE, + int groupId = -1) + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); + return animation ? animation_item_get(*animation, static_cast(type), id, groupType, groupId) : nullptr; + }; + command_item_reference_get = [](Document& document, Reference itemReference) + { + itemReference.frameIndex = -1; + return document.anm2.element_get(itemReference); + }; + command_frame_get = [](Document& document, const Reference& targetReference) + { + if (targetReference.frameIndex < 0) return (Element*)nullptr; + return document.anm2.element_get(targetReference); + }; + command_layer_get = [](Document& document, int id) + { return document.anm2.element_get(ElementType::LAYER_ELEMENT, id); }; + command_spritesheet_get = [](Document& document, int id) + { return document.anm2.element_get(ElementType::SPRITESHEET, id); }; + command_info_get = [](Document& document) + { return element_first_get(document.anm2.root, ElementType::INFO); }; + item_reference_get = [&](int type, int id, int groupType = NONE, int groupId = -1) + { return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; }; + item_reference_from_frame_get = [](Reference frameReference) + { + frameReference.frameIndex = -1; + return frameReference; + }; + is_same_item = [](const Reference& left, const Reference& right) + { + return left.animationIndex == right.animationIndex && left.itemType == right.itemType && + left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; + }; + is_frame_reference_valid_for = [&](Document& targetDocument, const Reference& frameReference) + { return targetDocument.is_frame_reference_valid(frameReference); }; + group_selection_reset_for = [this](Document& targetDocument) + { + targetDocument.groupReferences.clear(); + isRowSelectionAnchorSet = false; + }; + frame_references_for_current_get = [&]() + { return document.frame_references_get(Document::FrameReferenceFallback::NONE); }; + item_references_for_current_get = [&]() + { + std::set result = document.items.references; + if (result.empty() && reference.itemType != NONE) + { + auto itemReference = reference; + itemReference.frameIndex = -1; + result.insert(itemReference); + } + return result; + }; + frames_selection_sync_for = [&](Document& targetDocument) + { + auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + targetDocument.frame_references_set(std::move(selectedFrames)); + frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); + frameSelectionSnapshotReference = targetDocument.reference; + }; + item_selection_set_for = [&](Document& targetDocument, Reference itemReference) + { + itemReference.frameIndex = -1; + targetDocument.items.references = {itemReference}; + }; + frame_selection_set_for = [&](Document& targetDocument, Reference frameReference) + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + targetDocument.frame_references_set({frameReference}); + frames_selection_sync_for(targetDocument); + }; + frame_selection_toggle_for = [&](Document& targetDocument, Reference frameReference) + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + auto selection = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + auto itemReference = item_reference_from_frame_get(frameReference); + if (selection.contains(frameReference)) + { + if (selection.size() > 1) selection.erase(frameReference); + bool isItemStillSelected{}; + for (const auto& selectedFrame : selection) + if (is_same_item(selectedFrame, itemReference)) isItemStillSelected = true; + if (!isItemStillSelected && targetDocument.items.references.size() > 1) + targetDocument.items.references.erase(itemReference); + } + else + { + selection.insert(frameReference); + targetDocument.items.references.insert(itemReference); + } + targetDocument.reference = frameReference; + targetDocument.frame_references_set(std::move(selection)); + frames_selection_sync_for(targetDocument); + }; + frame_selection_range_set_for = [&](Document& targetDocument, Reference firstReference, + Reference lastReference, bool isAdditive) -> bool + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + if (!is_same_item(firstReference, lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) + return false; + + auto item = command_item_reference_get(targetDocument, lastReference); + if (!item) return false; + if (firstReference.frameIndex >= (int)item->children.size() || + lastReference.frameIndex >= (int)item->children.size()) + return false; + + auto firstIndex = firstReference.frameIndex; + auto lastIndex = lastReference.frameIndex; + if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); + auto selectedFrames = isAdditive ? targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE) + : std::set{}; + + for (int i = firstIndex; i <= lastIndex; ++i) + { + auto frameReference = lastReference; + frameReference.frameIndex = i; + selectedFrames.insert(frameReference); + } + + targetDocument.reference = lastReference; + targetDocument.frame_references_set(std::move(selectedFrames)); + frames_selection_sync_for(targetDocument); + return true; + }; + all_frame_references_for_items_get = [&]() + { return document.selected_item_frame_references_get(); }; + is_frame_copy_item = [](const Reference& itemReference) + { return itemReference.itemType == ROOT || itemReference.itemType == LAYER || itemReference.itemType == NULL_; }; + copy_frame_references_get = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + if (!selectedFrames.empty()) return selectedFrames; + + auto selectedItems = document.items.references; + if (selectedItems.empty() && reference.itemType != NONE && reference.frameIndex < 0) + { + auto itemReference = reference; + itemReference.frameIndex = -1; + selectedItems.insert(itemReference); + } + + std::set result{}; + for (auto itemReference : selectedItems) + { + itemReference.frameIndex = -1; + if (!is_frame_copy_item(itemReference)) continue; + auto itemFrames = document.item_frame_references_get(itemReference); + result.insert(itemFrames.begin(), itemFrames.end()); + } + return result; + }; + frames_selection_reset_for = [this](Document& targetDocument) + { + targetDocument.frame_references_clear(); + frameSelectionSnapshot.clear(); + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusRequested = false; + frameFocusIndex = -1; + frameSelectionSnapshotReference = targetDocument.reference; + }; + frames_selection_set_reference_for = [this](Document& targetDocument) + { + auto& targetReference = targetDocument.reference; + if (targetReference.frameIndex >= 0) + { + targetDocument.editTarget = Document::EditTarget::FRAME; + targetDocument.frame_references_set({targetReference}); + } + else + targetDocument.frame_references_clear(); + frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); + frameSelectionSnapshotReference = targetReference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = targetReference.frameIndex; + frameFocusRequested = targetReference.frameIndex >= 0; + }; + frames_reference_normalize_for = [&](Document& targetDocument) + { + auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + if (!selectedFrames.empty()) + { + targetDocument.frame_references_set(std::move(selectedFrames)); + frames_selection_sync_for(targetDocument); + return; + } + + if (targetDocument.reference.frameIndex >= 0 && + !is_frame_reference_valid_for(targetDocument, targetDocument.reference)) + targetDocument.reference.frameIndex = -1; + }; + frames_reference_normalize_for(document); + reference_clear_for = [=, this](Document& targetDocument) + { + targetDocument.reference = {targetDocument.reference.animationIndex}; + frames_selection_reset_for(targetDocument); + targetDocument.items.references.clear(); + }; + reference_set_item_reference_for = [=, this](Document& targetDocument, Reference itemReference) + { + itemReference.frameIndex = -1; + targetDocument.reference = itemReference; + frames_selection_reset_for(targetDocument); + item_selection_set_for(targetDocument, itemReference); + }; + reference_set_timeline_item_reference_for = [=, this](Document& targetDocument, Reference itemReference) + { + if (itemReference.itemType == LAYER) + if (auto layer = command_layer_get(targetDocument, itemReference.itemID)) + targetDocument.spritesheet.reference = layer->spritesheetId; + reference_set_item_reference_for(targetDocument, itemReference); + }; + command_push = [&](auto run) + { + manager.command_push({manager.selected, + [run](Manager& manager, Document& document) mutable { run(manager, document); }}); + }; + track_references_from_frame_references_get = [](std::set frameReferences) + { + std::set result{}; + for (auto frameReference : frameReferences) + { + frameReference.frameIndex = -1; + result.insert(frameReference); + } + return result; + }; + tracks_snapshot_command_push = [&](StringType messageType, const std::set& trackReferences) + { + auto message = std::string(localize.get(messageType)); + auto queuedTrackReferences = trackReferences; + manager.command_push({manager.selected, + [message, queuedTrackReferences](Manager&, Document& document) + { document.tracks_snapshot(message, queuedTrackReferences); }}); + }; + frames_snapshot_command_push = [&](StringType messageType, const std::set& frameReferences) + { + auto message = std::string(localize.get(messageType)); + auto queuedFrameReferences = frameReferences; + manager.command_push({manager.selected, + [message, queuedFrameReferences](Manager&, Document& document) + { document.frames_snapshot(message, queuedFrameReferences); }}); + }; + frames_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, + const std::set& frameReferences, auto run) + { + auto message = std::string(localize.get(messageType)); + auto queuedFrameReferences = frameReferences; + manager.command_push({manager.selected, + [=, this](Manager& manager, Document& document) mutable + { + (void)changeType; + document.frames_snapshot(message, queuedFrameReferences); + run(manager, document); + document.anm2_change(changeType); + }}); + }; + tracks_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, + const std::set& trackReferences, auto run) + { + auto message = std::string(localize.get(messageType)); + auto queuedTrackReferences = trackReferences; + manager.command_push({manager.selected, + [=, this](Manager& manager, Document& document) mutable + { + (void)changeType; + document.tracks_snapshot(message, queuedTrackReferences); + run(manager, document); + document.anm2_change(changeType); + }}); + }; + edit_command_push = [&](StringType messageType, Document::ChangeType changeType, auto run) + { + auto message = std::string(localize.get(messageType)); + manager.command_push({manager.selected, + [=, this](Manager& manager, Document& document) mutable + { + (void)changeType; + document.anm2_snapshot(message); + run(manager, document); + document.anm2_change(changeType); + }}); + }; + type_color_base_vec = [&](int type) + { return isLightTheme ? FRAME_COLOR_LIGHT_BASE[type_index(type)] : TYPE_COLOR[type]; }; + + type_color_active_vec = [&](int type) + { + if (isLightTheme) return FRAME_COLOR_LIGHT_ACTIVE[type_index(type)]; + return TYPE_COLOR_ACTIVE[type]; + }; + + type_color_hovered_vec = [&](int type) + { + if (isLightTheme) return FRAME_COLOR_LIGHT_HOVERED[type_index(type)]; + return TYPE_COLOR_HOVERED[type]; + }; + + item_color_vec = [&](int type) + { + if (!isLightTheme) return TYPE_COLOR[type]; + return ITEM_COLOR_LIGHT_BASE[type_index(type)]; + }; + + item_color_active_vec = [&](int type) + { + if (!isLightTheme) return TYPE_COLOR_ACTIVE[type]; + return ITEM_COLOR_LIGHT_ACTIVE[type_index(type)]; + }; + + iconTintDefault = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : ICON_TINT_DEFAULT_DARK; + itemIconTint = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : iconTintDefault; + frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; + frameBorderColorReferenced = + isLightTheme ? FRAME_BORDER_COLOR_REFERENCED_LIGHT : FRAME_BORDER_COLOR_REFERENCED_DARK; + frameMultipleOverlayColor = + isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; + textMultipleColor = isLightTheme ? TEXT_MULTIPLE_COLOR_LIGHT : TEXT_MULTIPLE_COLOR_DARK; + playheadLineColor = isLightTheme ? PLAYHEAD_LINE_COLOR_LIGHT : PLAYHEAD_LINE_COLOR_DARK; + playheadIconTint = isLightTheme ? PLAYHEAD_ICON_TINT_LIGHT : iconTintDefault; + timelineBackgroundColor = + isLightTheme ? TIMELINE_BACKGROUND_COLOR_LIGHT : ImGui::GetStyleColorVec4(ImGuiCol_Header); + timelinePlayheadRectColor = + isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; + timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; + itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; + + overlay_icon = [&](GLuint textureId, ImVec4 tint, bool isForced = false) + { + if (!isForced && !isLightTheme) return; + auto min = ImGui::GetItemRectMin(); + auto max = ImGui::GetItemRectMax(); + ImGui::GetWindowDrawList()->AddImage((ImTextureID)(intptr_t)textureId, min, max, ImVec2(0, 0), ImVec2(1, 1), + ImGui::GetColorU32(tint)); + }; + + frames_selection_set_reference = [&]() + { + frames_selection_set_reference_for(document); + }; + + playback_stop = [&]() + { + playback.isPlaying = false; + playback.isFinished = false; + playback.timing_reset(); + }; + + frame_insert = [&]() + { + auto targetReference = reference; + auto targetFrameTime = document.frameTime; + if (!animation || !command_item_reference_get(document, targetReference)) + return; + + tracks_edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, {targetReference}, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, targetReference.animationIndex); + auto item = command_item_reference_get(document, targetReference); + if (!animation || !item) return; + + auto newReference = targetReference; + + if (targetReference.itemType == TRIGGER) + { + for (auto& trigger : item->children) + if (targetFrameTime == trigger.atFrame) return; + + auto addFrame = element_make(ElementType::TRIGGER); + addFrame.atFrame = targetFrameTime; + item->children.push_back(addFrame); + frames_sort_by_at_frame(*item); + newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); + } + else + { + auto frame = command_frame_get(document, targetReference); + auto framesCount = item_frames_count(item); + if (frame) + { + auto addFrame = *frame; + auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, addFrame); + newReference.frameIndex = insertIndex; + } + else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) + { + item->children.emplace_back(*lastFrame); + newReference.frameIndex = framesCount; + } + else + { + item->children.emplace_back(element_make(ElementType::FRAME)); + newReference.frameIndex = 0; + } + } + + document.reference = newReference; + frames_selection_set_reference_for(document); + if (newReference.itemType != TRIGGER) + document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); + }); + }; + + frames_delete_for = [=, this](Document& document, std::set selectedFrames) mutable + { + std::map> groupedFrames{}; + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + auto childIndex = item_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } + } + + auto item = command_item_reference_get(document, document.reference); + if (!item || item->children.empty()) + { + document.reference.frameIndex = -1; + frames_selection_reset_for(document); + return; + } + + document.reference.frameIndex = glm::clamp(document.reference.frameIndex, 0, (int)item->children.size() - 1); + frames_selection_set_reference_for(document); + }; + + frames_delete_action = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + if (selectedFrames.empty()) return; + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + tracks_edit_command_push(EDIT_DELETE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { frames_delete_for(document, selectedFrames); }); + }; + + frames_duplicate = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (selectedFrames.empty()) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + tracks_edit_command_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + std::map> groupedFrames{}; + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } + + std::set duplicatedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + std::vector validIndices{}; + std::vector duplicatedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + duplicatedFrames.push_back(*frame); + } + if (validIndices.empty()) continue; + + auto insertIndex = validIndices.back() + 1; + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, + std::make_move_iterator(duplicatedFrames.begin()), + std::make_move_iterator(duplicatedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + duplicatedSelection.insert(targetReference); + auto sourceReference = itemReference; + sourceReference.frameIndex = validIndices[offset]; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } + + if (duplicatedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); + document.frame_references_set(std::move(duplicatedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); + }; + + is_frames_reverse_available = [&](std::set selectedFrames) + { + std::map counts{}; + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + ++counts[itemReference]; + } + return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); + }; + + frames_reverse = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (!is_frames_reverse_available(selectedFrames)) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + tracks_edit_command_push(EDIT_REVERSE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + std::map> groupedFrames{}; + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } + + std::set reversedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item || indices.size() < 2) continue; + + std::vector validIndices{}; + std::vector reversedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + reversedFrames.push_back(std::move(*frame)); + } + if (validIndices.size() < 2) continue; + + auto insertIndex = validIndices.front(); + for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) + { + auto childIndex = item_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } + + std::ranges::reverse(reversedFrames); + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, + std::make_move_iterator(reversedFrames.begin()), + std::make_move_iterator(reversedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + reversedSelection.insert(targetReference); + auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; + auto sourceReference = itemReference; + sourceReference.frameIndex = sourceIndex; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } + + if (reversedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); + document.frame_references_set(std::move(reversedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); + }; + + frames_bake = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + auto bakeInterval = settings.bakeInterval; + auto isRoundScale = settings.bakeIsRoundScale; + auto isRoundRotation = settings.bakeIsRoundRotation; + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (selectedFrames.empty()) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + tracks_edit_command_push(EDIT_BAKE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + std::map> groupedFrames{}; + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } + + std::set bakedSelection{}; + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + int insertedBefore = 0; + for (auto originalIndex : indices) + { + auto i = originalIndex + insertedBefore; + auto frame = track_frame_get(*item, i); + if (!frame) continue; + + auto originalDuration = frame->duration; + frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); + + auto bakedCount = originalDuration <= FRAME_DURATION_MIN + ? 1 + : (int)std::ceil((float)originalDuration / bakeInterval); + for (int offset = 0; offset < bakedCount; ++offset) + { + auto frameReference = itemReference; + frameReference.frameIndex = i + offset; + bakedSelection.insert(frameReference); + } + + insertedBefore += bakedCount - 1; + } + } + + document.frame_references_set(std::move(bakedSelection)); + if (!document.frames.references.empty()) + { + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + } + else + frames_selection_reset_for(document); + }); + }; + + selected_root_frame_references_get = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); + return selectedFrames; + }; + + item_references_for_bake_into_other_frames_get = [](const Document& targetDocument, + const Element& targetAnimation, + BakeIntoOtherFramesTarget target, bool isLayers, + bool isNulls) + { + std::set result{}; + auto animationIndex = targetDocument.reference.animationIndex; + if (target == BakeIntoOtherFramesTarget::CURRENT_SELECTION) + { + for (auto itemReference : targetDocument.items.references) + { + itemReference.frameIndex = -1; + if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) result.insert(itemReference); + } + return result; + } + + auto add_items = [&](const Element& container, int itemType) + { + auto trackType = item_type_to_track_type_get(static_cast(itemType)); + auto add_item = [&](auto&& self, const Element& item) -> void + { + if (item.type == ElementType::GROUP) + { + for (const auto& child : item.children) + self(self, child); + return; + } + if (item.type != trackType) return; + auto itemID = itemType == LAYER ? item.layerId : item.nullId; + auto groupType = item.groupId == -1 ? NONE : itemType; + result.insert({animationIndex, itemType, itemID, -1, groupType, item.groupId}); + }; + for (const auto& item : container.children) + add_item(add_item, item); + }; + + if (isLayers) + if (auto layerAnimations = element_child_first_get(targetAnimation, ElementType::LAYER_ANIMATIONS)) + add_items(*layerAnimations, LAYER); + if (isNulls) + if (auto nullAnimations = element_child_first_get(targetAnimation, ElementType::NULL_ANIMATIONS)) + add_items(*nullAnimations, NULL_); + return result; + }; + + is_bake_into_other_frames_ready = [&]() + { + auto selectedRootFrames = selected_root_frame_references_get(); + if (selectedRootFrames.empty() || !animation) return false; + auto targetItems = item_references_for_bake_into_other_frames_get( + document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); + return !targetItems.empty(); + }; + + frame_root_transform_apply = [](Element& frame, const Element& rootFrame, bool isRoundScale, + bool isRoundRotation, bool isUseRootPivot) + { + auto rootScale = math::percent_to_unit(rootFrame.scale); + auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); + auto offset = (frame.position - pivot) * rootScale; + auto radians = glm::radians(rootFrame.rotation); + auto cos = std::cos(radians); + auto sin = std::sin(radians); + + frame.position = + rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); + frame.scale *= rootScale; + frame.rotation += rootFrame.rotation; + frame.tint *= rootFrame.tint; + frame.colorOffset += rootFrame.colorOffset; + + if (isRoundScale) frame.scale = glm::round(frame.scale); + if (isRoundRotation) frame.rotation = std::round(frame.rotation); + }; + + bake_into_other_frames = [&]() + { + auto selectedRootFrames = selected_root_frame_references_get(); + if (selectedRootFrames.empty()) return; + if (!animation) return; + auto target = bakeIntoOtherFramesTarget; + auto isLayers = isBakeIntoOtherFramesLayers; + auto isNulls = isBakeIntoOtherFramesNulls; + auto isRoundScale = settings.bakeIsRoundScale; + auto isRoundRotation = settings.bakeIsRoundRotation; + auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; + auto isUseRootPivot = settings.bakeIsUseRootPivot; + auto targetItems = item_references_for_bake_into_other_frames_get( + document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); + auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); + trackReferences.insert(targetItems.begin(), targetItems.end()); + tracks_edit_command_push(EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, document.reference.animationIndex); + if (!animation) return; + auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); + for (auto rootReference : selectedRootFrames) + if (!is_same_item(rootReference, rootItemReference)) return; + auto root = command_item_reference_get(document, rootItemReference); + if (!root) return; + + std::vector spans{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); + spans.push_back({start, start + rootFrame->duration}); + } + if (spans.empty()) return; + + auto targetItems = item_references_for_bake_into_other_frames_get( + document, *animation, target, isLayers, isNulls); + if (targetItems.empty()) return; + + for (auto itemReference : targetItems) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + if (isMatchRootInterpolation) + { + std::vector bakeIndices{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); + for (auto span : spans) + if (frameStart >= span.start && frameStart < span.end) + { + bakeIndices.push_back(frameIndex); + break; + } + ++frameIndex; + } + for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) + frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); + } + + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); + bool isInsideSpan{}; + for (auto span : spans) + if (frameStart >= span.start && frameStart < span.end) + { + isInsideSpan = true; + break; + } + if (!isInsideSpan) + { + ++frameIndex; + continue; + } + auto rootFrame = frame_generate(*root, (float)frameStart); + frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, + isUseRootPivot); + ++frameIndex; + } + } + + std::set selectedRootFrameIndices{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + selectedRootFrameIndices.insert(rootReference.frameIndex); + } + if (selectedRootFrameIndices.empty()) return; + + std::vector rootFrames{}; + std::set defaultRootSelection{}; + int frameIndex{}; + int rewrittenFrameIndex{}; + int defaultDuration{}; + auto default_root_frame_push = [&]() + { + if (defaultDuration <= 0) return; + auto frame = element_make(ElementType::FRAME); + frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); + auto defaultRootReference = rootItemReference; + defaultRootReference.frameIndex = rewrittenFrameIndex; + defaultRootSelection.insert(defaultRootReference); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + defaultDuration = 0; + }; + + for (const auto& frame : root->children) + { + if (frame.type != ElementType::FRAME) + { + default_root_frame_push(); + rootFrames.push_back(frame); + continue; + } + + if (selectedRootFrameIndices.contains(frameIndex)) + defaultDuration += frame.duration; + else + { + default_root_frame_push(); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + } + ++frameIndex; + } + default_root_frame_push(); + + root->children = std::move(rootFrames); + document.frame_references_set(std::move(defaultRootSelection)); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); + }; + + frame_split = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + if (selectedFrames.size() != 1) return; + auto targetReference = *selectedFrames.begin(); + auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); + if (targetReference.itemType == TRIGGER) return; + + tracks_edit_command_push(EDIT_SPLIT_FRAME, Document::FRAMES, {targetReference}, + [=, this](Manager&, Document& document) mutable + { + if (targetReference.itemType == TRIGGER) return; + + auto item = command_item_reference_get(document, targetReference); + auto frame = command_frame_get(document, targetReference); + + if (!item || !frame) return; + + auto originalDuration = frame->duration; + if (originalDuration <= 1) return; + + auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); + int frameStart = (int)std::round(frameStartTime); + int firstDuration = splitTime - frameStart + 1; + + if (firstDuration <= 0 || firstDuration >= originalDuration) return; + + int secondDuration = originalDuration - firstDuration; + auto splitFrame = *frame; + splitFrame.duration = secondDuration; + + auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); + if (frame->interpolation != Interpolation::NONE && nextFrame) + { + float interpolation = (float)firstDuration / (float)originalDuration; + switch (frame->interpolation) + { + case Interpolation::EASE_IN: + interpolation *= interpolation; + break; + case Interpolation::EASE_OUT: + interpolation = 1.0f - ((1.0f - interpolation) * (1.0f - interpolation)); + break; + case Interpolation::EASE_IN_OUT: + interpolation = interpolation < 0.5f + ? (2.0f * interpolation * interpolation) + : (1.0f - std::pow(-2.0f * interpolation + 2.0f, 2.0f) * 0.5f); + break; + case Interpolation::LINEAR: + case Interpolation::NONE: + default: + break; + } + + splitFrame.rotation = glm::mix(frame->rotation, nextFrame->rotation, interpolation); + splitFrame.position = glm::mix(frame->position, nextFrame->position, interpolation); + splitFrame.scale = glm::mix(frame->scale, nextFrame->scale, interpolation); + splitFrame.colorOffset = glm::mix(frame->colorOffset, nextFrame->colorOffset, interpolation); + splitFrame.tint = glm::mix(frame->tint, nextFrame->tint, interpolation); + } + + frame->duration = firstDuration; + auto insertIndex = item_frame_insert_index_get(*item, targetReference.frameIndex + 1); + item->children.insert(item->children.begin() + insertIndex, splitFrame); + document.reference = targetReference; + frames_selection_set_reference_for(document); + }); + }; + + reference_clear = [&]() + { + group_selection_reset_for(document); + reference_clear_for(document); + }; + + reference_set_timeline_item_reference = [&](Reference itemReference) + { + group_selection_reset_for(document); + reference_set_timeline_item_reference_for(document, itemReference); + }; + + timeline_item_rows_get = [&]() + { + std::vector rows{}; + if (!animation) return rows; + + auto track_row_push = [&](const Element& item, int type, int index, int depth = 0) + { + auto rootGroupType = item.groupId == -1 ? NONE : type; + rows.push_back({.type = type, + .id = track_id_get(item, type), + .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; + }; + + rows.push_back({.type = ROOT}); + + if (auto layerAnimations = element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) + { + auto groupIds = group_ids_get(*layerAnimations); + auto layer_track_push = [&](int groupId, int depth) + { + for (int j = (int)layerAnimations->children.size() - 1; j >= 0; --j) + { + auto& item = layerAnimations->children[j]; + if (item.type != ElementType::LAYER_ANIMATION || item.groupId != groupId) continue; + if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, LAYER, j, depth); + } + }; + + for (int i = (int)layerAnimations->children.size() - 1; i >= 0; --i) + { + auto& item = layerAnimations->children[i]; + if (item.type == ElementType::GROUP) + { + group_row_push(item, LAYER, i); + if (item.isExpanded) + { + group_root_row_push(item, LAYER); + layer_track_push(item.id, 1); + } + } + else if (item.type == ElementType::LAYER_ANIMATION && !groupIds.contains(item.groupId) && + (settings.timelineIsShowUnused || !item.children.empty())) + track_row_push(item, LAYER, i); + } + } + + if (auto nullAnimations = element_child_first_get(*animation, ElementType::NULL_ANIMATIONS)) + { + auto groupIds = group_ids_get(*nullAnimations); + auto null_track_push = [&](int groupId, int depth) + { + for (int j = 0; j < (int)nullAnimations->children.size(); ++j) + { + auto& item = nullAnimations->children[j]; + if (item.type != ElementType::NULL_ANIMATION || item.groupId != groupId) continue; + if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, NULL_, j, depth); + } + }; + + for (int i = 0; i < (int)nullAnimations->children.size(); ++i) + { + auto& item = nullAnimations->children[i]; + if (item.type == ElementType::GROUP) + { + group_row_push(item, NULL_, i); + if (item.isExpanded) + { + group_root_row_push(item, NULL_); + null_track_push(item.id, 1); + } + } + else if (item.type == ElementType::NULL_ANIMATION && !groupIds.contains(item.groupId) && + (settings.timelineIsShowUnused || !item.children.empty())) + track_row_push(item, NULL_, i); + } + } + + rows.push_back({.type = TRIGGER}); + return rows; + }; + + timeline_item_references_get = [&]() + { + std::vector itemReferences; + for (const auto& row : timeline_item_rows_get()) + { + if (row.isGroup) continue; + itemReferences.push_back( + {reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); + } + return itemReferences; + }; + + group_reference_get = [&](const TimelineItemRow& row) + { return Reference{reference.animationIndex, row.type, row.id}; }; + + row_reference_get = [&](const TimelineItemRow& row) + { + return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, row.index, + row.rootGroupType, row.rootGroupId, row.isGroup}; + }; + + row_item_reference_get = [](const TimelineRowReference& row) + { return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; }; + + timeline_row_references_get = [&]() + { + std::vector rowReferences; + for (const auto& row : timeline_item_rows_get()) + { + if (row.type == NONE) continue; + rowReferences.push_back(row_reference_get(row)); + } + return rowReferences; + }; + + is_group_selected = [&](const TimelineItemRow& row) + { + return document.groupReferences.contains(group_reference_get(row)); + }; + + is_row_selected = [&](const TimelineItemRow& row) + { + if (row.isGroup) return is_group_selected(row); + auto itemReference = item_reference_get(row.type, row.id, row.rootGroupType, row.rootGroupId); + auto isReferenced = is_same_item(reference, itemReference); + return document.items.references.contains(itemReference) || + (document.items.references.empty() && document.groupReferences.empty() && isReferenced); + }; + + row_selection_clear = [&]() + { + document.items.references.clear(); + document.groupReferences.clear(); + }; + + row_selection_insert = [&](const TimelineRowReference& row) + { + if (row.isGroup) + document.groupReferences.insert({row.animationIndex, row.type, row.id}); + else + document.items.references.insert(row_item_reference_get(row)); + }; + + row_selection_erase = [&](const TimelineRowReference& row) + { + if (row.isGroup) + document.groupReferences.erase({row.animationIndex, row.type, row.id}); + else + document.items.references.erase(row_item_reference_get(row)); + }; + + is_row_reference_selected = [&](const TimelineRowReference& row) + { + if (row.isGroup) return document.groupReferences.contains({row.animationIndex, row.type, row.id}); + return document.items.references.contains(row_item_reference_get(row)); + }; + + row_selection_count_get = [&]() { return document.items.references.size() + document.groupReferences.size(); }; + + row_selection_set = [&](const TimelineItemRow& row) + { + auto rowReference = row_reference_get(row); + auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); + auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); + + if (row.isGroup) + reference = {reference.animationIndex}; + else + { + if (row.type == LAYER) + if (auto layer = layer_get(row.id)) document.spritesheet.reference = layer->spritesheetId; + reference = row_item_reference_get(rowReference); + } + frames_selection_reset_for(document); + + if (isShiftDown) + { + auto rowSelection = timeline_row_references_get(); + auto anchor = isRowSelectionAnchorSet ? rowSelectionAnchor : rowReference; + auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); + auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); + if (first == rowSelection.end() || last == rowSelection.end()) + { + if (!isCtrlDown) row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + else + { + auto firstIndex = (int)std::distance(rowSelection.begin(), first); + auto lastIndex = (int)std::distance(rowSelection.begin(), last); + if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); + if (!isCtrlDown) row_selection_clear(); + for (int i = firstIndex; i <= lastIndex; ++i) + row_selection_insert(rowSelection[i]); + if (!isRowSelectionAnchorSet) rowSelectionAnchor = rowReference; + } + } + else if (isCtrlDown) + { + if (is_row_reference_selected(rowReference) && row_selection_count_get() > 1) + row_selection_erase(rowReference); + else + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + else + { + row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + + isRowSelectionAnchorSet = true; + }; + + reference_set_adjacent_item = [&](int direction) + { + auto itemReferences = timeline_item_references_get(); + if (itemReferences.empty()) return; + + auto it = std::find_if( + itemReferences.begin(), itemReferences.end(), [&](const Reference& itemReference) + { return is_same_item(itemReference, reference); }); + + int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; + if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; + index = std::clamp(index, 0, (int)itemReferences.size() - 1); + + auto& itemReference = itemReferences[index]; + reference_set_timeline_item_reference(itemReference); + }; + + selected_row_references_get = [&]() + { + std::vector result{}; + for (const auto& row : timeline_item_rows_get()) + if (is_row_selected(row)) result.push_back(row_reference_get(row)); + return result; + }; + + row_drag_references_get = [&](const TimelineItemRow& row) + { + auto clicked = row_reference_get(row); + if (clicked.type != LAYER && clicked.type != NULL_) return std::vector{clicked}; + + auto rows = selected_row_references_get(); + if (!is_row_reference_selected(clicked)) rows = {clicked}; + if (rows.empty()) rows = {clicked}; + + std::erase_if(rows, [&](const TimelineRowReference& rowReference) { return rowReference.type != clicked.type; }); + if (rows.empty()) rows = {clicked}; + return rows; + }; + + item_remove = [&]() + { + auto targetRows = selected_row_references_get(); + std::map> targetIds{}; + std::map> targetGroupIds{}; + for (auto row : targetRows) + { + if (row.type != LAYER && row.type != NULL_) continue; + if (row.isGroup) + targetGroupIds[row.type].insert(row.id); + else + targetIds[row.type].insert(row.id); + } + auto animationIndex = reference.animationIndex; + if (!animation) return; + if (targetIds.empty() && targetGroupIds.empty()) return; + edit_command_push(EDIT_REMOVE_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + for (auto targetType : {LAYER, NULL_}) + { + auto containerType = container_type_get(targetType); + auto targetTrackType = track_type_get(targetType); + auto container = element_child_first_get(*animation, containerType); + if (!container) continue; + auto ids = targetIds.contains(targetType) ? targetIds.at(targetType) : std::set{}; + auto groupIds = + targetGroupIds.contains(targetType) ? targetGroupIds.at(targetType) : std::set{}; + for (int i = (int)container->children.size() - 1; i >= 0; --i) + { + auto& item = container->children[i]; + if (item.type == ElementType::GROUP && groupIds.contains(item.id)) + { + container->children.erase(container->children.begin() + i); + continue; + } + if (item.type == targetTrackType && + (ids.contains(track_id_get(item, targetType)) || groupIds.contains(item.groupId))) + container->children.erase(container->children.begin() + i); + } + } + reference_clear_for(document); + group_selection_reset_for(document); + }); + }; + + item_references_groupable_get = [&]() + { + if (!document.groupReferences.empty()) return std::vector{}; + auto selectedItems = item_references_for_current_get(); + std::erase_if(selectedItems, [](const Reference& itemReference) + { return itemReference.itemType != LAYER && itemReference.itemType != NULL_; }); + if (selectedItems.empty()) return std::vector{}; + auto itemType = selectedItems.begin()->itemType; + for (const auto& itemReference : selectedItems) + if (itemReference.itemType != itemType) return std::vector{}; + + std::vector result{}; + for (const auto& row : timeline_item_rows_get()) + { + if (row.isGroup || row.type != itemType) continue; + auto itemReference = item_reference_get(row.type, row.id, NONE, -1); + if (!selectedItems.contains(itemReference)) continue; + if (row.groupId != -1) return std::vector{}; + result.push_back(itemReference); + } + return result; + }; + + item_group = [&]() + { + auto targetReferences = item_references_groupable_get(); + if (targetReferences.empty()) return; + auto targetType = targetReferences.front().itemType; + auto animationIndex = reference.animationIndex; + auto groupName = std::string(localize.get(TEXT_NEW_GROUP)); + + edit_command_push(EDIT_GROUP_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + + auto containerType = container_type_get(targetType); + auto targetTrackType = track_type_get(targetType); + auto container = element_child_first_get(*animation, containerType); + if (!container) return; + + std::set targetIds{}; + for (auto itemReference : targetReferences) + targetIds.insert(itemReference.itemID); + + auto group = element_make(ElementType::GROUP); + group.id = element_child_next_id_get(*container, ElementType::GROUP); + group.name = groupName; + group.isExpanded = true; + auto root = element_make(ElementType::ROOT_ANIMATION); + root.children.push_back(element_make(ElementType::FRAME)); + group.children.push_back(root); + int insertIndex = (int)container->children.size(); + + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type == targetTrackType && targetIds.contains(track_id_get(item, targetType))) + { + insertIndex = std::min(insertIndex, i); + item.groupId = group.id; + } + } + + if (insertIndex == (int)container->children.size()) return; + insertIndex = std::clamp(insertIndex, 0, (int)container->children.size()); + container->children.insert(container->children.begin() + insertIndex, group); + + document.items.references.clear(); + for (auto itemReference : targetReferences) + document.items.references.insert(itemReference); + document.reference = targetReferences.front(); + frames_selection_reset_for(document); + }); + }; + + rows_move_to_row = [&](std::vector draggedRows, TimelineItemRow targetRow, + bool isDropAfter, bool isDropIntoGroup = false) + { + if (draggedRows.empty()) return; + auto targetType = draggedRows.front().type; + if (targetType != LAYER && targetType != NULL_) return; + for (const auto& draggedRow : draggedRows) + if (draggedRow.type != targetType) return; + + if (targetRow.isGroup && targetRow.type != targetType) return; + if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && + targetRow.type != TRIGGER) + return; + + auto animationIndex = reference.animationIndex; + edit_command_push(EDIT_MOVE_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + auto container = element_child_first_get(*animation, container_type_get(targetType)); + if (!container) return; + auto targetTrackType = track_type_get(targetType); + + std::set draggedIds{}; + std::set draggedGroupIds{}; + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + draggedGroupIds.insert(draggedRow.id); + else + draggedIds.insert(draggedRow.id); + } + + if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; + + std::vector movedItems{}; + for (const auto& item : container->children) + { + auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); + auto isDraggedTrack = item.type == targetTrackType && + (draggedIds.contains(track_id_get(item, targetType)) || + draggedGroupIds.contains(item.groupId)); + if (isDraggedGroup || isDraggedTrack) movedItems.push_back(item); + } + if (movedItems.empty()) return; + + if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; + + auto row_index_get = [&](const TimelineItemRow& row) + { + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; + if (!row.isGroup && row.type == targetType && item.type == targetTrackType && + track_id_get(item, targetType) == row.id) + return i; + } + return -1; + }; + auto group_end_index_get = [&](int groupId) + { + int result = -1; + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); + if (item.type == targetTrackType && item.groupId == groupId) + result = std::max(result, i); + } + return result; + }; + + int targetIndex = (int)container->children.size(); + if (targetRow.isGroup || targetRow.type == targetType) + { + auto rowIndex = row_index_get(targetRow); + if (rowIndex == -1) return; + if (targetRow.isGroup) + { + auto groupEndIndex = group_end_index_get(targetRow.id); + if (targetType == LAYER) + targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; + else + targetIndex = rowIndex + isDropAfter; + } + else + targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); + } + + int removedBeforeTarget = 0; + for (int i = (int)container->children.size() - 1; i >= 0; --i) + { + auto& item = container->children[i]; + auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); + auto isDraggedTrack = item.type == targetTrackType && + (draggedIds.contains(track_id_get(item, targetType)) || + draggedGroupIds.contains(item.groupId)); + if (isDraggedGroup || isDraggedTrack) + { + if (i < targetIndex) ++removedBeforeTarget; + container->children.erase(container->children.begin() + i); + } + } + + auto targetGroupId = -1; + if (targetRow.isGroup && isDropIntoGroup) + targetGroupId = targetRow.id; + else if (targetRow.type == targetType) + targetGroupId = targetRow.groupId; + + for (auto& item : movedItems) + if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) + item.groupId = targetGroupId; + + targetIndex -= removedBeforeTarget; + targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); + container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), + movedItems.end()); + + document.items.references.clear(); + document.groupReferences.clear(); + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + document.groupReferences.insert( + {draggedRow.animationIndex, draggedRow.type, draggedRow.id}); + else + document.items.references.insert(row_item_reference_get(draggedRow)); + } + if (!document.items.references.empty()) + document.reference = *document.items.references.begin(); + else + document.reference = {animationIndex}; + frames_selection_reset_for(document); + }); + }; + + fit_animation_length = [&]() + { + if (!animation) return; + auto animationIndex = reference.animationIndex; + edit_command_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + animation->frameNum = animation_length_get(*animation); + }); + }; + + frame_references_copy = [&](const std::set& selectedFrames) + { + if (!animation || selectedFrames.empty()) return; + + 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; + if (!frame) continue; + auto parentType = item_type_to_track_type_get(item_type_get(frameReference.itemType)); + clipboardString += element_to_string(*frame, parentType); + } + if (!clipboardString.empty()) clipboard.set(clipboardString); + }; + + copy = [&]() + { + auto selectedFrames = copy_frame_references_get(); + if (selectedFrames.empty()) return; + + frame_references_copy(selectedFrames); + }; + + cut = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + if (selectedFrames.empty()) return; + frame_references_copy(selectedFrames); + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + tracks_edit_command_push(EDIT_CUT_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { frames_delete_for(document, selectedFrames); }); + }; + + paste = [&]() + { + auto targetReference = reference; + auto selectedFrames = frame_references_for_current_get(); + auto clipboardString = clipboard.get(); + if (clipboardString.empty()) return; + auto targetHoveredTime = hoveredTime; + auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); + command_push([=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, targetReference.animationIndex); + if (!animation) return; + if (auto item = command_item_reference_get(document, targetReference)) + { + document.tracks_snapshot(message, {targetReference}); + std::set indices{}; + std::string errorString{}; + int insertIndex = (int)item->children.size(); + std::set selectedIndices{}; + for (auto frameReference : selectedFrames) + if (is_same_item(frameReference, targetReference)) + selectedIndices.insert(frameReference.frameIndex); + + if (!selectedIndices.empty()) + insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); + else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) + insertIndex = targetReference.frameIndex + 1; + + auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; + if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) + { + if (targetReference.itemType != LAYER) + { + for (auto i : indices) + if (auto frame = track_frame_get(*item, i); frame) + { + frame->regionId = -1; + frame->crop = {}; + frame->size = {}; + frame->pivot = {}; + } + } + else if (targetReference.itemID != -1) + { + auto layer = command_layer_get(document, targetReference.itemID); + auto spritesheet = layer ? command_spritesheet_get(document, layer->spritesheetId) : nullptr; + + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame || frame->regionId == -1) continue; + auto region = + spritesheet ? element_child_id_get(*spritesheet, ElementType::REGION, frame->regionId) + : nullptr; + if (!region) frame->regionId = -1; + } + } + + std::set pastedSelection{}; + for (auto i : indices) + { + auto pastedReference = targetReference; + pastedReference.frameIndex = i; + pastedSelection.insert(pastedReference); + } + document.reference = targetReference; + document.reference.frameIndex = *indices.begin(); + document.frame_references_set(std::move(pastedSelection)); + document.anm2_change(Document::FRAMES); + } + else + { + document.snapshots.pendingStep.reset(); + toasts.push( + std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); + logger.error(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, + anm2ed::ENGLISH), + errorString)); + } + } + else + { + toasts.push(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION)); + logger.warning(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION, anm2ed::ENGLISH)); + } + }); + }; + + context_menu = [&]() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + + if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED)) cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED)) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED)) paste(); + if (shortcut(manager.chords[SHORTCUT_SPLIT], shortcut::FOCUSED)) frame_split(); + if (shortcut(manager.chords[SHORTCUT_BAKE], shortcut::FOCUSED)) frames_bake(); + if (shortcut(manager.chords[SHORTCUT_FIT], shortcut::FOCUSED)) fit_animation_length(); + + auto make_region = [&]() + { + auto targetReference = reference; + auto frame = frame_get(); + if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; + if (frame->regionId != -1) return; + auto layer = layer_get(targetReference.itemID); + if (!layer) return; + + auto spritesheetID = layer->spritesheetId; + if (!spritesheet_get(spritesheetID)) return; + + auto settingsPtr = &settings; + command_push([=, this](Manager& manager, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame || frame->regionId != -1) return; + auto layer = command_layer_get(document, targetReference.itemID); + if (!layer) return; + + auto spritesheetID = layer->spritesheetId; + if (!command_spritesheet_get(document, spritesheetID)) return; + + auto region = element_make(ElementType::REGION); + region.crop = frame->crop; + region.size = frame->size; + region.pivot = frame->pivot; + region.origin = Origin::CUSTOM; + + document.spritesheet.reference = spritesheetID; + settingsPtr->windowIsRegions = true; + manager.makeRegionSpritesheetId = spritesheetID; + manager.makeRegion = region; + manager.isMakeRegionRequested = true; + }); + }; + + auto make_many_regions = [&]() + { + auto targetFrames = frame_references_for_current_get(); + std::erase_if(targetFrames, + [&](const Reference& frameReference) + { + if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; + auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, + frameReference.groupId); + auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; + auto layer = layer_get(frameReference.itemID); + return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); + }); + if (targetFrames.size() < 2) return; + + makeManyRegionReferences = targetFrames; + makeManyRegionsPopup.open(); + }; + + auto item = selected_item_get(); + auto frame = frame_get(); + auto selectedFrames = frame_references_for_current_get(); + auto copyFrames = copy_frame_references_get(); + auto selectedBakeFrames = selectedFrames; + std::erase_if(selectedBakeFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + auto isReverseFrames = is_frames_reverse_available(selectedFrames); + auto selectedRegionFrames = selectedFrames; + std::erase_if(selectedRegionFrames, + [&](const Reference& frameReference) + { + if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; + auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, + frameReference.groupId); + auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; + auto layer = layer_get(frameReference.itemID); + return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); + }); + bool isMakeManyRegions = selectedRegionFrames.size() > 1; + auto selectedRootFrames = selected_root_frame_references_get(); + bool isMakeRegion = frame && reference.itemType == LAYER && reference.itemID != -1 && frame->regionId == -1 && + layer_get(reference.itemID) && spritesheet_get(layer_get(reference.itemID)->spritesheetId); + Actions actions{}; + actions_undo_redo_add(actions, manager, document); + actions.separator(); + actions.add({.label = playback.isPlaying ? LABEL_PAUSE : LABEL_PLAY, + .shortcut = SHORTCUT_PLAY_PAUSE, + .isEnabled = []() { return true; }, + .run = [&]() { playback.toggle(); }}); + actions.add({.label = LABEL_INSERT, + .shortcut = SHORTCUT_INSERT_FRAME, + .isEnabled = [&]() { return item; }, + .run = [&]() { frame_insert(); }}); + actions.add(ACTION_DUPLICATE, [=, this]() { return !selectedBakeFrames.empty(); }, [&]() { frames_duplicate(); }); + actions.add({.label = LABEL_SPLIT, + .shortcut = SHORTCUT_SPLIT, + .isEnabled = [=, this]() { return selectedBakeFrames.size() == 1; }, + .run = [&]() { frame_split(); }}); + actions.add(ACTION_REVERSE, [=, this]() { return isReverseFrames; }, [&]() { frames_reverse(); }); + actions.separator(); + actions.add({.label = LABEL_BAKE, + .shortcut = SHORTCUT_BAKE, + .isEnabled = [=, this]() { return !selectedBakeFrames.empty(); }, + .run = [&]() { frames_bake(); }}); + actions.add({.label = LABEL_BAKE_INTO_OTHER_FRAMES, + .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.separator(); + actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, + .shortcut = -1, + .isEnabled = [=, this]() { return isMakeManyRegions || isMakeRegion; }, + .run = [&]() + { + if (isMakeManyRegions) + make_many_regions(); + else + make_region(); + }}); + actions.separator(); + actions.add({.label = LABEL_DELETE, + .shortcut = SHORTCUT_REMOVE, + .isEnabled = [=, this]() { return !selectedFrames.empty(); }, + .run = [&]() { frames_delete_action(); }}); + actions.separator(); + actions.add(ACTION_CUT, [=, this]() { return !selectedFrames.empty(); }, cut); + actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, copy); + actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, paste); + actions_context_window_draw("##Context Menu", actions, settings); + + ImGui::PopStyleVar(2); + }; + + item_base_properties_open = [&](int type, int id) + { + switch (type) + { + case LAYER: + manager.layer_properties_open(id); + break; + case NULL_: + manager.null_properties_open(id); + default: + break; + }; + }; + + group_properties_close = [&]() + { + groupName.clear(); + groupAnimationIndex = -1; + groupType = NONE; + groupId = -1; + groupPropertiesPopup.close(); + }; + + group_properties_open = [&](const TimelineItemRow& row, const Element& group) + { + groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; + groupAnimationIndex = reference.animationIndex; + groupType = row.type; + groupId = row.id; + groupPropertiesPopup.open(); + }; + + group_properties_update = [&]() + { + groupPropertiesPopup.trigger(); + + if (ImGui::BeginPopupModal(groupPropertiesPopup.label(), &groupPropertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) + { + auto childSize = child_size_get(1); + if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) + { + if (groupPropertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), &groupName); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + } + ImGui::EndChild(); + + auto widgetSize = widget_size_with_row_get(2); + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(BASIC_CONFIRM), widgetSize)) + { + auto targetName = groupName; + auto targetAnimationIndex = groupAnimationIndex; + auto targetType = groupType; + auto targetId = groupId; + edit_command_push(EDIT_RENAME_GROUP, Document::ITEMS, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, targetAnimationIndex); + auto container = + animation ? element_child_first_get(*animation, container_type_get(targetType)) + : nullptr; + auto group = container ? element_child_id_get(*container, ElementType::GROUP, targetId) + : nullptr; + if (!group) return; + group->name = targetName; + }); + group_properties_close(); + } + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) group_properties_close(); + + ImGui::EndPopup(); + } + + groupPropertiesPopup.end(); + }; + + item_context_menu = [&]() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + + auto& type = reference.itemType; + auto& id = reference.itemID; + auto item = selected_item_get(); + auto selectedRows = selected_row_references_get(); + auto selectedGroupableItems = item_references_groupable_get(); + auto copyFrames = copy_frame_references_get(); + TimelineItemRow selectedGroupRow{}; + Element* selectedGroup{}; + if (selectedRows.size() == 1 && selectedRows.front().isGroup) + { + auto row = selectedRows.front(); + selectedGroupRow = {.type = row.type, .id = row.id, .index = row.index, .isGroup = true}; + selectedGroup = row_group_get(selectedGroupRow); + } + auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) + { return row.type == LAYER || row.type == NULL_; }); + auto item_cut = [&]() + { + if (copyFrames.empty() || !isRemoveAvailable) return; + frame_references_copy(copyFrames); + item_remove(); + }; + + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && + ImGui::IsMouseClicked(ImGuiMouseButton_Right)) + ImGui::OpenPopup("##Items Context Menu"); + + Actions actions{}; + actions_undo_redo_add(actions, manager, document); + actions.separator(); + actions.add(ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, + [&]() + { + if (selectedGroup) + group_properties_open(selectedGroupRow, *selectedGroup); + else + item_base_properties_open(type, id); + }); + actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); + actions.add(ACTION_REMOVE, [=, this]() { return isRemoveAvailable; }, [&]() { item_remove(); }); + actions.add(ACTION_GROUP, [=, this]() { return !selectedGroupableItems.empty(); }, [&]() { item_group(); }); + actions.separator(); + actions.add(ACTION_CUT, [=, this]() { return !copyFrames.empty() && isRemoveAvailable; }, item_cut); + actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, copy); + actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, paste); + if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED) && !copyFrames.empty() && isRemoveAvailable) + item_cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && !copyFrames.empty()) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && item && !clipboard.is_empty()) paste(); + actions_popup_draw("##Items Context Menu", actions, settings); + + ImGui::PopStyleVar(2); + }; + + + } +} diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp new file mode 100644 index 0000000..9038f38 --- /dev/null +++ b/src/imgui/window/timeline/context.hpp @@ -0,0 +1,355 @@ +#pragma once + +#include "timeline.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "actions.hpp" +#include "log.hpp" +#include "math.hpp" +#include "toast.hpp" +#include "util/imgui/draw.hpp" +#include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" +#include "util/imgui/shortcut.hpp" +#include "util/imgui/tooltip.hpp" + +#include "vector.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::types; +using namespace anm2ed::util; +using namespace glm; + +namespace anm2ed::imgui +{ + + constexpr auto WIDTH_MULTIPLIER = 1.25f; + + constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f); + constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f); + constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f); + constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f); + constexpr auto FRAME_BORDER_COLOR_REFERENCED_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.60f); + constexpr auto FRAME_BORDER_THICKNESS = 1.0f; + constexpr auto FRAME_BORDER_THICKNESS_REFERENCED = 2.0f; + constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.05f); + constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.1f); + constexpr auto FRAME_ROUNDING = 3.0f; + constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f); + constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f); + constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f; + constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); + constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f); + constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT = ImVec4(0.8353f, 0.8353f, 0.7294f, 1.0f); + constexpr auto TIMELINE_TICK_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + constexpr auto TIMELINE_CHILD_BG_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); + constexpr auto TIMELINE_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + + enum class DropZone + { + BEFORE, + INSIDE, + AFTER + }; + + constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f}, + {0.5216f, 0.7333f, 1.0f, 1.0f}, + {1.0f, 0.9961f, 0.5882f, 1.0f}, + {0.6157f, 1.0f, 0.5882f, 1.0f}, + {1.0f, 0.5882f, 0.8314f, 1.0f}}; + constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f}, + {0.0980f, 0.3765f, 0.6431f, 1.0f}, + {1.0f, 0.5255f, 0.3333f, 1.0f}, + {0.3686f, 0.5765f, 0.2353f, 1.0f}, + {0.6118f, 0.2039f, 0.2745f, 1.0f}}; + constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f}, + {0.0752f, 0.2887f, 0.4931f, 1.0f}, + {0.85f, 0.4467f, 0.2833f, 1.0f}, + {0.2727f, 0.4265f, 0.1741f, 1.0f}, + {0.4618f, 0.1539f, 0.2072f, 1.0f}}; + constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f}, + {0.3333f, 0.5725f, 0.8392f, 1.0f}, + {1.0f, 0.5412f, 0.3412f, 1.0f}, + {0.5255f, 0.8471f, 0.4588f, 1.0f}, + {0.7961f, 0.3882f, 0.5412f, 1.0f}}; + constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f}, + {0.3733f, 0.6125f, 0.8792f, 1.0f}, + {0.9106f, 0.4949f, 0.2753f, 1.0f}, + {0.5655f, 0.8871f, 0.4988f, 1.0f}, + {0.8361f, 0.4282f, 0.5812f, 1.0f}}; + constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f}, + {0.2039f, 0.4549f, 0.7176f, 1.0f}, + {0.8745f, 0.4392f, 0.2275f, 1.0f}, + {0.3765f, 0.6784f, 0.2980f, 1.0f}, + {0.6353f, 0.2235f, 0.3647f, 1.0f}}; + + constexpr auto FRAME_MULTIPLE = 5; + constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; + constexpr auto DRAG_DROP_SOURCE_FLAGS = + ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; + +#define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5 + + struct TimelineItemRow + { + int type{NONE}; + int id{-1}; + int index{-1}; + int groupId{-1}; + int rootGroupType{NONE}; + int rootGroupId{-1}; + int depth{}; + bool isGroup{}; + }; + + struct RootFrameSpan + { + int start{}; + int end{}; + }; + + struct TimelineContext + { + Timeline& timeline; + bool& isDragging; + bool& isWindowHovered; + bool& isHorizontalScroll; + popup::ItemProperties& itemProperties; + PopupHelper& bakePopup; + PopupHelper& bakeIntoOtherFramesPopup; + PopupHelper& makeManyRegionsPopup; + BakeIntoOtherFramesTarget& bakeIntoOtherFramesTarget; + bool& isBakeIntoOtherFramesLayers; + bool& isBakeIntoOtherFramesNulls; + bool& isMakeManyRegionsMapFrames; + std::set& makeManyRegionReferences; + int& hoveredTime; + bool& isFrameBoxPending; + bool& isFrameBoxSelecting; + bool& isFrameBoxAdditive; + ImVec2& frameBoxStart; + ImVec2& frameBoxEnd; + std::set& frameBoxSelection; + TimelineRowReference& rowSelectionAnchor; + bool& isRowSelectionAnchorSet; + PopupHelper& groupPropertiesPopup; + std::string& groupName; + int& groupAnimationIndex; + int& groupType; + int& groupId; + Reference& draggedFrameReference; + bool& isDraggedFrameActive; + int& draggedFrameType; + int& draggedFrameIndex; + int& draggedFrameStart; + int& draggedFrameStartDuration; + std::vector& draggedFrameStartDurations; + float& draggedFrameStartMouseX; + float& draggedFrameWidth; + bool& isDraggedFrameSnapshot; + bool& frameFocusRequested; + int& frameFocusIndex; + FrameMoveDrag& frameMoveDrag; + std::vector& frameSelectionSnapshot; + std::vector& frameSelectionLocked; + bool& isFrameSelectionLocked; + Reference& frameSelectionSnapshotReference; + Reference& frameSelectionAnchor; + bool& isFrameSelectionAnchorSet; + int& animationLengthEditIndex; + std::vector& rowDragReferences; + glm::vec2& scroll; + ImGuiStyle& style; + + Manager& manager; + Settings& settings; + Resources& resources; + Clipboard& clipboard; + Document& document; + Anm2& anm2; + Playback& playback; + Reference& reference; + Storage& frames; + Storage& region; + Element* animation{}; + float rowFrameChildHeight{}; + bool isLightTheme{}; + bool isTextPushed{}; + + ImVec4 iconTintDefault{}; + ImVec4 itemIconTint{}; + ImVec4 frameBorderColor{}; + ImVec4 frameBorderColorReferenced{}; + ImVec4 frameMultipleOverlayColor{}; + ImVec4 textMultipleColor{}; + ImVec4 playheadLineColor{}; + ImVec4 playheadIconTint{}; + ImVec4 timelineBackgroundColor{}; + ImVec4 timelinePlayheadRectColor{}; + ImVec4 timelineTickColor{}; + ImVec4 itemTextColor{}; + std::optional frameSplitTimeAtCursor{}; + + int frameMoveDropType{NONE}; + int frameMoveDropItemID{-1}; + int frameMoveDropGroupType{NONE}; + int frameMoveDropGroupId{-1}; + int frameMoveDropIndex{-1}; + bool isFrameMoveDropTarget{}; + float playheadLineCenterX{}; + float playheadLineTopY{}; + bool isPlayheadLineSet{}; + ImVec2 frameBoxClipMin{}; + ImVec2 frameBoxClipMax{}; + bool isFrameBoxClipSet{}; + + std::function type_index{}; + std::function item_type_get{}; + std::function item_get{}; + std::function frame_get{}; + std::function selected_item_get{}; + std::function item_frame_type_get{}; + std::function item_frames_count{}; + std::function item_frame_child_index_get{}; + std::function item_frame_insert_index_get{}; + std::function layer_get{}; + std::function null_get{}; + std::function spritesheet_get{}; + std::function info_get{}; + std::function container_type_get{}; + std::function track_type_get{}; + std::function track_id_get{}; + std::function track_container_get{}; + std::function track_group_get{}; + std::function is_track_group_visible{}; + std::function row_group_get{}; + std::function group_items_count_get{}; + std::function command_animation_get{}; + std::function command_item_get{}; + std::function command_item_reference_get{}; + std::function command_frame_get{}; + std::function command_layer_get{}; + std::function command_spritesheet_get{}; + std::function command_info_get{}; + std::function item_reference_get{}; + std::function item_reference_from_frame_get{}; + std::function is_same_item{}; + std::function is_frame_reference_valid_for{}; + std::function group_selection_reset_for{}; + std::function()> frame_references_for_current_get{}; + std::function()> item_references_for_current_get{}; + std::function frames_selection_sync_for{}; + std::function item_selection_set_for{}; + std::function frame_selection_set_for{}; + std::function frame_selection_toggle_for{}; + std::function frame_selection_range_set_for{}; + std::function()> all_frame_references_for_items_get{}; + std::function is_frame_copy_item{}; + std::function()> copy_frame_references_get{}; + std::function frames_selection_reset_for{}; + std::function frames_selection_set_reference_for{}; + std::function frames_reference_normalize_for{}; + std::function reference_clear_for{}; + std::function reference_set_item_reference_for{}; + std::function reference_set_timeline_item_reference_for{}; + std::function)> command_push{}; + std::function(std::set)> track_references_from_frame_references_get{}; + std::function&)> tracks_snapshot_command_push{}; + std::function&)> frames_snapshot_command_push{}; + std::function&, + std::function)> + frames_edit_command_push{}; + std::function&, + std::function)> + tracks_edit_command_push{}; + std::function)> edit_command_push{}; + std::function type_color_base_vec{}; + std::function type_color_active_vec{}; + std::function type_color_hovered_vec{}; + std::function item_color_vec{}; + std::function item_color_active_vec{}; + std::function overlay_icon{}; + std::function frames_selection_set_reference{}; + std::function playback_stop{}; + std::function frame_insert{}; + std::function)> frames_delete_for{}; + std::function frames_delete_action{}; + std::function frames_duplicate{}; + std::function)> is_frames_reverse_available{}; + std::function frames_reverse{}; + std::function frames_bake{}; + std::function()> selected_root_frame_references_get{}; + std::function(const Document&, const Element&, BakeIntoOtherFramesTarget, bool, bool)> + item_references_for_bake_into_other_frames_get{}; + std::function is_bake_into_other_frames_ready{}; + std::function frame_root_transform_apply{}; + std::function bake_into_other_frames{}; + std::function frame_split{}; + std::function reference_clear{}; + std::function reference_set_timeline_item_reference{}; + std::function()> timeline_item_rows_get{}; + std::function()> timeline_item_references_get{}; + std::function group_reference_get{}; + std::function row_reference_get{}; + std::function row_item_reference_get{}; + std::function()> timeline_row_references_get{}; + std::function is_group_selected{}; + std::function is_row_selected{}; + std::function row_selection_clear{}; + std::function row_selection_insert{}; + std::function row_selection_erase{}; + std::function is_row_reference_selected{}; + std::function row_selection_count_get{}; + std::function row_selection_set{}; + std::function reference_set_adjacent_item{}; + std::function()> selected_row_references_get{}; + std::function(const TimelineItemRow&)> row_drag_references_get{}; + std::function item_remove{}; + std::function()> item_references_groupable_get{}; + std::function item_group{}; + std::function, TimelineItemRow, bool, bool)> rows_move_to_row{}; + std::function fit_animation_length{}; + std::function&)> frame_references_copy{}; + std::function copy{}; + std::function cut{}; + std::function paste{}; + std::function context_menu{}; + std::function item_base_properties_open{}; + std::function group_properties_close{}; + std::function group_properties_open{}; + std::function group_properties_update{}; + std::function item_context_menu{}; + + TimelineContext(Timeline&, Manager&, Settings&, Resources&, Clipboard&); + void update(); + void commands_bind(); + void item_child(const TimelineItemRow&, int); + void items_child(); + void frame_move_drag_clear(); + void frames_move_to(int, int, int, int, int); + ImVec2 frame_box_content_point_get(); + ImVec2 frame_box_screen_point_get(ImVec2); + bool is_frame_box_overlapping(ImVec2, ImVec2, ImVec2, ImVec2); + void frame_overlay_draw(ImDrawList*, ImVec2, ImVec2); + void frame_child(const TimelineItemRow&, int&, float); + void frames_child(); + void draw(); + }; +} diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp new file mode 100644 index 0000000..b637b73 --- /dev/null +++ b/src/imgui/window/timeline/frames.cpp @@ -0,0 +1,1135 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::frame_move_drag_clear() +{ + frameMoveDrag = {}; + frameSelectionLocked.clear(); + frameMoveDropType = NONE; + frameMoveDropItemID = -1; + frameMoveDropGroupType = NONE; + frameMoveDropGroupId = -1; + frameMoveDropIndex = -1; + isFrameMoveDropTarget = false; + } + + void TimelineContext::frames_move_to(int targetType, int targetID, int targetGroupType, int targetGroupId, int insertIndex) +{ + if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) return; + if (targetType == TRIGGER) return; + + auto drag = frameMoveDrag; + std::erase_if(drag.references, [](const Reference& frameReference) + { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); + if (drag.references.empty() && drag.frameIndex >= 0) + drag.references.push_back( + {drag.animationIndex, drag.type, drag.itemID, drag.frameIndex, drag.groupType, drag.groupId}); + std::erase_if(drag.references, [](const Reference& frameReference) + { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); + if (drag.references.empty()) return; + + auto trackReferences = track_references_from_frame_references_get( + std::set(drag.references.begin(), drag.references.end())); + trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); + tracks_edit_command_push(EDIT_MOVE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + auto targetItem = + command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, + targetGroupId); + if (!targetItem) return; + + std::map> groupedFrames{}; + for (auto frameReference : drag.references) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } + + int removedBeforeTarget = 0; + std::vector movedFrames; + for (auto& [itemReference, indices] : groupedFrames) + { + auto sourceItem = command_item_reference_get(document, itemReference); + if (!sourceItem) continue; + + for (auto i : indices) + { + auto childIndex = item_frame_child_index_get(*sourceItem, i); + if (childIndex == -1) continue; + movedFrames.push_back(std::move(sourceItem->children[childIndex])); + if (itemReference.itemType == targetType && itemReference.itemID == targetID && + itemReference.groupType == targetGroupType && itemReference.groupId == targetGroupId && + i < insertIndex) + ++removedBeforeTarget; + } + + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + auto childIndex = item_frame_child_index_get(*sourceItem, *it); + if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); + } + } + + if (movedFrames.empty()) return; + + int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); + desired -= removedBeforeTarget; + desired = std::clamp(desired, 0, item_frames_count(targetItem)); + + auto insertPosResult = desired; + auto insertedCount = (int)movedFrames.size(); + auto childIndex = item_frame_insert_index_get(*targetItem, insertPosResult); + targetItem->children.insert(targetItem->children.begin() + childIndex, + std::make_move_iterator(movedFrames.begin()), + std::make_move_iterator(movedFrames.end())); + + if (insertedCount <= 0) return; + + std::set movedSelection{}; + for (int offset = 0; offset < insertedCount; ++offset) + movedSelection.insert({drag.animationIndex, targetType, targetID, insertPosResult + offset, + targetGroupType, targetGroupId}); + + document.reference = {drag.animationIndex, targetType, targetID, insertPosResult, + targetGroupType, targetGroupId}; + document.frame_references_set(std::move(movedSelection)); + document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); + frameSelectionSnapshot.assign(document.frames.selection.begin(), + document.frames.selection.end()); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + if (targetType == LAYER) + if (auto layer = command_layer_get(document, targetID)) + document.spritesheet.reference = layer->spritesheetId; + }); + } + + ImVec2 TimelineContext::frame_box_content_point_get() +{ + auto mousePos = ImGui::GetIO().MousePos; + return ImVec2(mousePos.x + scroll.x - frameBoxClipMin.x, mousePos.y + scroll.y - frameBoxClipMin.y); + } + + ImVec2 TimelineContext::frame_box_screen_point_get(ImVec2 point) +{ return ImVec2(point.x - scroll.x + frameBoxClipMin.x, point.y - scroll.y + frameBoxClipMin.y); } + + bool TimelineContext::is_frame_box_overlapping(ImVec2 leftMin, ImVec2 leftMax, ImVec2 rightMin, ImVec2 rightMax) +{ + return leftMin.x <= rightMax.x && leftMax.x >= rightMin.x && leftMin.y <= rightMax.y && + leftMax.y >= rightMin.y; + } + + void TimelineContext::frame_overlay_draw(ImDrawList* drawList, ImVec2 clipMin, ImVec2 clipMax) +{ + if (isFrameBoxSelecting && isFrameBoxClipSet) + { + auto boxContentMin = + ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxContentMax = + ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto boxMin = frame_box_screen_point_get(boxContentMin); + auto boxMax = frame_box_screen_point_get(boxContentMax); + auto boxClipMin = clipMin; + if (isPlayheadLineSet) boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); + drawList->PushClipRect(boxClipMin, clipMax, true); + drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); + drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); + drawList->PopClipRect(); + } + + if (isPlayheadLineSet) + { + auto lineTopY = std::max(clipMin.y, playheadLineTopY); + if (clipMax.y > lineTopY) + { + auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); + auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); + drawList->PushClipRect(clipMin, clipMax, true); + drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), + ImGui::GetColorU32(playheadLineColor)); + drawList->PopClipRect(); + } + } + } + + void TimelineContext::frame_child(const TimelineItemRow& row, int& index, float width) +{ + auto type = row.type; + auto id = row.id; + auto row_reference_make = [&](int frameIndex = -1) + { return Reference{reference.animationIndex, type, id, frameIndex, row.rootGroupType, row.rootGroupId}; }; + auto childSize = ImVec2(width, rowFrameChildHeight); + if (row.isGroup) + { + auto group = row_group_get(row); + if (!group) return; + + ImGui::PushID(index); + ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); + ImGui::EndChild(); + index++; + ImGui::PopID(); + return; + } + + auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); + if (type != NONE && !item) return; + + auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; + if (item && type == ROOT && row.rootGroupId != -1) + isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); + auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; + if (isOnlyShowLayers && type != LAYER) isVisible = false; + + auto colorVec = type_color_base_vec(type); + auto colorActiveVec = type_color_active_vec(type); + auto colorHoveredVec = type_color_hovered_vec(type); + auto color = to_imvec4(colorVec); + auto colorActive = to_imvec4(colorActiveVec); + auto colorHovered = to_imvec4(colorHoveredVec); + auto colorHidden = to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER); + auto colorActiveHidden = to_imvec4(colorActiveVec * COLOR_HIDDEN_MULTIPLIER); + auto colorHoveredHidden = to_imvec4(colorHoveredVec * COLOR_HIDDEN_MULTIPLIER); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::PopStyleVar(2); + + ImGui::PushID(index); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + bool isDefaultChild = type == NONE; + if (isLightTheme && isDefaultChild) ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); + + bool isFramesChildVisible = ImGui::BeginChild("##Frames Child", childSize, ImGuiChildFlags_Borders); + auto drawList = ImGui::GetWindowDrawList(); + auto clipMax = drawList->GetClipRectMax(); + auto length = animation ? animation->frameNum : 0; + auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); + auto framesSize = ImVec2(frameSize.x * length, frameSize.y); + auto cursorPos = ImGui::GetCursorPos(); + auto cursorScreenPos = ImGui::GetCursorScreenPos(); + if (frameSize.x > 0.0f && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + { + auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; + frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); + } + auto border = glm::max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f); + auto borderLineLength = frameSize.y / 5; + auto frameMin = std::max(0, (int)std::floor(scroll.x / frameSize.x) - 1); + auto frameMax = std::min(FRAME_NUM_MAX, (int)std::ceil((scroll.x + clipMax.x) / frameSize.x) + 1); + + if (isFrameBoxSelecting && isFrameBoxClipSet && type != NONE && animation && item) + { + auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; + auto rowMaxY = rowMinY + childSize.y; + float selectionFrameTime{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) + { + 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; + auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); + auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); + if (is_frame_box_overlapping(frameContentMin, frameContentMax, boxMin, boxMax)) + frameBoxSelection.insert(frameReference); + if (type != TRIGGER) selectionFrameTime += frame.duration; + ++frameIndex; + } + } + + if (isFramesChildVisible) + { + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && + ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) + { + if (!frames.references.empty() || !frames.selection.empty()) + { + reference.frameIndex = -1; + frames_selection_reset_for(document); + } + else if (reference.itemType != NONE || reference.itemID != -1) + reference_clear(); + } + + if (type == NONE) + { + if (length > 0) + { + if (isLightTheme) + { + auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); + drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); + float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); + drawList->AddRectFilled(cursorScreenPos, + ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(timelinePlayheadRectColor)); + } + else + { + drawList->AddRectFilled(cursorScreenPos, + ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); + } + } + + for (int i = frameMin; i < frameMax; i++) + { + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + + drawList->AddRect(frameScreenPos, ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); + + drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), + ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); + + if (i % FRAME_MULTIPLE == 0) + { + auto string = std::to_string(i); + auto textSize = ImGui::CalcTextSize(string.c_str()); + auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, + frameScreenPos.y + (frameSize.y - textSize.y) / 2); + + drawList->AddRectFilled(frameScreenPos, + ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(frameMultipleOverlayColor)); + + drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); + } + } + + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + playback_stop(); + isDragging = true; + } + + auto childPos = ImGui::GetWindowPos(); + auto mousePos = ImGui::GetIO().MousePos; + auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); + hoveredTime = floorf(localMousePos.x / frameSize.x); + + if (isDragging) + { + playback.time = hoveredTime; + playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + if (!playback.isPlaying) playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; + + if (length > 0) + { + ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); + ImGui::Image(resources.icons[icon::PLAYHEAD].id, frameSize); + auto playheadMin = ImGui::GetItemRectMin(); + auto playheadMax = ImGui::GetItemRectMax(); + playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; + playheadLineTopY = playheadMax.y; + isPlayheadLineSet = true; + overlay_icon(resources.icons[icon::PLAYHEAD].id, playheadIconTint, true); + } + } + else if (animation) + { + float frameTime{}; + + for (int i = frameMin; i < frameMax; i++) + { + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); + + drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); + + if (i % FRAME_MULTIPLE == 0) + drawList->AddRectFilled(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameMultipleOverlayColor)); + } + + if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) + { + isFrameBoxPending = true; + isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); + frameBoxStart = frame_box_content_point_get(); + frameBoxEnd = frameBoxStart; + frameBoxSelection.clear(); + } + + bool isFrameMovePreview = false; + ImVec2 frameMovePreviewMin{}; + ImVec2 frameMovePreviewMax{}; + bool isFrameMoveHoveredFrame = false; + ImVec2 frameMoveHoveredFrameMin{}; + ImVec2 frameMoveHoveredFrameMax{}; + + if (frameMoveDrag.isActive && type != TRIGGER) + { + auto mousePos = ImGui::GetIO().MousePos; + auto rowMin = cursorScreenPos; + auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); + if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) + { + auto mouseX = mousePos.x - cursorScreenPos.x; + auto targetTime = glm::max(0.0f, mouseX / frameSize.x); + int dropIndex = item_frames_count(item); + float dropFrameTime{}; + float frameTime{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + + for (const auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = frameTime; + auto frameEnd = frameStart + frame.duration; + if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) + { + isFrameMoveHoveredFrame = true; + frameMoveHoveredFrameMin = ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); + frameMoveHoveredFrameMax = + ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); + } + + auto midpoint = frameStart + ((float)frame.duration * 0.5f); + if (targetTime < midpoint) + { + dropIndex = frameIndex; + dropFrameTime = frameStart; + break; + } + + frameTime = frameEnd; + dropFrameTime = frameTime; + ++frameIndex; + } + + frameMoveDropType = type; + frameMoveDropItemID = id; + frameMoveDropGroupType = row.rootGroupType; + frameMoveDropGroupId = row.rootGroupId; + frameMoveDropIndex = dropIndex; + isFrameMoveDropTarget = true; + + auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; + auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); + frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); + frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); + isFrameMovePreview = true; + } + } + + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) + { + auto& frame = item->children[childIndex]; + if (frame.type != frameType) continue; + ImGui::PushID(childIndex); + + auto frameReference = row_reference_make(frameIndex); + auto isFrameVisible = isVisible && frame.isVisible; + auto isReferenced = reference == frameReference; + auto isSelected = frames.references.contains(frameReference) || + (frames.references.empty() && frames.selection.contains(frameIndex) && + reference.itemType == type && reference.itemID == id && + reference.groupType == row.rootGroupType && reference.groupId == row.rootGroupId); + + if (type == TRIGGER) frameTime = frame.atFrame; + + auto buttonSize = type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); + auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; + auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; + if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) + { + if (type != TRIGGER) frameTime += frame.duration; + ImGui::PopID(); + ++frameIndex; + continue; + } + auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); + + if (frameFocusRequested && frameFocusIndex == frameIndex && reference == frameReference) + frameFocusRequested = false; + + ImGui::SetCursorPos(buttonPos); + + auto buttonScreenPos = ImGui::GetCursorScreenPos(); + auto fillColor = isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) + : (isFrameVisible ? color : colorHidden); + drawList->AddRectFilled(buttonScreenPos, + ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), + ImGui::GetColorU32(fillColor), FRAME_ROUNDING); + + ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); + ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); + + ImGui::SetNextItemAllowOverlap(); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); + ImGui::SetNextItemSelectionUserData(frameIndex); + bool isDifferentItem = !is_same_item(reference, frameReference); + if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) + { + if (type == LAYER) + if (auto layer = layer_get(id)) document.spritesheet.reference = layer->spritesheetId; + + if (type != TRIGGER) + { + if (ImGui::IsKeyDown(ImGuiMod_Alt)) + { + auto targetReference = frameReference; + frames_edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, {targetReference}, + [=, this](Manager&, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame) return; + frame->interpolation = frame->interpolation == Interpolation::NONE + ? Interpolation::LINEAR + : Interpolation::NONE; + }); + } + + document.frameTime = frameTime; + } + + auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); + auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); + if (isShiftDown) + { + auto isHadAnchor = isFrameSelectionAnchorSet; + auto anchorReference = isHadAnchor ? frameSelectionAnchor : frameReference; + auto isRangeSelected = + frame_selection_range_set_for(document, anchorReference, frameReference, isCtrlDown); + if (!isRangeSelected) frame_selection_set_for(document, frameReference); + if (!isHadAnchor || !isRangeSelected) frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } + else if (isCtrlDown) + { + frame_selection_toggle_for(document, frameReference); + frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } + else + { + frame_selection_set_for(document, frameReference); + frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } + reference = frameReference; + isReferenced = true; + region.reference = -1; + region.selection.clear(); + if (isDifferentItem) frames_selection_sync_for(document); + } + ImGui::PopStyleVar(); + + ImGui::PopStyleColor(4); + + if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) + { + isDraggedFrameActive = true; + draggedFrameReference = frameReference; + draggedFrameType = type; + draggedFrameIndex = frameIndex; + draggedFrameStart = hoveredTime; + if (type != TRIGGER) draggedFrameStartDuration = frame.duration; + draggedFrameStartDurations.clear(); + if (type != TRIGGER) + { + auto selectedReferences = frame_references_for_current_get(); + if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + std::erase_if(selectedReferences, [](const Reference& selectedReference) + { return selectedReference.itemType == TRIGGER; }); + if (selectedReferences.empty()) selectedReferences = {frameReference}; + for (auto selectedReference : selectedReferences) + { + auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, + selectedReference.groupType, selectedReference.groupId); + auto selectedFrame = + selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; + if (selectedFrame) + draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); + } + } + draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; + draggedFrameWidth = frameSize.x; + } + } + } + + if (type != TRIGGER) + { + if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && + ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + auto selectedReferences = frame_references_for_current_get(); + if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + std::erase_if(selectedReferences, [](const Reference& selectedReference) + { return selectedReference.itemType == TRIGGER; }); + if (selectedReferences.empty()) selectedReferences = {frameReference}; + int dragDuration = 0; + for (auto selectedReference : selectedReferences) + { + auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, + selectedReference.groupType, selectedReference.groupId); + auto selectedFrame = + selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; + if (selectedFrame) dragDuration += selectedFrame->duration; + } + dragDuration = glm::max(1, dragDuration); + + frameMoveDrag = { + .type = type, + .itemID = id, + .animationIndex = reference.animationIndex, + .groupType = row.rootGroupType, + .groupId = row.rootGroupId, + .frameIndex = frameIndex, + .duration = dragDuration, + .indices = {}, + .references = {selectedReferences.begin(), selectedReferences.end()}, + .isActive = true, + }; + } + } + + auto rectMin = ImGui::GetItemRectMin(); + auto rectMax = ImGui::GetItemRectMax(); + auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; + auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; + drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); + + auto icon = icon::UNINTERPOLATED; + if (type == TRIGGER) + icon = icon::TRIGGER; + else + { + switch (frame.interpolation) + { + case Interpolation::NONE: + icon = icon::UNINTERPOLATED; + break; + case Interpolation::LINEAR: + icon = icon::INTERPOLATED; + break; + case Interpolation::EASE_IN: + icon = icon::EASE_IN; + break; + case Interpolation::EASE_OUT: + icon = icon::EASE_OUT; + break; + case Interpolation::EASE_IN_OUT: + icon = icon::EASE_IN_OUT; + break; + default: + icon = icon::UNINTERPOLATED; + break; + } + } + auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), + cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); + ImGui::SetCursorPos(iconPos); + ImGui::Image(resources.icons[icon].id, icon_size_get()); + overlay_icon(resources.icons[icon].id, iconTintDefault, false); + + if (type != TRIGGER) frameTime += frame.duration; + + ImGui::PopID(); + ++frameIndex; + } + + if (isFrameMovePreview) + { + drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, + ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); + drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), + FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); + } + + if (isFrameMoveHoveredFrame) + drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, + ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, + ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); + + if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && + (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && + !ImGui::IsAnyItemHovered()) + row_selection_set(row); + + if (isFrameSelectionLocked) + { + std::set lockedSelection{}; + for (int idx : frameSelectionLocked) + lockedSelection.insert(row_reference_make(idx)); + document.frame_references_set(std::move(lockedSelection)); + isFrameSelectionLocked = false; + frameSelectionLocked.clear(); + } + if (reference.itemType == type && reference.itemID == id && reference.groupType == row.rootGroupType && + reference.groupId == row.rootGroupId) + { + frameSelectionSnapshot.assign(frames.selection.begin(), frames.selection.end()); + frameSelectionSnapshotReference = reference; + } + } + + } + + if (isDraggedFrameActive) + { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + auto durationDelta = draggedFrameWidth > 0.0f + ? static_cast((ImGui::GetIO().MousePos.x - draggedFrameStartMouseX) / + draggedFrameWidth) + : hoveredTime - draggedFrameStart; + auto isDraggedFrameChanged = + draggedFrameType == TRIGGER ? hoveredTime != draggedFrameStart : durationDelta != 0; + + if (!isDraggedFrameSnapshot && isDraggedFrameChanged) + { + isDraggedFrameSnapshot = true; + if (draggedFrameType == TRIGGER) + tracks_snapshot_command_push(EDIT_TRIGGER_AT_FRAME, {item_reference_from_frame_get(draggedFrameReference)}); + else + { + std::set draggedFrameReferences{}; + if (draggedFrameStartDurations.empty()) + draggedFrameReferences.insert(draggedFrameReference); + else + for (auto& frameDuration : draggedFrameStartDurations) + draggedFrameReferences.insert(frameDuration.reference); + frames_snapshot_command_push(EDIT_FRAME_DURATION, draggedFrameReferences); + } + } + + if (isDraggedFrameSnapshot) + { + auto targetReference = draggedFrameReference; + auto targetType = draggedFrameType; + auto targetIndex = draggedFrameIndex; + auto targetStartDuration = draggedFrameStartDuration; + auto targetStartDurations = draggedFrameStartDurations; + auto targetHoveredTime = hoveredTime; + auto targetDurationDelta = durationDelta; + auto isPlaybackClamp = settings.playbackIsClamp; + auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; + command_push([=, this](Manager&, Document& document) + { + auto item = command_item_reference_get(document, targetReference); + auto frame = command_frame_get(document, targetReference); + if (!item || !frame) return; + + if (targetType == TRIGGER) + { + frame->atFrame = + glm::clamp(targetHoveredTime, 0, + isPlaybackClamp ? animationLength - 1 : FRAME_NUM_MAX - 1); + + for (auto [i, trigger] : std::views::enumerate(item->children)) + { + if ((int)i == targetIndex) continue; + if (trigger.atFrame == frame->atFrame) frame->atFrame--; + } + } + else + { + if (targetStartDurations.empty()) + { + frame->duration = glm::clamp(targetStartDuration + targetDurationDelta, + FRAME_DURATION_MIN, FRAME_DURATION_MAX); + return; + } + + for (auto frameDuration : targetStartDurations) + { + auto targetFrame = command_frame_get(document, frameDuration.reference); + if (!targetFrame) continue; + targetFrame->duration = glm::clamp(frameDuration.duration + targetDurationDelta, + FRAME_DURATION_MIN, FRAME_DURATION_MAX); + } + } + }); + } + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + auto targetReference = draggedFrameReference; + auto targetType = draggedFrameType; + command_push([=, this](Manager&, Document& document) + { + auto item = command_item_reference_get(document, targetReference); + if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); + document.anm2_change(Document::FRAMES); + }); + isDraggedFrameActive = false; + draggedFrameReference = {}; + draggedFrameType = NONE; + draggedFrameIndex = -1; + draggedFrameStart = -1; + draggedFrameStartDuration = -1; + draggedFrameStartDurations.clear(); + draggedFrameStartMouseX = 0.0f; + draggedFrameWidth = 0.0f; + isDraggedFrameSnapshot = false; + frameSelectionLocked.clear(); + } + } + + context_menu(); + + ImGui::EndChild(); + if (isLightTheme && isDefaultChild) ImGui::PopStyleColor(); + ImGui::PopStyleVar(); + + index++; + ImGui::PopID(); + } + + void TimelineContext::frames_child() +{ + auto cursorPos = ImGui::GetCursorPos(); + ImGui::SetCursorPos(ImVec2(cursorPos.x + ITEM_CHILD_WIDTH, cursorPos.y)); + + auto framesChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y); + + if (ImGui::BeginChild("##Frames Child", framesChildSize, ImGuiChildFlags_Borders)) + { + auto viewListChildSize = + ImVec2(ImGui::GetContentRegionAvail().x, + ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); + + 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)); + return length; + }(); + auto childWidth = animationsLength * ImGui::GetTextLineHeight(); + if (animation && animation->frameNum > animationsLength) + childWidth = animation->frameNum * ImGui::GetTextLineHeight(); + childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); + + childWidth *= WIDTH_MULTIPLIER; + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) + { + playheadLineCenterX = 0.0f; + playheadLineTopY = 0.0f; + isPlayheadLineSet = false; + isFrameBoxClipSet = false; + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + { + group_selection_reset_for(document); + document.frame_references_set(all_frame_references_for_items_get()); + if (!document.frames.references.empty()) + frames_selection_sync_for(document); + } + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + if (ImGui::BeginTable("##Frames List Table", 1, + ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) + { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + + scroll.x = ImGui::GetScrollX(); + scroll.y = ImGui::GetScrollY(); + + isHorizontalScroll = window->ScrollbarX; + + if (isWindowHovered) + { + auto& io = ImGui::GetIO(); + auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; + + scroll.x -= io.MouseWheelH * lineHeight; + scroll.y -= io.MouseWheel * lineHeight; + } + + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + + auto frameBoxDrawList = ImGui::GetWindowDrawList(); + frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); + frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); + isFrameBoxClipSet = true; + if (isFrameBoxPending || isFrameBoxSelecting) + { + auto& io = ImGui::GetIO(); + auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; + frameBoxEnd = frame_box_content_point_get(); + auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); + if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) + { + isFrameBoxPending = false; + isFrameBoxSelecting = true; + } + auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); + auto scrollStep = edgeSize * 0.5f; + if (isFrameBoxSelecting) + { + if (io.MousePos.x < frameBoxClipMin.x + edgeSize) + scroll.x -= scrollStep; + else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) + scroll.x += scrollStep; + if (io.MousePos.y < frameBoxClipMin.y + edgeSize) + scroll.y -= scrollStep; + else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) + scroll.y += scrollStep; + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + frameBoxEnd = frame_box_content_point_get(); + frameBoxSelection.clear(); + } + } + + int index{}; + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Frames"); + + auto frames_child_row = [&](const TimelineItemRow& row) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + frame_child(row, index, childWidth); + }; + + frames_child_row({.type = NONE}); + + if (animation) + { + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); + + for (const auto& row : timeline_item_rows_get()) + frames_child_row(row); + + ImGui::PopStyleVar(); + } + ImGui::EndTable(); + } + + if (isFrameBoxClipSet) + { + auto overlayCursor = ImGui::GetCursorScreenPos(); + auto overlayPos = ImGui::GetWindowPos(); + auto overlaySize = ImGui::GetWindowSize(); + ImGui::SetCursorScreenPos(overlayPos); + if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | + ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) + frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); + ImGui::EndChild(); + ImGui::SetCursorScreenPos(overlayCursor); + } + + if (isFrameBoxPending || isFrameBoxSelecting) + { + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + if (isFrameBoxSelecting) + { + group_selection_reset_for(document); + if (isFrameBoxAdditive) + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); + document.frame_references_set(std::move(selectedFrames)); + } + else + document.frame_references_set(frameBoxSelection); + frames_selection_sync_for(document); + } + isFrameBoxPending = false; + isFrameBoxSelecting = false; + frameBoxSelection.clear(); + } + } + + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::SetCursorPos( + ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); + + auto widgetSize = widget_size_with_row_get(10); + + ImGui::BeginDisabled(!animation); + { + auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); + auto tooltip = + playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); + + shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); + if (ImGui::Button(label, widgetSize)) playback.toggle(); + set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); + + ImGui::SameLine(); + + auto item = selected_item_get(); + auto selectedFrames = frame_references_for_current_get(); + auto selectedBakeFrames = selectedFrames; + std::erase_if(selectedBakeFrames, [](const Reference& frameReference) + { return frameReference.itemType == TRIGGER; }); + + ImGui::BeginDisabled(!item); + { + shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); + if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) frame_insert(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); + + ImGui::SameLine(); + + ImGui::BeginDisabled(selectedFrames.empty()); + { + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) frames_delete_action(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); + + ImGui::SameLine(); + + ImGui::BeginDisabled(selectedBakeFrames.empty()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) bakePopup.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); + ImGui::EndDisabled(); + } + ImGui::EndDisabled(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); + shortcut(manager.chords[SHORTCUT_FIT]); + if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) fit_animation_length(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); + ImGui::EndDisabled(); + + ImGui::SameLine(); + + auto frameNum = animation ? animation->frameNum : dummy_value(); + auto currentAnimationIndex = reference.animationIndex; + ImGui::SetNextItemWidth(widgetSize.x); + auto isLengthChanged = input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, + FRAME_NUM_MAX, STEP, STEP_FAST, + !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); + if (ImGui::IsItemActivated()) animationLengthEditIndex = currentAnimationIndex; + if (isLengthChanged && animation) + { + auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; + edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + animation->frameNum = frameNum; + }); + } + if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); + + ImGui::SameLine(); + + auto isLoop = animation ? animation->isLoop : dummy_value(); + ImGui::SetNextItemWidth(widgetSize.x); + if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) + { + auto animationIndex = reference.animationIndex; + edit_command_push(EDIT_LOOP, Document::ANIMATIONS, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + animation->isLoop = isLoop; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + auto info = info_get(); + auto fps = info ? info->fps : 30; + ImGui::SetNextItemWidth(widgetSize.x); + if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) + { + edit_command_push(EDIT_FPS, Document::INFO, + [=, this](Manager&, Document& document) + { + auto info = command_info_get(document); + if (!info) + { + document.anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &document.anm2.root.children.back(); + } + info->fps = fps; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); + + ImGui::SameLine(); + + info = info_get(); + auto createdBy = info ? info->createdBy : std::string{}; + ImGui::SetNextItemWidth(widgetSize.x); + if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) + { + edit_command_push(EDIT_AUTHOR, Document::INFO, + [=, this](Manager&, Document& document) + { + auto info = command_info_get(document); + if (!info) + { + document.anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &document.anm2.root.children.back(); + } + info->createdBy = createdBy; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); + + ImGui::SameLine(); + + ImGui::SetNextItemWidth(widgetSize.x); + ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); + + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + + ImGui::SetCursorPos(cursorPos); + } +} diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp new file mode 100644 index 0000000..9a7c961 --- /dev/null +++ b/src/imgui/window/timeline/popups.cpp @@ -0,0 +1,248 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::draw() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline)) + { + isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + frames_child(); + if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + if (isFrameMoveDropTarget) + frames_move_to(frameMoveDropType, frameMoveDropItemID, frameMoveDropGroupType, frameMoveDropGroupId, + frameMoveDropIndex); + frame_move_drag_clear(); + } + items_child(); + } + ImGui::PopStyleVar(); + ImGui::End(); + + if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document); + group_properties_update(); + + makeManyRegionsPopup.trigger(); + if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) + { + input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); + ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); + + auto widgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(LABEL_MAKE_MANY_REGIONS), widgetSize)) + { + auto targetFrames = makeManyRegionReferences; + auto format = settings.generateRegionNameFormat; + auto mapping = isMakeManyRegionsMapFrames ? Document::RegionFrameMapping::SET + : Document::RegionFrameMapping::PRESERVE; + edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, + [=, this](Manager&, Document& document) mutable + { document.regions_generate_from_frames(targetFrames, format, mapping); }); + makeManyRegionsPopup.close(); + } + + ImGui::SameLine(); + + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) makeManyRegionsPopup.close(); + + ImGui::EndPopup(); + } + makeManyRegionsPopup.end(); + + bakePopup.trigger(); + + if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize)) + { + auto& interval = settings.bakeInterval; + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; + + auto frame = frame_get(); + + input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, + frame ? frame->duration : FRAME_DURATION_MIN); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + + auto widgetSize = widget_size_with_row_get(2); + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + frames_bake(); + bakePopup.close(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + + ImGui::EndPopup(); + } + + bakeIntoOtherFramesPopup.trigger(); + + if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen, + ImGuiWindowFlags_NoResize)) + { + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; + auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; + auto& isUseRootPivot = settings.bakeIsUseRootPivot; + int target = (int)bakeIntoOtherFramesTarget; + ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, + (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); + bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; + + auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; + ImGui::BeginDisabled(isCurrentSelection); + ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); + ImGui::EndDisabled(); + + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + + ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); + + ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); + + auto widgetSize = widget_size_with_row_get(2); + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + bake_into_other_frames(); + bakeIntoOtherFramesPopup.close(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + + ImGui::EndPopup(); + } + + if (animation) + { + if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); + + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) + { + playback_stop(); + playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL)) + { + playback_stop(); + playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + static bool isShortenChordHeld = false; + auto isShortenFrame = shortcut(manager.chords[SHORTCUT_SHORTEN_FRAME], shortcut::GLOBAL); + + if (isShortenFrame) + { + + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (!selectedFrames.empty()) + { + if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames); + command_push([=, this](Manager&, Document& document) + { + for (auto frameReference : selectedFrames) + { + auto frame = command_frame_get(document, frameReference); + if (!frame) continue; + frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); + } + document.anm2_change(Document::FRAMES); + }); + } + } + isShortenChordHeld = isShortenFrame; + + static bool isExtendChordHeld = false; + auto isExtendFrame = shortcut(manager.chords[SHORTCUT_EXTEND_FRAME], shortcut::GLOBAL); + if (isExtendFrame) + { + + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (!selectedFrames.empty()) + { + if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames); + command_push([=, this](Manager&, Document& document) + { + for (auto frameReference : selectedFrames) + { + auto frame = command_frame_get(document, frameReference); + if (!frame) continue; + frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); + } + document.anm2_change(Document::FRAMES); + }); + } + } + isExtendChordHeld = isExtendFrame; + + auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], shortcut::GLOBAL); + auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], shortcut::GLOBAL); + auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], shortcut::GLOBAL); + auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL); + + if (isPreviousFrame) + if (auto item = selected_item_get(); item && !item->children.empty()) + reference.frameIndex = glm::clamp(--reference.frameIndex, 0, (int)item->children.size() - 1); + + if (isNextFrame) + if (auto item = selected_item_get(); item && !item->children.empty()) + reference.frameIndex = glm::clamp(++reference.frameIndex, 0, (int)item->children.size() - 1); + + if (isPreviousFrame || isNextFrame) + { + if (auto item = selected_item_get(); item && !item->children.empty()) + { + frames_selection_set_reference(); + document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); + } + } + + if (isPreviousItem) reference_set_adjacent_item(-1); + if (isNextItem) reference_set_adjacent_item(1); + } + + if (isTextPushed) ImGui::PopStyleColor(); + } +} diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp new file mode 100644 index 0000000..bf48618 --- /dev/null +++ b/src/imgui/window/timeline/timeline.cpp @@ -0,0 +1,67 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + Timeline::Timeline() = default; + Timeline::~Timeline() = default; + + TimelineContext::TimelineContext(Timeline& timeline, Manager& manager, Settings& settings, Resources& resources, + Clipboard& clipboard) + : timeline(timeline), isDragging(timeline.isDragging), isWindowHovered(timeline.isWindowHovered), + isHorizontalScroll(timeline.isHorizontalScroll), itemProperties(timeline.itemProperties), + bakePopup(timeline.bakePopup), bakeIntoOtherFramesPopup(timeline.bakeIntoOtherFramesPopup), + makeManyRegionsPopup(timeline.makeManyRegionsPopup), + bakeIntoOtherFramesTarget(timeline.bakeIntoOtherFramesTarget), + isBakeIntoOtherFramesLayers(timeline.isBakeIntoOtherFramesLayers), + isBakeIntoOtherFramesNulls(timeline.isBakeIntoOtherFramesNulls), + isMakeManyRegionsMapFrames(timeline.isMakeManyRegionsMapFrames), + makeManyRegionReferences(timeline.makeManyRegionReferences), hoveredTime(timeline.hoveredTime), + isFrameBoxPending(timeline.isFrameBoxPending), isFrameBoxSelecting(timeline.isFrameBoxSelecting), + isFrameBoxAdditive(timeline.isFrameBoxAdditive), frameBoxStart(timeline.frameBoxStart), + frameBoxEnd(timeline.frameBoxEnd), frameBoxSelection(timeline.frameBoxSelection), + rowSelectionAnchor(timeline.rowSelectionAnchor), isRowSelectionAnchorSet(timeline.isRowSelectionAnchorSet), + groupPropertiesPopup(timeline.groupPropertiesPopup), groupName(timeline.groupName), + groupAnimationIndex(timeline.groupAnimationIndex), groupType(timeline.groupType), groupId(timeline.groupId), + draggedFrameReference(timeline.draggedFrameReference), isDraggedFrameActive(timeline.isDraggedFrameActive), + draggedFrameType(timeline.draggedFrameType), draggedFrameIndex(timeline.draggedFrameIndex), + draggedFrameStart(timeline.draggedFrameStart), draggedFrameStartDuration(timeline.draggedFrameStartDuration), + draggedFrameStartDurations(timeline.draggedFrameStartDurations), + draggedFrameStartMouseX(timeline.draggedFrameStartMouseX), draggedFrameWidth(timeline.draggedFrameWidth), + isDraggedFrameSnapshot(timeline.isDraggedFrameSnapshot), frameFocusRequested(timeline.frameFocusRequested), + frameFocusIndex(timeline.frameFocusIndex), frameMoveDrag(timeline.frameMoveDrag), + frameSelectionSnapshot(timeline.frameSelectionSnapshot), frameSelectionLocked(timeline.frameSelectionLocked), + isFrameSelectionLocked(timeline.isFrameSelectionLocked), + frameSelectionSnapshotReference(timeline.frameSelectionSnapshotReference), + frameSelectionAnchor(timeline.frameSelectionAnchor), isFrameSelectionAnchorSet(timeline.isFrameSelectionAnchorSet), + animationLengthEditIndex(timeline.animationLengthEditIndex), rowDragReferences(timeline.rowDragReferences), + scroll(timeline.scroll), style(timeline.style), manager(manager), settings(settings), resources(resources), + clipboard(clipboard), document(*manager.get()), anm2(document.anm2), playback(document.playback), + reference(document.reference), frames(document.frames), region(document.region) + { + } + + void TimelineContext::update() + { + animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex); + rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f; + + style = ImGui::GetStyle(); + isLightTheme = settings.theme == theme::LIGHT; + isTextPushed = false; + if (isLightTheme) + { + ImGui::PushStyleColor(ImGuiCol_Text, TIMELINE_TEXT_COLOR_LIGHT); + isTextPushed = true; + } + + commands_bind(); + draw(); + } + + void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) + { + if (!manager.get()) return; + context = std::make_unique(*this, manager, settings, resources, clipboard); + context->update(); + } +} diff --git a/src/imgui/window/timeline.hpp b/src/imgui/window/timeline/timeline.hpp similarity index 95% rename from src/imgui/window/timeline.hpp rename to src/imgui/window/timeline/timeline.hpp index 60fb212..c3df6b0 100644 --- a/src/imgui/window/timeline.hpp +++ b/src/imgui/window/timeline/timeline.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -14,6 +15,8 @@ namespace anm2ed::imgui { + struct TimelineContext; + struct TimelineRowReference { int documentIndex{-1}; @@ -56,6 +59,8 @@ namespace anm2ed::imgui class Timeline { + friend struct TimelineContext; + bool isDragging{}; bool isWindowHovered{}; bool isHorizontalScroll{}; @@ -105,8 +110,11 @@ namespace anm2ed::imgui std::vector rowDragReferences{}; glm::vec2 scroll{}; ImGuiStyle style{}; + std::unique_ptr context{}; public: + Timeline(); + ~Timeline(); void update(Manager&, Settings&, Resources&, Clipboard&); }; } diff --git a/src/imgui/window/timeline/tracks.cpp b/src/imgui/window/timeline/tracks.cpp new file mode 100644 index 0000000..bb8fab3 --- /dev/null +++ b/src/imgui/window/timeline/tracks.cpp @@ -0,0 +1,629 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::item_child(const TimelineItemRow& row, int index) +{ + ImGui::PushID(index); + + auto type = row.type; + auto id = row.id; + auto row_reference_make = [&]() + { return Reference{reference.animationIndex, type, id, -1, row.rootGroupType, row.rootGroupId}; }; + if (row.isGroup) + { + auto group = row_group_get(row); + if (!group) + { + ImGui::PopID(); + return; + } + + auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; + auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); + auto isGroupVisible = group->isVisible; + auto colorVec = item_color_vec(type); + if (is_group_selected(row)) + { + if (isLightTheme) + colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; + else + colorVec = item_color_active_vec(type); + } + auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); + ImGui::PushStyleColor(ImGuiCol_ChildBg, color); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto groupChildMin = ImGui::GetWindowPos(); + auto groupChildMax = ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, + groupChildMin.y + ImGui::GetWindowSize().y); + + auto toggle_group = [&]() + { + auto targetRow = row; + auto targetAnimationIndex = reference.animationIndex; + edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, targetAnimationIndex); + auto container = + animation ? element_child_first_get(*animation, container_type_get(targetRow.type)) + : nullptr; + auto group = container ? element_child_id_get(*container, ElementType::GROUP, + targetRow.id) + : nullptr; + if (!group) return; + group->isExpanded = !group->isExpanded; + }); + }; + + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::InvisibleButton("##Group Button", itemSize); + auto groupButtonMin = ImGui::GetItemRectMin(); + auto groupButtonMax = ImGui::GetItemRectMax(); + auto mousePos = ImGui::GetIO().MousePos; + auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) + { return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; }; + auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); + bool isGroupTooltipDelayed{}; + if (isGroupHovered) + { + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + isGroupTooltipDelayed = + ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); + imguiStyle.HoverDelayNormal = previousTooltipDelay; + } + + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + { + rowDragReferences = row_drag_references_get(row); + ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), + (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); + ImGui::EndDragDropSource(); + } + + if (ImGui::BeginDragDropTarget()) + { + if (auto payload = ImGui::AcceptDragDropPayload( + "Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; + auto dropZone = DropZone::BEFORE; + if (mousePos.y >= groupButtonMax.y - groupDropThird) + dropZone = DropZone::AFTER; + else if (mousePos.y >= groupButtonMin.y + groupDropThird) + dropZone = DropZone::INSIDE; + auto isDropAfter = dropZone != DropZone::BEFORE; + auto payloadRows = (TimelineRowReference*)payload->Data; + auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); + std::vector draggedRows(payloadRows, payloadRows + payloadCount); + auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); + for (auto draggedRow : draggedRows) + if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false; + + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); + + if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); + } + ImGui::EndDragDropTarget(); + } + + ImGui::SetCursorPos(cursorPos); + auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; + ImGui::Image(resources.icons[folderIcon].id, icon_size_get()); + auto iconMin = ImGui::GetItemRectMin(); + auto iconMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icons[folderIcon].id, itemIconTint, false); + ImGui::SameLine(); + + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; + if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + { + auto targetAnimationIndex = reference.animationIndex; + auto targetType = type; + auto targetGroupId = group->id; + auto targetVisible = !isGroupVisible; + edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, targetAnimationIndex); + auto container = + animation ? element_child_first_get(*animation, container_type_get(targetType)) + : nullptr; + if (!container) return; + auto group = element_child_id_get(*container, ElementType::GROUP, targetGroupId); + if (!group) return; + group->isVisible = targetVisible; + }); + } + auto visibleButtonMin = ImGui::GetItemRectMin(); + auto visibleButtonMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icons[visibleIcon].id, itemIconTint, false); + ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); + auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); + if (isGroupTooltipDelayed && !isVisibleButtonHovered) + { + ImGui::BeginTooltip(); + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + 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); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); + ImGui::EndTooltip(); + } + if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + toggle_group(); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + group_properties_open(row, *group); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + ImGui::PopID(); + return; + } + + auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); + if (type != NONE && !item) + { + ImGui::PopID(); + return; + } + auto isItemVisible = item ? item->isVisible : false; + auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; + if (item && type == ROOT && row.rootGroupId != -1) + isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); + auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; + if (isOnlyShowLayers && type != LAYER) isVisible = false; + auto isReferenced = is_same_item(reference, row_reference_make()); + auto isItemSelected = is_row_selected(row); + + auto label = [&]() -> std::string + { + if (type == LAYER) + { + auto layer = layer_get(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 = null_get(id); + if (!null) return localize.get(TYPE_STRINGS[type]); + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); + } + return localize.get(TYPE_STRINGS[type]); + }(); + auto icon = TYPE_ICONS[type]; + auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint; + auto baseColorVec = item_color_vec(type); + auto activeColorVec = item_color_active_vec(type); + auto colorVec = baseColorVec; + if (isItemSelected && type != NONE) + { + if (isLightTheme) + colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; + else + colorVec = activeColorVec; + } + auto color = to_imvec4(colorVec); + color = !isVisible ? to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER) : color; + ImGui::PushStyleColor(ImGuiCol_ChildBg, color); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); + + if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto itemChildMin = ImGui::GetWindowPos(); + auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); + + if (type != NONE) + { + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::SetNextItemStorageID(id); + ImGui::InvisibleButton("##Item Button", itemSize); + auto itemButtonMin = ImGui::GetItemRectMin(); + auto itemButtonMax = ImGui::GetItemRectMax(); + auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + + if (type == LAYER || type == NULL_) + { + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) + { + rowDragReferences = row_drag_references_get(row); + ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), + (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); + ImGui::EndDragDropSource(); + } + + if (ImGui::BeginDragDropTarget()) + { + if (auto payload = ImGui::AcceptDragDropPayload( + "Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + { + auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); + drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); + + auto payloadRows = (TimelineRowReference*)payload->Data; + auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); + std::vector draggedRows(payloadRows, payloadRows + payloadCount); + if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, false); + } + ImGui::EndDragDropTarget(); + } + } + + if (isItemButtonHovered) + { + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) item_base_properties_open(type, id); + else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); + + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | + ImGuiHoveredFlags_NoSharedDelay; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + bool showItemTooltip = ImGui::BeginItemTooltip(); + imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; + imguiStyle.HoverDelayNormal = previousTooltipDelay; + + if (showItemTooltip) + { + auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); }; + auto visibleLabel = yesNoLabel(isVisible); + auto framesCount = item_frames_count(item); + + switch (type) + { + case ROOT: + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(localize.get(BASIC_ROOT)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + auto transformLabel = yesNoLabel(settings.previewIsRootTransform); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case LAYER: + { + auto layer = layer_get(id); + if (!layer) break; + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(layer->name.c_str()); + ImGui::PopFont(); + + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case NULL_: + { + auto nullInfo = null_get(id); + if (!nullInfo) break; + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(nullInfo->name.c_str()); + ImGui::PopFont(); + + auto rectLabel = yesNoLabel(nullInfo->isShowRect); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case TRIGGER: + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + default: + break; + } + + ImGui::EndTooltip(); + } + } + + auto contentCursorPos = cursorPos; + contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetCursorPos(contentCursorPos); + + ImGui::Image(resources.icons[icon].id, icon_size_get()); + overlay_icon(resources.icons[icon].id, iconTintCurrent, false); + ImGui::SameLine(); + if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + if (isReferenced) ImGui::PopFont(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; + if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + { + auto animationIndex = reference.animationIndex; + auto targetType = type; + auto targetID = id; + auto targetGroupType = row.rootGroupType; + auto targetGroupId = row.rootGroupId; + edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto item = command_item_get(document, animationIndex, targetType, targetID, + targetGroupType, targetGroupId); + if (!item) return; + item->isVisible = !item->isVisible; + }); + } + overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + + if (type == NULL_) + { + if (auto null = null_get(id)) + { + auto& isShowRect = null->isShowRect; + auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; + ImGui::SetCursorPos( + ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get())) + { + auto nullID = id; + edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto nulls = document.anm2.element_get(ElementType::NULLS); + auto null = nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) + : nullptr; + if (!null) return; + null->isShowRect = !null->isShowRect; + }); + } + overlay_icon(resources.icons[rectIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) + : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); + } + } + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + } + else + { + auto cursorPos = ImGui::GetCursorPos(); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + ImGui::SetCursorPos( + ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + + auto& isShowUnused = settings.timelineIsShowUnused; + auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; + if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get())) + isShowUnused = !isShowUnused; + overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) + : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); + + auto& showLayersOnly = settings.timelineIsOnlyShowLayers; + auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS; + ImGui::SetCursorPos( + ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get())) + showLayersOnly = !showLayersOnly; + overlay_icon(resources.icons[layersIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) + : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + ImGui::SetCursorPos(cursorPos); + + ImGui::BeginDisabled(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + ImGui::Text("(?)"); + ImGui::PopStyleColor(); + auto tooltipShortcuts = std::vformat( + localize.get(TOOLTIP_TIMELINE_SHORTCUTS), + std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, + settings.shortcutShortenFrame, settings.shortcutExtendFrame, + settings.shortcutPreviousFrame, settings.shortcutNextFrame, + settings.shortcutPreviousItem, settings.shortcutNextItem)); + ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); + ImGui::EndDisabled(); + } + } + ImGui::EndChild(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(2); + + ImGui::PopID(); + } + + void TimelineContext::items_child() +{ + auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + bool isItemsChildOpen = ImGui::BeginChild("##Items Child", itemsChildSize, ImGuiChildFlags_Borders); + ImGui::PopStyleVar(); + if (isItemsChildOpen) + { + auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - + ImGui::GetTextLineHeightWithSpacing() - + ImGui::GetStyle().ItemSpacing.y * 2); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) + { + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + { + auto rowReferences = timeline_row_references_get(); + row_selection_clear(); + for (auto rowReference : rowReferences) + row_selection_insert(rowReference); + if (!rowReferences.empty()) + { + rowSelectionAnchor = rowReferences.front(); + isRowSelectionAnchorSet = true; + } + frames_selection_reset_for(document); + } + + if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) && + !item_references_groupable_get().empty()) + item_group(); + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); + if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) + { + ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + ImGui::SetScrollY(scroll.y); + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Items"); + + auto item_child_row = [&](const TimelineItemRow& row, int index) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + item_child(row, index); + }; + + int index{}; + item_child_row({.type = NONE}, index++); + if (animation) + for (const auto& row : timeline_item_rows_get()) + item_child_row(row, index++); + + if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); + } + + ImGui::EndTable(); + } + ImGui::PopStyleVar(2); + + item_context_menu(); + } + ImGui::PopStyleVar(2); + ImGui::EndChild(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); + auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); + + ImGui::BeginDisabled(!animation); + { + shortcut(manager.chords[SHORTCUT_ADD]); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); + ImGui::SameLine(); + + auto selectedRows = selected_row_references_get(); + auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) + { return row.type == LAYER || row.type == NULL_; }); + ImGui::BeginDisabled(!isRemoveAvailable); + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); + ImGui::EndDisabled(); + } + ImGui::EndDisabled(); + + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + } +}