From 5792dd25a28d140a932a79fbd7e812c01c269c65 Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 9 Jul 2026 19:49:33 -0400 Subject: [PATCH] Overlays, Shaders, Group Roots, Serialization Changes. Legalize Nuclear Bombs --- src/anm2/anm2.cpp | 1101 +++++++++++- src/anm2/anm2.hpp | 40 +- src/canvas.cpp | 121 +- src/canvas.hpp | 2 +- src/clipboard.cpp | 4 +- src/dialog.hpp | 6 + src/document.cpp | 919 ++++++++-- src/document.hpp | 48 +- src/imgui/actions.cpp | 8 +- src/imgui/dockspace.cpp | 2 + src/imgui/dockspace.hpp | 3 + src/imgui/documents.cpp | 158 +- src/imgui/popup/item_properties.cpp | 2 +- src/imgui/taskbar.cpp | 10 +- src/imgui/window/animation_preview.cpp | 206 ++- src/imgui/window/frame_properties.cpp | 43 +- src/imgui/window/shaders.cpp | 430 +++++ src/imgui/window/shaders.hpp | 17 + src/imgui/window/spritesheet_editor.cpp | 110 +- src/imgui/window/timeline.cpp | 489 ++++-- src/imgui/window/timeline.hpp | 4 + src/imgui/window/window.cpp | 1540 ++++++++++++++++- src/imgui/window/window.hpp | 5 +- .../wizard/change_all_frame_properties.cpp | 21 +- src/imgui/wizard/configure.cpp | 12 +- .../wizard/generate_animation_from_grid.cpp | 5 +- src/imgui/wizard/render_animation.cpp | 44 +- src/manager.hpp | 3 + src/render.hpp | 37 + src/resource/shader.cpp | 460 ++++- src/resource/shader.hpp | 168 ++ src/resource/strings.hpp | 61 +- src/settings.cpp | 145 +- src/settings.hpp | 9 +- src/snapshots.cpp | 416 ++++- src/snapshots.hpp | 85 +- src/util/imgui/selectable.cpp | 47 +- src/util/imgui/selectable.hpp | 2 + src/util/imgui/tree.cpp | 41 + src/util/imgui/tree.hpp | 22 + 40 files changed, 6099 insertions(+), 747 deletions(-) create mode 100644 src/imgui/window/shaders.cpp create mode 100644 src/imgui/window/shaders.hpp create mode 100644 src/util/imgui/tree.cpp create mode 100644 src/util/imgui/tree.hpp diff --git a/src/anm2/anm2.cpp b/src/anm2/anm2.cpp index 8505d81..b8f804b 100644 --- a/src/anm2/anm2.cpp +++ b/src/anm2/anm2.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -28,9 +29,14 @@ namespace anm2ed 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) +#define ANM2_PATH_ATTRIBUTES \ + X("Path", path) \ + X("Vertex", vertex) \ + X("Fragment", fragment) #define ANM2_INT_ATTRIBUTES \ X("Id", id) \ @@ -45,13 +51,15 @@ namespace anm2ed X("EventId", eventId) \ X("RegionId", regionId) \ X("SoundId", soundId) \ - X("GroupId", groupId) + X("GroupId", groupId) \ + X("Index", index) #define ANM2_BOOL_ATTRIBUTES \ X("Loop", isLoop) \ X("Visible", isVisible) \ X("ShowRect", isShowRect) \ - X("Expanded", isExpanded) + X("IsExpanded", isExpanded) \ + X("Enabled", isEnabled) #define ANM2_FLOAT_ATTRIBUTES \ X("Rotation", rotation) \ @@ -87,11 +95,56 @@ namespace anm2ed "", "", "EaseIn", "EaseOut", "EaseInOut"}; constexpr std::array ORIGIN_VALUES = {"", "TopLeft", "Center"}; + constexpr std::string_view ANM2ED_GROUP_FRAME_BACKUP_TAG = "FrameRestore"; + void group_metadata_embed(Element&); + void group_metadata_extract(Element&, Flags); void groups_flatten(Element&); + void group_frames_restore(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{}; + for (const auto& child : animations.children) + if (child.type == ElementType::ANIMATION) ++count; + return count; + } + + int animations_child_index_get(const Element& animations, int animationIndex) + { + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + if (animations.children[i].type != ElementType::ANIMATION) continue; + if (current == animationIndex) return i; + ++current; + } + return -1; + } + + int animations_child_insert_index_get(const Element& animations, int animationIndex) + { + if (animationIndex <= 0) + { + for (int i = 0; i < (int)animations.children.size(); ++i) + if (animations.children[i].type == ElementType::ANIMATION) return i; + return (int)animations.children.size(); + } + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + if (animations.children[i].type != ElementType::ANIMATION) continue; + if (current == animationIndex) return i; + ++current; + } + return (int)animations.children.size(); + } + bool anm2_document_load(Anm2& anm2, XMLDocument& document, std::string* errorString) { auto rootElement = document.RootElement(); @@ -103,6 +156,8 @@ namespace anm2ed } anm2.root = element_read(rootElement); + group_metadata_embed(anm2.root); + group_frames_restore(anm2.root); groups_flatten(anm2.root); anm2.region_frames_sync(true); anm2.isValid = true; @@ -152,6 +207,188 @@ namespace anm2ed 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.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; @@ -297,13 +534,14 @@ namespace anm2ed auto restored = element_read(child); restored.interpolation = bakeInterpolation; restored.duration = bakeDelay; - out.children.push_back(std::move(restored)); + if (is_track_child_valid(out.type, restored.type)) out.children.push_back(std::move(restored)); child = bake_frames_skip(child, bakeDelay); continue; } } - out.children.push_back(element_read(child)); + auto childElement = element_read(child); + if (is_track_child_valid(out.type, childElement.type)) out.children.push_back(std::move(childElement)); child = child->NextSiblingElement(); } } @@ -342,8 +580,12 @@ namespace anm2ed 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::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 && !has_flag(flags, SERIALIZE_SOUNDS)) return true; @@ -399,10 +641,29 @@ namespace anm2ed } else if (element.type == ElementType::ANIMATIONS) out->SetAttribute("DefaultAnimation", element.defaultAnimation.c_str()); - else if (element.type == ElementType::SPRITESHEET) + else if (element.type == ElementType::SPRITESHEET || element.type == ElementType::OVERLAY) { out->SetAttribute("Id", element.id); path_set(out, "Path", element.path); + if (element.type == ElementType::OVERLAY && !element.isVisible) out->SetAttribute("Visible", element.isVisible); + } + else if (element.type == ElementType::SHADER) + { + if (!element.isEnabled) out->SetAttribute("Enabled", element.isEnabled); + 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) { @@ -430,8 +691,11 @@ namespace anm2ed { out->SetAttribute("Id", element.id); out->SetAttribute("Name", element.name.c_str()); - out->SetAttribute("Expanded", element.isExpanded); + 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) { @@ -448,6 +712,7 @@ namespace anm2ed out->SetAttribute("Name", element.name.c_str()); out->SetAttribute("FrameNum", element.frameNum); out->SetAttribute("Loop", element.isLoop); + if (element.groupId != -1 && has_flag(flags, SERIALIZE_GROUPS)) out->SetAttribute("GroupId", element.groupId); } else if (element.type == ElementType::LAYER_ANIMATION) { @@ -547,9 +812,435 @@ namespace anm2ed 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); + 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); + } + + 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 || element.type == ElementType::OVERLAY) + { + hash_attr_append(hash, "Id", element.id); + hash_path_attr_append(hash, "Path", element.path); + if (element.type == ElementType::OVERLAY && !element.isVisible) hash_attr_append(hash, "Visible", element.isVisible); + } + else if (element.type == ElementType::SHADER) + { + if (!element.isEnabled) hash_attr_append(hash, "Enabled", element.isEnabled); + 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) + { + 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 && has_flag(flags, SERIALIZE_GROUPS)) 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 && has_flag(flags, SERIALIZE_GROUPS)) 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 && has_flag(flags, SERIALIZE_GROUPS)) 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 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.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, '['); + 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 trackType) + auto container_flatten = [](Element& container, ElementType childType, bool isRootKept) { int nextGroupId{}; for (const auto& item : container.children) @@ -568,11 +1259,27 @@ namespace anm2ed 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 != trackType) continue; + if (child.type != childType) continue; child.groupId = groupId; flattened.push_back(child); } @@ -583,15 +1290,17 @@ namespace anm2ed if (item.type == ElementType::GROUP) groupIds.insert(item.id); for (auto& item : flattened) - if (item.type == trackType && !groupIds.contains(item.groupId)) item.groupId = -1; + if (item.type == childType && !groupIds.contains(item.groupId)) item.groupId = -1; container.children = std::move(flattened); }; - if (element.type == ElementType::LAYER_ANIMATIONS) - container_flatten(element, ElementType::LAYER_ANIMATION); + 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); + container_flatten(element, ElementType::NULL_ANIMATION, true); for (auto& child : element.children) groups_flatten(child); @@ -618,6 +1327,42 @@ namespace anm2ed 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) @@ -696,6 +1441,17 @@ namespace anm2ed element.type == ElementType::NULL_ANIMATION || element.type == ElementType::TRIGGERS; } + bool is_track_child_valid(ElementType parentType, ElementType childType) + { + if (parentType == ElementType::TRIGGERS) return childType == ElementType::TRIGGER; + 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; @@ -717,6 +1473,43 @@ namespace anm2ed 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; @@ -768,6 +1561,28 @@ namespace anm2ed 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; @@ -776,50 +1591,89 @@ namespace anm2ed return true; } - Element* animation_item_get(Element& animation, ItemType type, int id) + 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)); - return container ? track_find(*container, trackType, id) : nullptr; + 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) { - auto trackType = item_type_to_track_type_get(type); - if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType); + return animation_item_get(animation, type, id, NONE, -1); + } - auto container = child_first_get(animation, item_type_to_container_type_get(type)); - return container ? track_find(*container, trackType, id) : nullptr; + 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) { - if (index < 0) return nullptr; - auto frameType = track_frame_type_get(track); - int frameIndex{}; - for (auto& frame : track.children) - { - if (frame.type != frameType) continue; - if (frameIndex == index) return &frame; - ++frameIndex; - } - return nullptr; + 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) { - if (index < 0) return nullptr; - auto frameType = track_frame_type_get(track); - int frameIndex{}; - for (const auto& frame : track.children) - { - if (frame.type != frameType) continue; - if (frameIndex == index) return &frame; - ++frameIndex; - } - return nullptr; + auto childIndex = track_frame_child_index_get(track, index); + return childIndex == -1 ? nullptr : &track.children[childIndex]; } Element frame_generate(const Element& track, float time) @@ -936,8 +1790,10 @@ namespace anm2ed void frame_bake(Element& track, int index, int interval, bool isRoundScale, bool isRoundRotation) { - auto frame = track_frame_get(track, index); - if (!frame) return; + 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) @@ -949,8 +1805,9 @@ namespace anm2ed auto nextFrame = track_frame_get(track, index + 1); auto next = nextFrame ? *nextFrame : original; int duration{}; - int insertIndex = index; interval = std::max(interval, FRAME_DURATION_MIN); + std::vector bakedFrames{}; + bakedFrames.reserve((original.duration + interval - 1) / interval); while (duration < original.duration) { @@ -966,14 +1823,14 @@ namespace anm2ed 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); - + bakedFrames.push_back(baked); duration += baked.duration; - ++insertIndex; } + + 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, @@ -1017,17 +1874,22 @@ namespace anm2ed if (frameType == ElementType::FRAME) { - start = std::clamp(start, 0, (int)track.children.size()); - int count{}; + 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; - auto index = start + count; - track.children.insert(track.children.begin() + index, frame); - indices.insert(index); - ++count; + 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(); } @@ -1293,12 +2155,17 @@ namespace anm2ed XMLElement* Anm2::to_element(XMLDocument& document, Options options) const { - auto serialized = normalized_for_serialize(); + auto serialized = normalized_for_serialize(options.flags); serialized.region_frames_sync(true); return element_to_xml(document, serialized.root, ElementType::UNKNOWN, options.flags); } - std::uint64_t Anm2::hash(Options options) const { return std::hash{}(to_string(options)); } + std::uint64_t Anm2::hash(Options options) const + { + auto serialized = normalized_for_serialize(options.flags); + serialized.region_frames_sync(true); + return element_hash(serialized.root, options.flags); + } bool Anm2::is_special_interpolated_frames() const { return ::anm2ed::is_special_interpolated_frames(root); } @@ -1401,10 +2268,13 @@ namespace anm2ed } } - Anm2 Anm2::normalized_for_serialize() const + Anm2 Anm2::normalized_for_serialize(Flags flags) const { auto normalized = *this; + group_frames_restore(normalized.root); groups_flatten(normalized.root); + if (has_flag(flags, SERIALIZE_BAKE_GROUP_FRAMES)) group_frames_bake(normalized.root); + 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"; }); @@ -1515,6 +2385,18 @@ namespace anm2ed 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); @@ -1527,6 +2409,24 @@ namespace anm2ed 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{}; @@ -1769,11 +2669,22 @@ namespace anm2ed { 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); + } + auto frame = frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, t)); if (frame.size == glm::vec2() || !frame.isVisible) return; - auto layerTransform = transform * math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation); + auto layerTransform = itemTransform * math::quad_model_get(frame.size, frame.position, frame.pivot, + math::percent_to_unit(frame.scale), frame.rotation); for (auto& corner : CORNERS) { auto world = layerTransform * glm::vec4(corner, 0.0f, 1.0f); @@ -1885,7 +2796,7 @@ namespace anm2ed } bool Anm2::animations_deserialize(const std::string& string, int start, std::set& indices, - std::string* errorString) + std::string* errorString, std::set* groupIds) { XMLDocument document{}; if (document.Parse(string.c_str()) != XML_SUCCESS) @@ -1894,12 +2805,6 @@ namespace anm2ed return false; } - if (!document.FirstChildElement("Animation")) - { - if (errorString) *errorString = "No valid animation(s)."; - return false; - } - auto animations = element_get(ElementType::ANIMATIONS); if (!animations) { @@ -1907,17 +2812,46 @@ namespace anm2ed return false; } - start = std::clamp(start, 0, (int)animations->children.size()); - int count{}; - for (auto element = document.FirstChildElement("Animation"); element; - element = element->NextSiblingElement("Animation")) + 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 index = start + count; - animations->children.insert(animations->children.begin() + index, element_read(element)); - indices.insert(index); - ++count; + 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; } @@ -1939,14 +2873,28 @@ namespace anm2ed 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); @@ -2057,8 +3005,9 @@ namespace anm2ed for (auto it = sources.rbegin(); it != sources.rend(); ++it) { auto source = *it; - if (source == target || source < 0 || source >= (int)animations->children.size()) continue; - animations->children.erase(animations->children.begin() + source); + 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; } diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index 73a2fbc..84dbc18 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -22,6 +22,10 @@ X(CONTENT, "Content") \ X(SPRITESHEETS, "Spritesheets") \ X(SPRITESHEET, "Spritesheet") \ + X(OVERLAY, "Overlay") \ + X(SHADER, "Shader") \ + X(UNIFORM, "Uniform") \ + X(COMPONENT, "Component") \ X(REGION, "Region") \ X(LAYERS, "Layers") \ X(LAYER_ELEMENT, "Layer") \ @@ -35,8 +39,10 @@ X(ANIMATION, "Animation") \ X(ROOT_ANIMATION, "RootAnimation") \ X(LAYER_ANIMATIONS, "LayerAnimations") \ + X(LAYER_ANIMATION_GROUPS, "LayerAnimationGroups") \ X(LAYER_ANIMATION, "LayerAnimation") \ X(NULL_ANIMATIONS, "NullAnimations") \ + X(NULL_ANIMATION_GROUPS, "NullAnimationGroups") \ X(NULL_ANIMATION, "NullAnimation") \ X(GROUP, "Group") \ X(TRIGGERS, "Triggers") \ @@ -181,7 +187,8 @@ namespace anm2ed SERIALIZE_REGIONS = 1 << 1, SERIALIZE_SOUNDS = 1 << 2, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES = 1 << 3, - SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES = 1 << 4 + SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES = 1 << 4, + SERIALIZE_BAKE_GROUP_FRAMES = 1 << 5 }; using Flags = int; @@ -189,7 +196,8 @@ namespace anm2ed constexpr bool has_flag(Flags flags, Flag flag) { return (flags & flag) != 0; } constexpr Flags SERIALIZE_EDITOR_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_REDUNDANT_FRAME_REGION_VALUES; - constexpr Flags SERIALIZE_DEFAULT = SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES; + constexpr Flags SERIALIZE_DEFAULT = + SERIALIZE_EDITOR_DEFAULT | SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES | SERIALIZE_BAKE_GROUP_FRAMES; struct Options { @@ -233,6 +241,10 @@ namespace anm2ed std::string createdBy{"robot"}; std::string createdOn{}; std::filesystem::path path{}; + std::filesystem::path vertex{}; + std::filesystem::path fragment{}; + std::string binding{}; + std::string value{}; std::string defaultAnimation{}; int id{-1}; int layerId{-1}; @@ -247,10 +259,12 @@ namespace anm2ed int regionId{-1}; int soundId{-1}; int groupId{-1}; + int index{-1}; bool isLoop{true}; bool isVisible{true}; bool isShowRect{}; bool isExpanded{true}; + bool isEnabled{true}; Interpolation interpolation{Interpolation::NONE}; Origin origin{Origin::CUSTOM}; float rotation{}; @@ -270,6 +284,8 @@ namespace anm2ed int itemType{(int)ItemType::NONE}; int itemID{-1}; int frameIndex{-1}; + int groupType{(int)ItemType::NONE}; + int groupId{-1}; auto operator<=>(const Reference&) const = default; }; @@ -283,6 +299,10 @@ namespace anm2ed Flags = SERIALIZE_EDITOR_DEFAULT); Element* element_child_first_get(Element&, ElementType); const Element* element_child_first_get(const Element&, ElementType); + Element* shader_uniform_get(Element&, std::string_view, bool = false); + const Element* shader_uniform_get(const Element&, std::string_view); + Element* shader_uniform_component_get(Element&, int, bool = false); + const Element* shader_uniform_component_get(const Element&, int); Element* element_child_id_get(Element&, ElementType, int); const Element* element_child_id_get(const Element&, ElementType, int); int element_child_next_id_get(const Element&, ElementType); @@ -292,6 +312,13 @@ namespace anm2ed const Element* element_first_get(const Element&, ElementType); Element* animation_item_get(Element&, ItemType, int = -1); const Element* animation_item_get(const Element&, ItemType, int = -1); + Element* animation_item_get(Element&, ItemType, int, int, int); + const Element* animation_item_get(const Element&, ItemType, int, int, int); + Element* animation_group_get(Element&, int, int); + const Element* animation_group_get(const Element&, int, int); + Element* animation_group_root_get(Element&, int, int); + const Element* animation_group_root_get(const Element&, int, int); + Element* animation_group_root_ensure(Element&, int, int); ElementType item_type_to_track_type_get(ItemType); Element* track_frame_get(Element&, int); const Element* track_frame_get(const Element&, int); @@ -326,7 +353,7 @@ namespace anm2ed void special_interpolated_frames_bake(int, bool, bool); void region_frames_sync(bool); void region_ids_remap(); - Anm2 normalized_for_serialize() const; + Anm2 normalized_for_serialize(Flags = SERIALIZE_DEFAULT) const; Element* element_get(ElementType); const Element* element_get(ElementType) const; @@ -334,8 +361,12 @@ namespace anm2ed const Element* element_get(ElementType, int) const; Element* element_get(int, ItemType, int = -1); const Element* element_get(int, ItemType, int = -1) const; + Element* element_get(int, ItemType, int, int, int); + const Element* element_get(int, ItemType, int, int, int) const; Element* element_get(int, ItemType, int, int); const Element* element_get(int, ItemType, int, int) const; + Element* element_get(Reference); + const Element* element_get(Reference) const; std::set element_unused(ElementType) const; std::set element_unused(ElementType, const Element&) const; std::set element_unused(ElementType, int) const; @@ -347,7 +378,8 @@ namespace anm2ed types::destination::Type = types::destination::ALL); int null_animation_add(int, int = -1, std::string = {}, bool = false, types::destination::Type = types::destination::ALL); - bool animations_deserialize(const std::string&, int, std::set&, std::string* = nullptr); + bool animations_deserialize(const std::string&, int, std::set&, std::string* = nullptr, + std::set* = nullptr); int animations_merge(int, std::set&, types::merge::Type = types::merge::APPEND, bool = true); }; } diff --git a/src/canvas.cpp b/src/canvas.cpp index 9e6d689..c115476 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -165,17 +165,128 @@ namespace anm2ed canvas_blend_straight_set(); } + void texture_uniform_vec4_set(const shader::Uniform& uniform, vec4 value) + { + if (uniform.location == -1) return; + + switch (uniform.valueType) + { + case shader::UNIFORM_VALUE_FLOAT: + glUniform1f(uniform.location, value.x); + break; + case shader::UNIFORM_VALUE_VEC2: + glUniform2fv(uniform.location, 1, value_ptr(value)); + break; + case shader::UNIFORM_VALUE_VEC3: + glUniform3fv(uniform.location, 1, value_ptr(value)); + break; + case shader::UNIFORM_VALUE_VEC4: + glUniform4fv(uniform.location, 1, value_ptr(value)); + break; + default: + break; + } + } + + void texture_uniform_manual_set(const shader::Uniform& uniform) + { + if (uniform.location == -1) return; + + switch (uniform.valueType) + { + case shader::UNIFORM_VALUE_FLOAT: + glUniform1f(uniform.location, uniform.value.x); + break; + case shader::UNIFORM_VALUE_INT: + case shader::UNIFORM_VALUE_SAMPLER2D: + glUniform1i(uniform.location, uniform.intValue); + break; + case shader::UNIFORM_VALUE_VEC2: + glUniform2fv(uniform.location, 1, value_ptr(uniform.value)); + break; + case shader::UNIFORM_VALUE_VEC3: + glUniform3fv(uniform.location, 1, value_ptr(uniform.value)); + break; + case shader::UNIFORM_VALUE_VEC4: + glUniform4fv(uniform.location, 1, value_ptr(uniform.value)); + break; + default: + break; + } + } + + float texture_uniform_component_value_get(const shader::Uniform::Component& component, float playbackTime) + { + if (component.binding == shader::UNIFORM_BINDING_PLAYBACK_TIME) return playbackTime; + return component.value; + } + + vec4 texture_uniform_component_vec4_get(const shader::Uniform& uniform, float playbackTime) + { + return {texture_uniform_component_value_get(uniform.components[0], playbackTime), + texture_uniform_component_value_get(uniform.components[1], playbackTime), + texture_uniform_component_value_get(uniform.components[2], playbackTime), + texture_uniform_component_value_get(uniform.components[3], playbackTime)}; + } + + void texture_uniforms_set(Shader& shader, mat4 transform, vec4 tint, vec3 colorOffset, vec2 textureSize, + float playbackTime) + { + if (shader.uniforms.empty()) + { + glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_TEXTURE), 0); + glUniform3fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); + glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TINT), 1, value_ptr(tint)); + glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + return; + } + + for (const auto& uniform : shader.uniforms) + { + if (uniform.location == -1) continue; + + switch (uniform.binding) + { + case shader::UNIFORM_BINDING_MAIN_TEXTURE: + glUniform1i(uniform.location, 0); + break; + case shader::UNIFORM_BINDING_TRANSFORM: + if (uniform.valueType == shader::UNIFORM_VALUE_MAT4) + glUniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform)); + break; + case shader::UNIFORM_BINDING_FRAME_TINT: + texture_uniform_vec4_set(uniform, tint); + break; + case shader::UNIFORM_BINDING_COLOR_OFFSET: + texture_uniform_vec4_set(uniform, vec4(colorOffset, 0.0f)); + break; + case shader::UNIFORM_BINDING_TEXTURE_SIZE: + texture_uniform_vec4_set(uniform, vec4(textureSize, 0.0f, 0.0f)); + break; + case shader::UNIFORM_BINDING_PLAYBACK_TIME: + texture_uniform_vec4_set(uniform, vec4(playbackTime)); + break; + case shader::UNIFORM_BINDING_COMPONENTS: + texture_uniform_vec4_set(uniform, texture_uniform_component_vec4_get(uniform, playbackTime)); + break; + case shader::UNIFORM_BINDING_MANUAL: + texture_uniform_manual_set(uniform); + break; + default: + break; + } + } + } + void Canvas::texture_render(Shader& shader, GLuint& texture, mat4 transform, vec4 tint, vec3 colorOffset, - float* vertices) const + float* vertices, vec2 textureSize, float playbackTime) const { canvas_blend_premultiplied_set(); glUseProgram(shader.id); - glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_TEXTURE), 0); - glUniform3fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TINT), 1, value_ptr(tint)); - glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + texture_uniforms_set(shader, transform, tint, colorOffset, textureSize, playbackTime); + glVertexAttrib4fv(2, value_ptr(tint)); glBindVertexArray(textureVAO); diff --git a/src/canvas.hpp b/src/canvas.hpp index 1cd827a..4d3cc0a 100644 --- a/src/canvas.hpp +++ b/src/canvas.hpp @@ -61,7 +61,7 @@ namespace anm2ed void grid_render(resource::Shader&, float, glm::vec2, glm::ivec2 = glm::ivec2(32, 32), glm::ivec2 = {}, glm::vec4 = glm::vec4(1.0f)) const; void texture_render(resource::Shader&, GLuint&, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, - float* = (float*)TEXTURE_VERTICES) const; + float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f) const; void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; void rect_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f), diff --git a/src/clipboard.cpp b/src/clipboard.cpp index ddcaf6a..5145b31 100644 --- a/src/clipboard.cpp +++ b/src/clipboard.cpp @@ -16,7 +16,7 @@ namespace anm2ed return string; } - bool Clipboard::is_empty() { return get().empty(); } + bool Clipboard::is_empty() { return !SDL_HasClipboardText(); } - void Clipboard::set(const std::string& string) { SDL_SetClipboardText(string.data()); } + void Clipboard::set(const std::string& string) { SDL_SetClipboardText(string.c_str()); } } diff --git a/src/dialog.hpp b/src/dialog.hpp index 7993749..272591c 100644 --- a/src/dialog.hpp +++ b/src/dialog.hpp @@ -20,6 +20,7 @@ namespace anm2ed X(NO_FILTER, {}) \ X(ANM2, {"Anm2 file", "anm2;xml"}) \ X(PNG, {"PNG image", "png;PNG"}) \ + X(SHADER, {"Shader file", "fs;vs;FS;VS"}) \ X(SOUND, {"WAV file;OGG file", "wav;ogg"}) \ X(GIF, {"GIF image", "gif"}) \ X(WEBM, {"WebM video", "webm"}) \ @@ -48,9 +49,14 @@ namespace anm2ed X(ANM2_SAVE, ANM2) \ X(SOUND_OPEN, SOUND) \ X(SOUND_REPLACE, SOUND) \ + X(OVERLAY_OPEN, PNG) \ + X(OVERLAY_REPLACE, PNG) \ + X(OVERLAY_PATH_SET, PNG) \ X(SPRITESHEET_OPEN, PNG) \ X(SPRITESHEET_REPLACE, PNG) \ X(SPRITESHEET_PATH_SET, PNG) \ + X(SHADER_FRAGMENT_PATH_SET, SHADER) \ + X(SHADER_VERTEX_PATH_SET, SHADER) \ X(FFMPEG_PATH_SET, EXECUTABLE) \ X(PNG_DIRECTORY_SET, NO_FILTER) \ X(PNG_PATH_SET, PNG) \ diff --git a/src/document.cpp b/src/document.cpp index e9d1db3..8a0b200 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -14,6 +15,7 @@ #include +#include "file.hpp" #include "log.hpp" #include "manager.hpp" #include "path.hpp" @@ -57,6 +59,185 @@ namespace anm2ed::document } } + const Element* shader_element_get(const Element& spritesheet) + { + return element_child_first_get(spritesheet, ElementType::SHADER); + } + + Element* shader_element_get(Element& spritesheet) + { + return element_child_first_get(spritesheet, ElementType::SHADER); + } + + std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) + { + auto loadPath = path::backslash_handle(path); + if (loadPath.empty() || loadPath.is_absolute()) return loadPath; + return document.directory_get() / loadPath; + } + + void shader_status_append(const resource::ShaderCompileResult& result, std::string* status) + { + if (!status) return; + + *status += localize.get(result.isCompiled ? LABEL_SHADER_COMPILE_SUCCEEDED : LABEL_SHADER_COMPILE_FAILED); + *status += "\n"; + if (result.isCompiled) + { + *status += localize.get(result.isLinked ? LABEL_SHADER_LINK_SUCCEEDED : LABEL_SHADER_LINK_FAILED); + *status += "\n"; + } + if (!result.output.empty()) *status += result.output; + } + + std::string shader_source_lines_get(std::string_view label, std::string_view source) + { + std::string output = std::format("\n{}:\n", label); + int lineNumber{1}; + std::size_t position{}; + while (position <= source.size()) + { + auto end = source.find('\n', position); + auto isEnd = end == std::string_view::npos; + auto line = source.substr(position, isEnd ? std::string_view::npos : end - position); + output += std::format("{:4}: {}\n", lineNumber++, line); + if (isEnd) break; + position = end + 1; + } + return output; + } + + bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, + StringType label, std::string* status, const char* fallback = nullptr) + { + if (shaderPath.empty()) + { + if (fallback) + { + source = fallback; + return true; + } + + if (status) + { + auto labelString = std::string(localize.get(label)); + *status += std::vformat(localize.get(LABEL_SHADER_PATH_EMPTY), std::make_format_args(labelString)) + "\n"; + } + return false; + } + + auto absolute = path::case_insensitive_find(shader_absolute_path_get(document, shaderPath)); + if (file::read_to_string(absolute, &source)) return true; + + if (status) + { + auto pathString = path::to_utf8(shaderPath); + *status += std::vformat(localize.get(LABEL_SHADER_READ_FAILED), std::make_format_args(pathString)) + "\n"; + } + return false; + } + + void shader_uniform_configs_apply(const Element& shaderElement, resource::Shader& shader) + { + for (auto& uniform : shader.uniforms) + { + auto config = shader_uniform_get(shaderElement, uniform.name); + if (!config) continue; + + if (!config->binding.empty()) + { + auto binding = resource::shader::uniform_binding_get(config->binding); + if (resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) uniform.binding = binding; + } + if (!config->value.empty()) resource::shader::uniform_value_parse(uniform, config->value); + for (int index = 0; index < (int)uniform.components.size(); ++index) + { + auto component = shader_uniform_component_get(*config, index); + if (!component) continue; + + if (!component->binding.empty()) + { + auto binding = resource::shader::uniform_binding_get(component->binding); + if (binding == resource::shader::UNIFORM_BINDING_MANUAL || + binding == resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) + uniform.components[index].binding = binding; + } + if (!component->value.empty()) + { + std::stringstream stream{component->value}; + stream >> uniform.components[index].value; + } + } + } + } + + bool shader_uniform_configs_trim(Element& shaderElement, const resource::Shader& shader) + { + auto component_count_get = [](resource::shader::UniformValueType type) + { + if (type == resource::shader::UNIFORM_VALUE_VEC2) return 2; + if (type == resource::shader::UNIFORM_VALUE_VEC3) return 3; + if (type == resource::shader::UNIFORM_VALUE_VEC4) return 4; + return 0; + }; + + bool isChanged{}; + for (auto it = shaderElement.children.begin(); it != shaderElement.children.end();) + { + if (it->type != ElementType::UNIFORM) + { + ++it; + continue; + } + + auto uniform = + std::find_if(shader.uniforms.begin(), shader.uniforms.end(), + [&](const resource::shader::Uniform& uniform) { return uniform.name == it->name; }); + if (uniform == shader.uniforms.end()) + { + it = shaderElement.children.erase(it); + isChanged = true; + continue; + } + + if (!it->binding.empty()) + { + auto binding = resource::shader::uniform_binding_get(it->binding); + if (!resource::shader::is_uniform_binding_valid(binding, uniform->valueType)) + { + it->binding.clear(); + isChanged = true; + } + } + + auto componentCount = component_count_get(uniform->valueType); + auto isComponents = resource::shader::uniform_binding_get(it->binding) == resource::shader::UNIFORM_BINDING_COMPONENTS; + auto removed = std::erase_if(it->children, + [&](const Element& component) + { + if (component.type != ElementType::COMPONENT) return false; + if (!isComponents) return true; + return component.index < 0 || component.index >= componentCount; + }); + if (removed > 0) isChanged = true; + + for (auto& component : it->children) + { + if (component.type != ElementType::COMPONENT || component.binding.empty()) continue; + auto binding = resource::shader::uniform_binding_get(component.binding); + if (binding == resource::shader::UNIFORM_BINDING_MANUAL || + binding == resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) + continue; + component.binding.clear(); + isChanged = true; + } + + ++it; + } + + return isChanged; + } + Element* frame_region_match_get(Element& spritesheet, const Element& frame) { auto frameCrop = glm::ivec2(frame.crop); @@ -130,6 +311,41 @@ namespace anm2ed::document return ids; } + std::vector overlay_labels_get(const Element* spritesheet) + { + std::vector labels{}; + if (!spritesheet) return labels; + for (auto& overlay : spritesheet->children) + if (overlay.type == ElementType::OVERLAY) + { + auto pathString = path::to_utf8(overlay.path); + labels.emplace_back(std::vformat(localize.get(FORMAT_OVERLAY), std::make_format_args(overlay.id, pathString))); + } + return labels; + } + + std::vector overlay_ids_get(const Element* spritesheet) + { + std::vector ids{}; + if (!spritesheet) return ids; + for (auto& overlay : spritesheet->children) + if (overlay.type == ElementType::OVERLAY) ids.emplace_back(overlay.id); + return ids; + } + + int overlay_next_id_get(const Anm2& data) + { + int nextId{}; + if (auto spritesheets = data.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY) nextId = std::max(nextId, overlay.id + 1); + } + return nextId; + } + std::vector sound_labels_get(const Anm2& data) { std::vector labels{localize.get(BASIC_NONE)}; @@ -198,13 +414,18 @@ namespace anm2ed::document if (reference.animationIndex < 0 || reference.animationIndex >= animationCount) reference.animationIndex = std::clamp(reference.animationIndex, 0, animationCount - 1); - auto item = - document.anm2.element_get(reference.animationIndex, item_type_get(reference.itemType), reference.itemID); + auto referenceItem = reference; + referenceItem.frameIndex = -1; + auto item = document.anm2.element_get(referenceItem); if (!item) { reference.itemType = (int)ItemType::ROOT; reference.itemID = -1; - item = document.anm2.element_get(reference.animationIndex, item_type_get(reference.itemType), reference.itemID); + reference.groupType = (int)ItemType::NONE; + reference.groupId = -1; + referenceItem = reference; + referenceItem.frameIndex = -1; + item = document.anm2.element_get(referenceItem); } if (!item) @@ -219,7 +440,9 @@ namespace anm2ed::document for (auto it = itemReferences.begin(); it != itemReferences.end();) { - auto item = document.anm2.element_get(it->animationIndex, item_type_get(it->itemType), it->itemID); + auto itemReference = *it; + itemReference.frameIndex = -1; + auto item = document.anm2.element_get(itemReference); if (!item) it = itemReferences.erase(it); else @@ -243,7 +466,9 @@ namespace anm2ed::document for (auto it = frameReferences.begin(); it != frameReferences.end();) { - auto item = document.anm2.element_get(it->animationIndex, item_type_get(it->itemType), it->itemID); + auto itemReference = *it; + itemReference.frameIndex = -1; + auto item = document.anm2.element_get(itemReference); auto frameCount = item ? frame_count_get(*item) : 0; if (!item || it->frameIndex < 0 || it->frameIndex >= frameCount) it = frameReferences.erase(it); @@ -274,12 +499,17 @@ namespace anm2ed::document if (frameReferences.empty()) for (auto frameIndex : selection) - frameReferences.insert({reference.animationIndex, reference.itemType, reference.itemID, frameIndex}); + { + auto frameReference = reference; + frameReference.frameIndex = frameIndex; + frameReferences.insert(frameReference); + } selection.clear(); for (const auto& frameReference : frameReferences) if (frameReference.animationIndex == reference.animationIndex && frameReference.itemType == reference.itemType && - frameReference.itemID == reference.itemID) + frameReference.itemID == reference.itemID && frameReference.groupType == reference.groupType && + frameReference.groupId == reference.groupId) selection.insert(frameReference.frameIndex); document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); @@ -322,18 +552,23 @@ namespace anm2ed Document::Document(Document&& other) noexcept : path(std::move(other.path)), tabId(other.tabId), snapshots(std::move(other.snapshots)), current(snapshots.current), playback(current.playback), animation(current.animation), event(current.event), frames(current.frames), - items(current.items), layer(current.layer), merge(current.merge), null(current.null), region(current.region), - sound(current.sound), spritesheet(current.spritesheet), textures(current.textures), sounds(current.sounds), - anm2(current.anm2), reference(current.reference), groupReferences(current.groupReferences), + items(current.items), layer(current.layer), merge(current.merge), null(current.null), overlay(current.overlay), + region(current.region), sound(current.sound), spritesheet(current.spritesheet), textures(current.textures), + overlayTextures(current.overlayTextures), sounds(current.sounds), anm2(current.anm2), + reference(current.reference), groupReferences(current.groupReferences), frameTime(current.frameTime), message(current.message), regionBySpritesheet(std::move(other.regionBySpritesheet)), changeAllFramePropertiesRegionId(other.changeAllFramePropertiesRegionId), previewZoom(other.previewZoom), previewPan(other.previewPan), editorPan(other.editorPan), editorZoom(other.editorZoom), overlayIndex(other.overlayIndex), hash(other.hash), saveHash(other.saveHash), autosaveHash(other.autosaveHash), lastAutosaveTime(other.lastAutosaveTime), isValid(other.isValid), isOpen(other.isOpen), isForceDirty(other.isForceDirty), spritesheetHashes(std::move(other.spritesheetHashes)), - spritesheetSaveHashes(std::move(other.spritesheetSaveHashes)), texturePaths(std::move(other.texturePaths)), - soundPaths(std::move(other.soundPaths)), isAnimationPreviewSet(other.isAnimationPreviewSet), - isSpritesheetEditorSet(other.isSpritesheetEditorSet), editTarget(other.editTarget) + spritesheetSaveHashes(std::move(other.spritesheetSaveHashes)), overlayHashes(std::move(other.overlayHashes)), + overlaySaveHashes(std::move(other.overlaySaveHashes)), texturePaths(std::move(other.texturePaths)), + overlayTexturePaths(std::move(other.overlayTexturePaths)), soundPaths(std::move(other.soundPaths)), + shaderVertexPaths(std::move(other.shaderVertexPaths)), + shaderFragmentPaths(std::move(other.shaderFragmentPaths)), shaders(std::move(other.shaders)), + isAnimationPreviewSet(other.isAnimationPreviewSet), isSpritesheetEditorSet(other.isSpritesheetEditorSet), + editTarget(other.editTarget) { } @@ -420,6 +655,13 @@ namespace anm2ed change(SPRITESHEETS); } + void Document::overlay_texture_change(int id) + { + auto texture = overlay_texture_get(id); + if (!texture || !overlay_get(id)) return; + change(SPRITESHEETS); + } + bool Document::texture_reload(int id) { auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); @@ -431,6 +673,17 @@ namespace anm2ed return true; } + bool Document::overlay_texture_reload(int id) + { + auto overlay = overlay_get(id); + if (!overlay) return false; + + util::WorkingDirectory workingDirectory(directory_get()); + overlayTextures[id] = resource::Texture(path::case_insensitive_find(overlay->path)); + overlayTexturePaths[id] = overlay->path; + return true; + } + bool Document::sound_reload(int id) { auto sound = anm2.element_get(ElementType::SOUND_ELEMENT, id); @@ -442,11 +695,71 @@ namespace anm2ed return true; } + bool Document::shader_reload(int id, std::string* status) + { + auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); + auto shaderElement = spritesheet ? document::shader_element_get(*spritesheet) : nullptr; + if (!shaderElement || !shaderElement->isEnabled) + { + if (status && !shaderElement) + { + auto labelString = std::string(localize.get(LABEL_FRAGMENT)); + *status += std::vformat(localize.get(LABEL_SHADER_PATH_EMPTY), std::make_format_args(labelString)) + "\n"; + } + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); + return false; + } + + std::string vertexSource{}; + std::string fragmentSource{}; + auto isVertexLoaded = document::shader_source_load(*this, shaderElement->vertex, vertexSource, LABEL_VERTEX, status, + resource::shader::TEXTURE_COMPATIBILITY_VERTEX); + auto isFragmentLoaded = + document::shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); + if (!isVertexLoaded || !isFragmentLoaded) + { + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); + return false; + } + + auto vertex = resource::shader::gles_vertex_convert(vertexSource); + auto fragment = resource::shader::gles_fragment_convert(fragmentSource); + auto result = resource::shader_compile(vertex.c_str(), fragment.c_str()); + document::shader_status_append(result, status); + if (status && (!result.isCompiled || !result.isLinked)) + { + *status += document::shader_source_lines_get("Converted vertex shader", vertex); + *status += document::shader_source_lines_get("Converted fragment shader", fragment); + } + if (!result.isLinked || !result.id) + { + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); + return false; + } + + resource::Shader runtime{}; + runtime.id = result.id; + runtime.uniforms = std::move(result.uniforms); + if (document::shader_uniform_configs_trim(*shaderElement, runtime)) hash_set(); + document::shader_uniform_configs_apply(*shaderElement, runtime); + shaders[id] = std::move(runtime); + shaderVertexPaths[id] = shaderElement->vertex; + shaderFragmentPaths[id] = shaderElement->fragment; + return true; + } + void Document::assets_sync(ChangeType type) { if (type == ALL || type == SPRITESHEETS || type == TEXTURES) { std::set validIds{}; + std::set validOverlayIds{}; util::WorkingDirectory workingDirectory(directory_get()); if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) for (auto& spritesheet : spritesheets->children) @@ -460,6 +773,38 @@ namespace anm2ed textures[spritesheet.id] = resource::Texture(path::case_insensitive_find(spritesheet.path)); texturePaths[spritesheet.id] = spritesheet.path; } + + for (auto& overlay : spritesheet.children) + { + if (overlay.type != ElementType::OVERLAY) continue; + validOverlayIds.insert(overlay.id); + auto isOverlayReload = !overlayTextures.contains(overlay.id) || !overlayTexturePaths.contains(overlay.id) || + overlayTexturePaths.at(overlay.id) != overlay.path; + if (isOverlayReload) + { + overlayTextures[overlay.id] = resource::Texture(path::case_insensitive_find(overlay.path)); + overlayTexturePaths[overlay.id] = overlay.path; + } + } + + auto shaderElement = document::shader_element_get(spritesheet); + if (!shaderElement || !shaderElement->isEnabled || shaderElement->fragment.empty()) + { + shaders.erase(spritesheet.id); + shaderVertexPaths.erase(spritesheet.id); + shaderFragmentPaths.erase(spritesheet.id); + continue; + } + + auto isShaderReload = + !shaders.contains(spritesheet.id) || !shaderVertexPaths.contains(spritesheet.id) || + !shaderFragmentPaths.contains(spritesheet.id) || + shaderVertexPaths.at(spritesheet.id) != shaderElement->vertex || + shaderFragmentPaths.at(spritesheet.id) != shaderElement->fragment; + if (isShaderReload) + shader_reload(spritesheet.id); + else if (auto shader = shader_get(spritesheet.id)) + document::shader_uniform_configs_apply(*shaderElement, *shader); } for (auto it = textures.begin(); it != textures.end();) @@ -472,6 +817,29 @@ namespace anm2ed else ++it; } + + for (auto it = overlayTextures.begin(); it != overlayTextures.end();) + { + if (!validOverlayIds.contains(it->first)) + { + overlayTexturePaths.erase(it->first); + it = overlayTextures.erase(it); + } + else + ++it; + } + + for (auto it = shaders.begin(); it != shaders.end();) + { + if (!validIds.contains(it->first)) + { + shaderVertexPaths.erase(it->first); + shaderFragmentPaths.erase(it->first); + it = shaders.erase(it); + } + else + ++it; + } } if (type == ALL || type == SOUNDS) @@ -517,6 +885,18 @@ namespace anm2ed return it == textures.end() ? nullptr : &it->second; } + resource::Texture* Document::overlay_texture_get(int id) + { + auto it = overlayTextures.find(id); + return it == overlayTextures.end() ? nullptr : &it->second; + } + + const resource::Texture* Document::overlay_texture_get(int id) const + { + auto it = overlayTextures.find(id); + return it == overlayTextures.end() ? nullptr : &it->second; + } + resource::Audio* Document::sound_get(int id) { auto it = sounds.find(id); @@ -529,6 +909,18 @@ namespace anm2ed return it == sounds.end() ? nullptr : &it->second; } + resource::Shader* Document::shader_get(int id) + { + auto it = shaders.find(id); + return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; + } + + const resource::Shader* Document::shader_get(int id) const + { + auto it = shaders.find(id); + return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; + } + bool Document::regions_trim(int spritesheetId, const std::set& ids) { auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); @@ -598,7 +990,7 @@ namespace anm2ed { if (animationIndices.empty()) return false; - int regionNumber{}; + std::unordered_map regionNumbers{}; bool isChanged{}; for (auto animationIndex : animationIndices) { @@ -631,6 +1023,8 @@ namespace anm2ed { auto generated = element_make(ElementType::REGION); generated.id = element_child_next_id_get(*spritesheet, ElementType::REGION); + auto [regionNumberIt, _] = regionNumbers.try_emplace(layer->spritesheetId, 1); + auto& regionNumber = regionNumberIt->second; generated.name = document::region_name_get(format, regionNumber++); generated.crop = frame.crop; generated.size = frame.size; @@ -658,14 +1052,13 @@ namespace anm2ed bool Document::regions_generate_from_frames(const std::set& frameReferences, const std::string& format, RegionFrameMapping mapping) { - int regionNumber{}; + std::unordered_map regionNumbers{}; bool isChanged{}; for (auto frameReference : frameReferences) { if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) continue; - auto frame = anm2.element_get(frameReference.animationIndex, ItemType::LAYER, frameReference.itemID, - frameReference.frameIndex); + auto frame = anm2.element_get(frameReference); if (!frame || frame->type != ElementType::FRAME || frame->regionId != -1) continue; auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); @@ -677,6 +1070,7 @@ namespace anm2ed { auto generated = element_make(ElementType::REGION); generated.id = element_child_next_id_get(*spritesheet, ElementType::REGION); + auto& regionNumber = regionNumbers[layer->spritesheetId]; generated.name = document::region_name_get(format, regionNumber++); generated.crop = frame->crop; generated.size = frame->size; @@ -1118,11 +1512,14 @@ namespace anm2ed } } - bool Document::file_merge(const std::filesystem::path& path) + bool Document::file_merge(const std::filesystem::path& path, FileMergePreset preset) { Anm2 source(path); if (!source.isValid) return false; + bool isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; + bool isReplaceMatching = preset == FILE_MERGE_PRESET_REPLACE_MATCHING; + auto remap_path = [&](const std::filesystem::path& original) -> std::filesystem::path { if (directory_get().empty()) return original; @@ -1168,6 +1565,39 @@ namespace anm2ed return (Element*)nullptr; }; + auto name_unique_get = [&](Element& container, ElementType type, const std::string& name) + { + if (!find_by_name(container, type, name)) return name; + for (int i = 2;; ++i) + { + auto candidate = std::format("{} {}", name, i); + if (!find_by_name(container, type, candidate)) return candidate; + } + }; + + auto named_element_merge = [&](Element& container, Element item, ElementType type) + { + if (isAppendAsNew) + { + item.id = element_child_next_id_get(container, type); + item.name = name_unique_get(container, type, item.name); + container.children.push_back(item); + return item.id; + } + + if (auto existing = find_by_name(container, type, item.name)) + { + item.id = existing->id; + *existing = item; + } + else + { + item.id = element_child_next_id_get(container, type); + container.children.push_back(item); + } + return item.id; + }; + auto child_set = [](Element& container, Element child, ElementType type) { if (auto existing = element_child_first_get(container, type)) @@ -1206,17 +1636,24 @@ namespace anm2ed std::unordered_map eventRemap{}; std::unordered_map soundRemap{}; - if (auto sourceSpritesheets = source.element_get(ElementType::SPRITESHEETS)) - if (auto destinationSpritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto spritesheet : sourceSpritesheets->children) - { - if (spritesheet.type != ElementType::SPRITESHEET) continue; - auto sourceId = spritesheet.id; - spritesheet.id = element_child_next_id_get(*destinationSpritesheets, ElementType::SPRITESHEET); - spritesheet.path = remap_path(spritesheet.path); - destinationSpritesheets->children.push_back(spritesheet); - spritesheetRemap[sourceId] = spritesheet.id; - } + auto spritesheet_import = [&](int sourceId) + { + if (sourceId < 0) return -1; + if (spritesheetRemap.contains(sourceId)) return spritesheetRemap[sourceId]; + + auto sourceSpritesheets = source.element_get(ElementType::SPRITESHEETS); + auto destinationSpritesheets = anm2.element_get(ElementType::SPRITESHEETS); + auto spritesheet = + sourceSpritesheets ? element_child_id_get(*sourceSpritesheets, ElementType::SPRITESHEET, sourceId) : nullptr; + if (!spritesheet || !destinationSpritesheets) return -1; + + auto imported = *spritesheet; + imported.id = element_child_next_id_get(*destinationSpritesheets, ElementType::SPRITESHEET); + imported.path = remap_path(imported.path); + destinationSpritesheets->children.push_back(imported); + spritesheetRemap[sourceId] = imported.id; + return imported.id; + }; if (auto sourceSounds = source.element_get(ElementType::SOUNDS)) if (auto destinationSounds = anm2.element_get(ElementType::SOUNDS)) @@ -1226,14 +1663,15 @@ namespace anm2ed auto sourceId = sound.id; sound.path = remap_path(sound.path); int destinationId{-1}; - for (auto& existing : destinationSounds->children) - if (existing.type == ElementType::SOUND_ELEMENT && existing.path == sound.path) - { - destinationId = existing.id; - sound.id = destinationId; - existing = sound; - break; - } + if (!isAppendAsNew) + for (auto& existing : destinationSounds->children) + if (existing.type == ElementType::SOUND_ELEMENT && existing.path == sound.path) + { + destinationId = existing.id; + sound.id = destinationId; + existing = sound; + break; + } if (destinationId == -1) { destinationId = element_child_next_id_get(*destinationSounds, ElementType::SOUND_ELEMENT); @@ -1249,18 +1687,11 @@ namespace anm2ed { if (layer.type != ElementType::LAYER_ELEMENT) continue; auto sourceId = layer.id; - layer.spritesheetId = remap_id(spritesheetRemap, layer.spritesheetId); - if (auto existing = find_by_name(*destinationLayers, ElementType::LAYER_ELEMENT, layer.name)) - { - layer.id = existing->id; - *existing = layer; - } - else - { - layer.id = element_child_next_id_get(*destinationLayers, ElementType::LAYER_ELEMENT); - destinationLayers->children.push_back(layer); - } - layerRemap[sourceId] = layer.id; + auto sourceSpritesheetId = layer.spritesheetId; + auto existing = + isAppendAsNew ? nullptr : find_by_name(*destinationLayers, ElementType::LAYER_ELEMENT, layer.name); + layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(sourceSpritesheetId); + layerRemap[sourceId] = named_element_merge(*destinationLayers, layer, ElementType::LAYER_ELEMENT); } if (auto sourceNulls = source.element_get(ElementType::NULLS)) @@ -1269,17 +1700,7 @@ namespace anm2ed { if (null.type != ElementType::NULL_ELEMENT) continue; auto sourceId = null.id; - if (auto existing = find_by_name(*destinationNulls, ElementType::NULL_ELEMENT, null.name)) - { - null.id = existing->id; - *existing = null; - } - else - { - null.id = element_child_next_id_get(*destinationNulls, ElementType::NULL_ELEMENT); - destinationNulls->children.push_back(null); - } - nullRemap[sourceId] = null.id; + nullRemap[sourceId] = named_element_merge(*destinationNulls, null, ElementType::NULL_ELEMENT); } if (auto sourceEvents = source.element_get(ElementType::EVENTS)) @@ -1288,17 +1709,7 @@ namespace anm2ed { if (event.type != ElementType::EVENT_ELEMENT) continue; auto sourceId = event.id; - if (auto existing = find_by_name(*destinationEvents, ElementType::EVENT_ELEMENT, event.name)) - { - event.id = existing->id; - *existing = event; - } - else - { - event.id = element_child_next_id_get(*destinationEvents, ElementType::EVENT_ELEMENT); - destinationEvents->children.push_back(event); - } - eventRemap[sourceId] = event.id; + eventRemap[sourceId] = named_element_merge(*destinationEvents, event, ElementType::EVENT_ELEMENT); } auto item_remap = [&](Element& item) @@ -1321,6 +1732,15 @@ namespace anm2ed group.id = item.id == -1 ? element_child_next_id_get(container, ElementType::GROUP) : item.id; group.name = item.name; group.isExpanded = item.isExpanded; + group.isVisible = item.isVisible; + if (auto root = element_child_first_get(item, ElementType::ROOT_ANIMATION)) + group.children.push_back(*root); + else + { + auto defaultRoot = element_make(ElementType::ROOT_ANIMATION); + defaultRoot.children.push_back(element_make(ElementType::FRAME)); + group.children.push_back(defaultRoot); + } container.children.push_back(group); for (auto child : item.children) self(self, child, itemType, container, group.id); @@ -1396,7 +1816,14 @@ namespace anm2ed if (item.type != ElementType::GROUP) continue; auto sourceGroupId = item.id; item.id = element_child_next_id_get(destinationContainer, ElementType::GROUP); - item.children.clear(); + std::erase_if(item.children, [](const Element& child) + { return child.type != ElementType::ROOT_ANIMATION; }); + if (!element_child_first_get(item, ElementType::ROOT_ANIMATION)) + { + auto root = element_make(ElementType::ROOT_ANIMATION); + root.children.push_back(element_make(ElementType::FRAME)); + item.children.push_back(root); + } destinationContainer.children.push_back(item); groupRemap[sourceGroupId] = item.id; } @@ -1413,17 +1840,30 @@ namespace anm2ed if (auto sourceAnimations = source.element_get(ElementType::ANIMATIONS)) if (auto destinationAnimations = anm2.element_get(ElementType::ANIMATIONS)) { + std::string defaultAnimationName{}; for (const auto& incoming : sourceAnimations->children) { if (incoming.type != ElementType::ANIMATION) continue; auto processed = animation_build(incoming); auto destination = find_by_name(*destinationAnimations, ElementType::ANIMATION, processed.name); - if (!destination) + if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; + if (!destination || isAppendAsNew) { + if (isAppendAsNew) + { + processed.name = name_unique_get(*destinationAnimations, ElementType::ANIMATION, processed.name); + if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; + } destinationAnimations->children.push_back(processed); continue; } + if (isReplaceMatching) + { + *destination = processed; + continue; + } + destination->frameNum = std::max(destination->frameNum, processed.frameNum); destination->isLoop = processed.isLoop; if (auto root = element_child_first_get(processed, ElementType::ROOT_ANIMATION); @@ -1449,7 +1889,8 @@ namespace anm2ed } if (destinationAnimations->defaultAnimation.empty() && !sourceAnimations->defaultAnimation.empty()) - destinationAnimations->defaultAnimation = sourceAnimations->defaultAnimation; + destinationAnimations->defaultAnimation = + defaultAnimationName.empty() ? sourceAnimations->defaultAnimation : defaultAnimationName; } assets_sync(ALL); @@ -1471,6 +1912,7 @@ namespace anm2ed { spritesheetHashes.clear(); spritesheetSaveHashes.clear(); + overlay_hashes_reset(); if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) for (auto& spritesheet : spritesheets->children) if (spritesheet.type == ElementType::SPRITESHEET) @@ -1514,6 +1956,65 @@ namespace anm2ed } } + void Document::overlay_hashes_reset() + { + overlayHashes.clear(); + overlaySaveHashes.clear(); + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY) + { + auto currentHash = document::spritesheet_hash_get(overlay, overlay_texture_get(overlay.id)); + overlayHashes[overlay.id] = currentHash; + overlaySaveHashes[overlay.id] = currentHash; + } + } + } + + void Document::overlay_hashes_sync() + { + std::set validIds{}; + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY) validIds.insert(overlay.id); + } + + for (auto it = overlayHashes.begin(); it != overlayHashes.end();) + { + if (!validIds.contains(it->first)) + it = overlayHashes.erase(it); + else + ++it; + } + + for (auto it = overlaySaveHashes.begin(); it != overlaySaveHashes.end();) + { + if (!validIds.contains(it->first)) + it = overlaySaveHashes.erase(it); + else + ++it; + } + + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY) + { + auto currentHash = document::spritesheet_hash_get(overlay, overlay_texture_get(overlay.id)); + overlayHashes[overlay.id] = currentHash; + if (!overlaySaveHashes.contains(overlay.id)) overlaySaveHashes[overlay.id] = currentHash; + } + } + } + void Document::change(ChangeType type) { hash_set(); @@ -1532,6 +2033,12 @@ namespace anm2ed { spritesheet.labels_set(document::spritesheet_labels_get(anm2), document::spritesheet_ids_get(anm2)); spritesheet_hashes_sync(); + if (auto currentSpritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheet.reference)) + overlay.labels_set(document::overlay_labels_get(currentSpritesheet), + document::overlay_ids_get(currentSpritesheet)); + else + overlay.labels_set({}, {}); + overlay_hashes_sync(); }; auto sounds_set = [&]() { sound.labels_set(document::sound_labels_get(anm2), document::sound_ids_get(anm2)); }; @@ -1584,6 +2091,8 @@ namespace anm2ed default: break; } + + snapshots.commit(current); } bool Document::is_dirty() const { return hash != saveHash; } @@ -1622,6 +2131,46 @@ namespace anm2ed if (spritesheet.type == ElementType::SPRITESHEET && spritesheet_is_dirty(spritesheet.id)) return true; return false; } + + void Document::overlay_hash_update(int id) + { + auto overlay = overlay_get(id); + if (!overlay) return; + assets_sync(TEXTURES); + overlayHashes[id] = document::spritesheet_hash_get(*overlay, overlay_texture_get(id)); + } + + void Document::overlay_hash_set_saved(int id) + { + auto overlay = overlay_get(id); + if (!overlay) return; + assets_sync(TEXTURES); + auto currentHash = document::spritesheet_hash_get(*overlay, overlay_texture_get(id)); + overlayHashes[id] = currentHash; + overlaySaveHashes[id] = currentHash; + } + + bool Document::overlay_is_dirty(int id) + { + if (!overlay_get(id)) return false; + if (!overlayHashes.contains(id)) overlay_hash_update(id); + auto saveIt = overlaySaveHashes.find(id); + if (saveIt == overlaySaveHashes.end()) return false; + return overlayHashes.at(id) != saveIt->second; + } + + bool Document::overlay_any_dirty() + { + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY && overlay_is_dirty(overlay.id)) return true; + } + return false; + } + std::filesystem::path Document::directory_get() const { return path.parent_path(); } std::filesystem::path Document::filename_get() const { return path.filename(); } bool Document::is_valid() const { return isValid && !path.empty(); } @@ -1634,8 +2183,9 @@ namespace anm2ed bool Document::is_frame_reference_valid(Reference frameReference) const { if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; - auto itemType = static_cast(frameReference.itemType); - auto item = anm2.element_get(frameReference.animationIndex, itemType, frameReference.itemID); + auto itemReference = frameReference; + itemReference.frameIndex = -1; + auto item = anm2.element_get(itemReference); return item && track_frame_get(*item, frameReference.frameIndex); } @@ -1645,16 +2195,17 @@ namespace anm2ed itemReference.frameIndex = -1; if (itemReference.itemType == NONE) return result; - auto itemType = static_cast(itemReference.itemType); - auto item = anm2.element_get(itemReference.animationIndex, itemType, itemReference.itemID); + auto item = anm2.element_get(itemReference); if (!item) return result; - auto frameType = itemType == ItemType::TRIGGER ? ElementType::TRIGGER : ElementType::FRAME; + auto frameType = itemReference.itemType == TRIGGER ? ElementType::TRIGGER : ElementType::FRAME; int frameIndex{}; for (auto& child : item->children) { if (child.type != frameType) continue; - result.insert({itemReference.animationIndex, itemReference.itemType, itemReference.itemID, frameIndex}); + auto frameReference = itemReference; + frameReference.frameIndex = frameIndex; + result.insert(frameReference); ++frameIndex; } return result; @@ -1664,7 +2215,11 @@ namespace anm2ed { auto selectedItems = items.references; if (selectedItems.empty() && reference.itemType != NONE) - selectedItems.insert({reference.animationIndex, reference.itemType, reference.itemID}); + { + auto itemReference = reference; + itemReference.frameIndex = -1; + selectedItems.insert(itemReference); + } std::set result{}; for (auto itemReference : selectedItems) @@ -1679,20 +2234,39 @@ namespace anm2ed { auto result = frames.references; for (auto frameIndex : frames.selection) - result.insert({reference.animationIndex, reference.itemType, reference.itemID, frameIndex}); + { + auto frameReference = reference; + frameReference.frameIndex = frameIndex; + result.insert(frameReference); + } + + std::map frameCounts{}; + auto is_frame_reference_valid_cached = [&](Reference frameReference) + { + if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; + auto itemReference = frameReference; + itemReference.frameIndex = -1; + if (!frameCounts.contains(itemReference)) + { + auto item = anm2.element_get(itemReference); + frameCounts[itemReference] = item ? document::frame_count_get(*item) : 0; + } + return frameReference.frameIndex < frameCounts[itemReference]; + }; bool isMultiFrameSelection = frames.references.size() > 1 || frames.selection.size() > 1; - std::erase_if(result, [&](const Reference& frameReference) { return !is_frame_reference_valid(frameReference); }); + std::erase_if(result, + [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); if (isMultiFrameSelection && result.size() <= 1) { auto itemFrames = selected_item_frame_references_get(); std::erase_if(itemFrames, - [&](const Reference& frameReference) { return !is_frame_reference_valid(frameReference); }); + [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); if (itemFrames.size() > result.size()) result = std::move(itemFrames); } - if (result.empty() && fallback == FrameReferenceFallback::CURRENT && is_frame_reference_valid(reference)) + if (result.empty() && fallback == FrameReferenceFallback::CURRENT && is_frame_reference_valid_cached(reference)) result.insert(reference); return result; @@ -1700,8 +2274,22 @@ namespace anm2ed void Document::frame_references_set(std::set frameReferences) { + std::map frameCounts{}; + auto is_frame_reference_valid_cached = [&](Reference frameReference) + { + if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; + auto itemReference = frameReference; + itemReference.frameIndex = -1; + if (!frameCounts.contains(itemReference)) + { + auto item = anm2.element_get(itemReference); + frameCounts[itemReference] = item ? document::frame_count_get(*item) : 0; + } + return frameReference.frameIndex < frameCounts[itemReference]; + }; + std::erase_if(frameReferences, - [&](const Reference& frameReference) { return !is_frame_reference_valid(frameReference); }); + [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); frames.references = std::move(frameReferences); frames.selection.clear(); @@ -1709,7 +2297,7 @@ namespace anm2ed if (frames.references.empty()) return; - if (!frames.references.contains(reference) || !is_frame_reference_valid(reference)) + if (!frames.references.contains(reference) || !is_frame_reference_valid_cached(reference)) reference = *frames.references.begin(); for (auto frameReference : frames.references) @@ -1720,7 +2308,8 @@ namespace anm2ed for (auto frameReference : frames.references) if (frameReference.animationIndex == reference.animationIndex && frameReference.itemType == reference.itemType && - frameReference.itemID == reference.itemID && frameReference.frameIndex >= 0) + frameReference.itemID == reference.itemID && frameReference.groupType == reference.groupType && + frameReference.groupId == reference.groupId && frameReference.frameIndex >= 0) frames.selection.insert(frameReference.frameIndex); } @@ -1740,19 +2329,24 @@ namespace anm2ed selectedReferences.insert(frameReference); } if (selectedReferences.empty() && reference.itemType != NONE) - selectedReferences.insert({reference.animationIndex, reference.itemType, reference.itemID}); + { + auto itemReference = reference; + itemReference.frameIndex = -1; + selectedReferences.insert(itemReference); + } std::vector result{}; for (auto itemReference : selectedReferences) { itemReference.frameIndex = -1; if (itemReference.itemType != LAYER) return {}; - if (!anm2.element_get(itemReference.animationIndex, ItemType::LAYER, itemReference.itemID)) + if (!anm2.element_get(itemReference)) { - if (reference.animationIndex == itemReference.animationIndex || - !anm2.element_get(reference.animationIndex, ItemType::LAYER, itemReference.itemID)) + auto targetReference = itemReference; + targetReference.animationIndex = reference.animationIndex; + if (reference.animationIndex == itemReference.animationIndex || !anm2.element_get(targetReference)) return {}; - itemReference.animationIndex = reference.animationIndex; + itemReference = targetReference; } result.push_back(itemReference); } @@ -1761,17 +2355,53 @@ namespace anm2ed Element* Document::frame_get() { - return anm2.element_get(reference.animationIndex, document::item_type_get(reference.itemType), reference.frameIndex, - reference.itemID); + return anm2.element_get(reference); } Element* Document::item_get() { - return anm2.element_get(reference.animationIndex, document::item_type_get(reference.itemType), reference.itemID); + auto itemReference = reference; + itemReference.frameIndex = -1; + return anm2.element_get(itemReference); } Element* Document::animation_get() { return anm2.element_get(ElementType::ANIMATION, reference.animationIndex); } Element* Document::spritesheet_get() { return anm2.element_get(ElementType::SPRITESHEET, spritesheet.reference); } + Element* Document::overlay_get(int id) + { + if (id == -1) id = overlay.reference; + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + if (auto overlay = element_child_id_get(spritesheet, ElementType::OVERLAY, id)) return overlay; + } + return nullptr; + } + + const Element* Document::overlay_get(int id) const + { + if (id == -1) id = overlay.reference; + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + if (auto overlay = element_child_id_get(spritesheet, ElementType::OVERLAY, id)) return overlay; + } + return nullptr; + } + + int Document::overlay_spritesheet_id_get(int id) const + { + if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + if (element_child_id_get(spritesheet, ElementType::OVERLAY, id)) return spritesheet.id; + } + return -1; + } + void Document::spritesheet_add(const std::filesystem::path& path) { spritesheets_add({path}); @@ -1812,7 +2442,7 @@ namespace anm2ed } if (loaded.empty()) return; - snapshot(localize.get(EDIT_ADD_SPRITESHEET)); + anm2_snapshot(localize.get(EDIT_ADD_SPRITESHEET)); std::set added{}; for (auto& loadedSpritesheet : loaded) @@ -1836,6 +2466,71 @@ namespace anm2ed change(Document::SPRITESHEETS); } + void Document::overlay_add(int spritesheetId, const std::filesystem::path& path) + { + overlays_add(spritesheetId, {path}); + } + + void Document::overlays_add(int spritesheetId, const std::vector& paths) + { + struct LoadedOverlay + { + std::filesystem::path relativePath{}; + resource::Texture texture{}; + }; + + auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return; + auto directory = directory_get(); + + std::vector loaded{}; + for (auto& path : paths) + { + auto pathCopy = path; + auto storagePath = path::backslash_handle(pathCopy); + std::optional workingDirectory{}; + if (!storagePath.is_absolute()) workingDirectory.emplace(directory); + auto loadPath = path::case_insensitive_find(storagePath); + auto texture = resource::Texture(loadPath); + if (!texture.is_valid()) + { + auto pathUtf8 = path::to_utf8(pathCopy); + toasts.push(std::vformat(localize.get(TOAST_OVERLAY_INIT_FAILED), std::make_format_args(pathUtf8))); + logger.error(std::vformat(localize.get(TOAST_OVERLAY_INIT_FAILED, anm2ed::ENGLISH), + std::make_format_args(pathUtf8))); + continue; + } + + loaded.push_back({.relativePath = path::backslash_replace(path::make_relative(storagePath, directory)), + .texture = std::move(texture)}); + } + if (loaded.empty()) return; + + anm2_snapshot(localize.get(EDIT_ADD_OVERLAY)); + + std::set added{}; + for (auto& loadedOverlay : loaded) + { + auto id = document::overlay_next_id_get(anm2); + auto overlayElement = element_make(ElementType::OVERLAY); + overlayElement.id = id; + overlayElement.path = loadedOverlay.relativePath; + auto pathString = path::to_utf8(overlayElement.path); + spritesheet->children.push_back(overlayElement); + overlayTextures[id] = std::move(loadedOverlay.texture); + overlayTexturePaths[id] = overlayElement.path; + added.insert(id); + overlay.reference = id; + overlay_hash_set_saved(id); + toasts.push(std::vformat(localize.get(TOAST_OVERLAY_INITIALIZED), std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_OVERLAY_INITIALIZED, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } + overlay.selection = added; + editTarget = Document::EditTarget::OVERLAY; + change(Document::SPRITESHEETS); + } + void Document::sound_add(const std::filesystem::path& path) { sounds_add({path}); @@ -1852,7 +2547,7 @@ namespace anm2ed if (!path.empty()) validPaths.push_back(path); if (validPaths.empty()) return; - snapshot(localize.get(EDIT_ADD_SOUND)); + anm2_snapshot(localize.get(EDIT_ADD_SOUND)); std::set added{}; for (auto& path : validPaths) @@ -1880,10 +2575,34 @@ namespace anm2ed change(Document::SOUNDS); } - void Document::snapshot(const std::string& message) + void Document::anm2_snapshot(const std::string& message) { this->message = message; - snapshots.push(current); + snapshots.anm2_push(current, message); + } + + void Document::frames_snapshot(const std::string& message, const std::set& frameReferences) + { + this->message = message; + snapshots.frames_push(current, message, frameReferences); + } + + void Document::regions_snapshot(const std::string& message, int spritesheetId, const std::set& regionIds) + { + this->message = message; + snapshots.regions_push(current, message, spritesheetId, regionIds); + } + + void Document::textures_snapshot(const std::string& message) + { + this->message = message; + snapshots.textures_push(current, message); + } + + void Document::anm2_textures_snapshot(const std::string& message) + { + this->message = message; + snapshots.anm2_textures_push(current, message); } void Document::undo() diff --git a/src/document.hpp b/src/document.hpp index 830a189..9c621cc 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -12,6 +12,7 @@ #include #include "origin.hpp" +#include "shader.hpp" #include "types.hpp" namespace anm2ed @@ -49,6 +50,7 @@ namespace anm2ed NONE, FRAME, REGION, + OVERLAY, SPRITESHEET }; @@ -58,6 +60,14 @@ namespace anm2ed SET }; + enum FileMergePreset + { + FILE_MERGE_PRESET_MERGE_BY_NAME, + FILE_MERGE_PRESET_APPEND_AS_NEW, + FILE_MERGE_PRESET_REPLACE_MATCHING, + FILE_MERGE_PRESET_COUNT + }; + std::filesystem::path path{}; uint64_t tabId{}; @@ -72,10 +82,12 @@ namespace anm2ed Storage& layer = current.layer; Storage& merge = current.merge; Storage& null = current.null; + Storage& overlay = current.overlay; Storage& region = current.region; Storage& sound = current.sound; Storage& spritesheet = current.spritesheet; std::map& textures = current.textures; + std::map& overlayTextures = current.overlayTextures; std::map& sounds = current.sounds; Anm2& anm2 = current.anm2; Reference& reference = current.reference; @@ -100,8 +112,14 @@ namespace anm2ed bool isForceDirty{false}; std::unordered_map spritesheetHashes{}; std::unordered_map spritesheetSaveHashes{}; + std::unordered_map overlayHashes{}; + std::unordered_map overlaySaveHashes{}; std::unordered_map texturePaths{}; + std::unordered_map overlayTexturePaths{}; std::unordered_map soundPaths{}; + std::unordered_map shaderVertexPaths{}; + std::unordered_map shaderFragmentPaths{}; + std::map shaders{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; EditTarget editTarget{EditTarget::NONE}; @@ -115,19 +133,26 @@ namespace anm2ed void anm2_change(ChangeType); void assets_sync(ChangeType = ALL); void texture_change(int); + void overlay_texture_change(int); bool texture_reload(int); + bool overlay_texture_reload(int); bool sound_reload(int); + bool shader_reload(int, std::string* = nullptr); resource::Texture* texture_get(int); const resource::Texture* texture_get(int) const; + resource::Texture* overlay_texture_get(int); + const resource::Texture* overlay_texture_get(int) const; resource::Audio* sound_get(int); const resource::Audio* sound_get(int) const; + resource::Shader* shader_get(int); + const resource::Shader* shader_get(int) const; bool regions_trim(int, const std::set&); bool regions_generate_from_animations(const std::set&, const std::string&, RegionFrameMapping); bool regions_generate_from_frames(const std::set&, const std::string&, RegionFrameMapping); bool spritesheet_pack(int, int); bool spritesheets_merge(const std::set&, bool, bool, bool, origin::Type); void scan_and_set_regions(); - bool file_merge(const std::filesystem::path&); + bool file_merge(const std::filesystem::path&, FileMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME); void hash_set(); void clean(); void change(ChangeType); @@ -143,6 +168,12 @@ namespace anm2ed bool spritesheet_any_dirty(); void spritesheet_hashes_reset(); void spritesheet_hashes_sync(); + void overlay_hash_update(int); + void overlay_hash_set_saved(int); + bool overlay_is_dirty(int); + bool overlay_any_dirty(); + void overlay_hashes_reset(); + void overlay_hashes_sync(); bool is_frame_reference_valid(Reference) const; std::set item_frame_references_get(Reference) const; std::set selected_item_frame_references_get() const; @@ -154,10 +185,15 @@ namespace anm2ed Element* frame_get(); Element* item_get(); Element* spritesheet_get(); + Element* overlay_get(int = -1); + const Element* overlay_get(int = -1) const; + int overlay_spritesheet_id_get(int) const; Element* animation_get(); void spritesheet_add(const std::filesystem::path&); void spritesheets_add(const std::vector&); + void overlay_add(int, const std::filesystem::path&); + void overlays_add(int, const std::vector&); void sound_add(const std::filesystem::path&); void sounds_add(const std::vector&); @@ -165,7 +201,11 @@ namespace anm2ed std::filesystem::path autosave_path_get(); std::filesystem::path path_from_autosave_get(const std::filesystem::path&); - void snapshot(const std::string& message); + void anm2_snapshot(const std::string& message); + void frames_snapshot(const std::string& message, const std::set&); + void regions_snapshot(const std::string& message, int, const std::set&); + void textures_snapshot(const std::string& message); + void anm2_textures_snapshot(const std::string& message); void undo(); void redo(); bool is_able_to_undo(); @@ -174,14 +214,14 @@ namespace anm2ed #define DOCUMENT_EDIT(document, message, changeType, body) \ { \ - document.snapshot(message); \ + document.anm2_snapshot(message); \ body; \ document.change(changeType); \ } #define DOCUMENT_EDIT_PTR(document, message, changeType, body) \ { \ - document->snapshot(message); \ + document->anm2_snapshot(message); \ body; \ document->change(changeType); \ } diff --git a/src/imgui/actions.cpp b/src/imgui/actions.cpp index 558ea91..d4d997d 100644 --- a/src/imgui/actions.cpp +++ b/src/imgui/actions.cpp @@ -79,7 +79,11 @@ namespace anm2ed::imgui bool actions_context_window_draw(const char* label, Actions& actions, Settings& settings, ImGuiPopupFlags flags) { - if (!ImGui::BeginPopupContextWindow(label, flags)) return false; + auto mouseButton = flags & ImGuiPopupFlags_MouseButtonMask_; + if (ImGui::IsMouseReleased(mouseButton) && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) + if (!(flags & ImGuiPopupFlags_NoOpenOverItems) || !ImGui::IsAnyItemHovered()) ImGui::OpenPopup(label, flags); + + if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) return false; actions_menu_draw(actions, settings); ImGui::EndPopup(); return true; @@ -87,7 +91,7 @@ namespace anm2ed::imgui bool actions_popup_draw(const char* label, Actions& actions, Settings& settings) { - if (!ImGui::BeginPopup(label)) return false; + if (!ImGui::BeginPopup(label, ImGuiWindowFlags_NoMove)) return false; actions_menu_draw(actions, settings); ImGui::EndPopup(); return true; diff --git a/src/imgui/dockspace.cpp b/src/imgui/dockspace.cpp index 99fdf80..f1ca56d 100644 --- a/src/imgui/dockspace.cpp +++ b/src/imgui/dockspace.cpp @@ -40,6 +40,8 @@ namespace anm2ed::imgui if (settings.windowIsLayers) window_update(layers, manager, settings, resources, dialog, clipboard); if (settings.windowIsNulls) window_update(nulls, manager, settings, resources, dialog, clipboard); if (settings.windowIsOnionskin) onionskin.update(manager, settings); + if (settings.windowIsOverlays) window_update(overlays, manager, settings, resources, dialog, clipboard); + if (settings.windowIsShaders) shaders.update(manager, settings, resources, dialog); if (settings.windowIsSounds) window_update(sounds, manager, settings, resources, dialog, clipboard); if (settings.windowIsSpritesheetEditor) spritesheetEditor.update(manager, settings, resources); if (settings.windowIsSpritesheets) diff --git a/src/imgui/dockspace.hpp b/src/imgui/dockspace.hpp index bab15a5..33b6193 100644 --- a/src/imgui/dockspace.hpp +++ b/src/imgui/dockspace.hpp @@ -6,6 +6,7 @@ #include "window/animation_preview.hpp" #include "window/frame_properties.hpp" #include "window/onionskin.hpp" +#include "window/shaders.hpp" #include "window/spritesheet_editor.hpp" #include "window/timeline.hpp" #include "window/tools.hpp" @@ -25,6 +26,8 @@ namespace anm2ed::imgui Window layers{layers_window_register()}; Window nulls{nulls_window_register()}; Onionskin onionskin; + Window overlays{overlays_window_register()}; + ShadersWindow shaders; SpritesheetEditor spritesheetEditor; Window spritesheets{spritesheets_window_register()}; Window sounds{sounds_window_register()}; diff --git a/src/imgui/documents.cpp b/src/imgui/documents.cpp index 7d6ab26..192a898 100644 --- a/src/imgui/documents.cpp +++ b/src/imgui/documents.cpp @@ -1,5 +1,6 @@ #include "documents.hpp" +#include #include #include #include @@ -26,17 +27,46 @@ namespace anm2ed::imgui uint64_t documentId{}; }; +#define ANM2_DRAG_DROP_MERGE_PRESETS \ + X(FILE_MERGE_PRESET_MERGE_BY_NAME, BASIC_MERGE, TOOLTIP_MERGE_PRESET_MERGE_BY_NAME) \ + X(FILE_MERGE_PRESET_APPEND_AS_NEW, BASIC_APPEND, TOOLTIP_MERGE_PRESET_APPEND_AS_NEW) \ + X(FILE_MERGE_PRESET_REPLACE_MATCHING, BASIC_REPLACE, TOOLTIP_MERGE_PRESET_REPLACE_MATCHING) + + constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[Document::FILE_MERGE_PRESET_COUNT] = { +#define X(preset, label, tooltip) label, + ANM2_DRAG_DROP_MERGE_PRESETS +#undef X + }; + + constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[Document::FILE_MERGE_PRESET_COUNT] = { +#define X(preset, label, tooltip) tooltip, + ANM2_DRAG_DROP_MERGE_PRESETS +#undef X + }; + +#undef ANM2_DRAG_DROP_MERGE_PRESETS + Options save_options_get(const Settings& settings) { - Flags flags{}; - if (settings.fileIsSerializeGroups) flags |= SERIALIZE_GROUPS; - if (settings.fileIsSerializeRegions) flags |= SERIALIZE_REGIONS; - if (settings.fileIsSerializeSounds) flags |= SERIALIZE_SOUNDS; + Flags flags{SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS}; if (settings.fileIsKeepRedundantFrameRegionValues) flags |= SERIALIZE_REDUNDANT_FRAME_REGION_VALUES; if (settings.fileIsBakeSpecialInterpolatedFrames) flags |= SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES; + if (settings.isFileBakeGroupFrames) flags |= SERIALIZE_BAKE_GROUP_FRAMES; return {.flags = flags}; } + void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, + Document::FileMergePreset preset) + { + manager.command_push({manager.selected, + [paths, preset](Manager&, Document& document) + { + document.anm2_snapshot(localize.get(EDIT_MERGE_ANM2)); + for (auto& path : paths) document.file_merge(path, preset); + document.change(Document::ALL); + }}); + } + void Documents::pending_document_order_apply(Manager& manager) { if (pendingDocumentTabIds.size() != manager.documents.size()) @@ -161,7 +191,7 @@ namespace anm2ed::imgui { auto& document = manager.documents[i]; auto isDocumentDirty = document.is_dirty() || document.isForceDirty; - auto isSpritesheetDirty = document.spritesheet_any_dirty(); + auto isSpritesheetDirty = document.spritesheet_any_dirty() || document.overlay_any_dirty(); auto isDirty = isDocumentDirty || isSpritesheetDirty; if (!closePopup.is_open()) @@ -258,7 +288,7 @@ namespace anm2ed::imgui auto filename = path::to_utf8(closeDocument.filename_get()); auto isDocumentDirty = closeDocument.is_dirty() || closeDocument.isForceDirty; - auto isSpritesheetDirty = closeDocument.spritesheet_any_dirty(); + auto isSpritesheetDirty = closeDocument.spritesheet_any_dirty() || closeDocument.overlay_any_dirty(); auto promptLabel = isDocumentDirty && isSpritesheetDirty ? LABEL_DOCUMENT_AND_SPRITESHEETS_MODIFIED_PROMPT @@ -296,24 +326,51 @@ namespace anm2ed::imgui if (spritesheet.type != ElementType::SPRITESHEET) continue; auto id = spritesheet.id; auto texture = closeDocument.texture_get(id); - if (!texture || !closeDocument.spritesheet_is_dirty(id)) continue; - auto pathString = path::to_utf8(spritesheet.path); - auto savePath = closeDocument.directory_get() / spritesheet.path; - path::ensure_directory(savePath.parent_path()); - if (texture->write_png(savePath)) + if (texture && closeDocument.spritesheet_is_dirty(id)) { - closeDocument.spritesheet_hash_set_saved(id); - toasts.push( - std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + auto pathString = path::to_utf8(spritesheet.path); + auto savePath = closeDocument.directory_get() / spritesheet.path; + path::ensure_directory(savePath.parent_path()); + if (texture->write_png(savePath)) + { + closeDocument.spritesheet_hash_set_saved(id); + toasts.push( + std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } + else + { + toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), + std::make_format_args(id, pathString))); + logger.error(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } } - else + + for (auto& overlay : spritesheet.children) { - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), - std::make_format_args(id, pathString))); - logger.error(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + if (overlay.type != ElementType::OVERLAY) continue; + auto overlayTexture = closeDocument.overlay_texture_get(overlay.id); + if (!overlayTexture || !closeDocument.overlay_is_dirty(overlay.id)) continue; + auto pathString = path::to_utf8(overlay.path); + auto savePath = closeDocument.directory_get() / overlay.path; + path::ensure_directory(savePath.parent_path()); + if (overlayTexture->write_png(savePath)) + { + closeDocument.overlay_hash_set_saved(overlay.id); + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY), + std::make_format_args(overlay.id, pathString))); + logger.info(std::vformat(localize.get(TOAST_SAVE_OVERLAY, anm2ed::ENGLISH), + std::make_format_args(overlay.id, pathString))); + } + else + { + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED), + std::make_format_args(overlay.id, pathString))); + logger.error(std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED, anm2ed::ENGLISH), + std::make_format_args(overlay.id, pathString))); + } } } } @@ -366,17 +423,62 @@ namespace anm2ed::imgui manager.isAnm2DragDrop = false; manager.anm2DragDropPaths.clear(); manager.anm2DragDropPopup.close(); + manager.anm2DragDropMergePopup.close(); + manager.anm2DragDropMergePreset = Document::FILE_MERGE_PRESET_MERGE_BY_NAME; }; if (manager.anm2DragDropPaths.empty()) drag_drop_reset(); + else if (manager.anm2DragDropMergePopup.is_open()) + { + manager.anm2DragDropMergePopup.trigger(); + + if (ImGui::BeginPopupModal(manager.anm2DragDropMergePopup.label(), &manager.anm2DragDropMergePopup.isOpen, + ImGuiWindowFlags_NoResize)) + { + auto document = manager.get(); + manager.anm2DragDropMergePreset = + std::clamp(manager.anm2DragDropMergePreset, 0, Document::FILE_MERGE_PRESET_COUNT - 1); + + for (int preset = 0; preset < Document::FILE_MERGE_PRESET_COUNT; ++preset) + { + ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]), + &manager.anm2DragDropMergePreset, preset); + ImGui::SetItemTooltip("%s", localize.get(ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[preset])); + } + + auto widgetSize = widget_size_with_row_get(2); + shortcut(manager.chords[SHORTCUT_CONFIRM]); + ImGui::BeginDisabled(!document); + if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) + { + auto paths = manager.anm2DragDropPaths; + auto preset = (Document::FileMergePreset)manager.anm2DragDropMergePreset; + anm2_drag_drop_merge_queue(manager, paths, preset); + drag_drop_reset(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) drag_drop_reset(); + + manager.anm2DragDropMergePopup.end(); + ImGui::EndPopup(); + + if (manager.isAnm2DragDrop && !manager.anm2DragDropMergePopup.is_open()) drag_drop_reset(); + } + else if (!ImGui::IsPopupOpen(manager.anm2DragDropMergePopup.label())) + drag_drop_reset(); + } else { if (!manager.anm2DragDropPopup.is_open()) manager.anm2DragDropPopup.open(); manager.anm2DragDropPopup.trigger(); - if (ImGui::BeginPopupContextWindow(manager.anm2DragDropPopup.label(), ImGuiPopupFlags_None)) + if (ImGui::BeginPopup(manager.anm2DragDropPopup.label(), ImGuiWindowFlags_NoMove)) { auto document = manager.get(); if (ImGui::MenuItem(manager.anm2DragDropPaths.size() > 1 ? localize.get(LABEL_DOCUMENTS_OPEN_MANY) @@ -396,15 +498,9 @@ namespace anm2ed::imgui { if (document) { - auto paths = manager.anm2DragDropPaths; - manager.command_push({manager.selected, - [paths](Manager&, Document& document) - { - document.snapshot(localize.get(EDIT_MERGE_ANM2)); - for (auto& path : paths) document.file_merge(path); - document.change(Document::ALL); - }}); - drag_drop_reset(); + manager.anm2DragDropPopup.close(); + manager.anm2DragDropMergePopup.open(); + ImGui::CloseCurrentPopup(); } } diff --git a/src/imgui/popup/item_properties.cpp b/src/imgui/popup/item_properties.cpp index dbdf3b8..6adaf85 100644 --- a/src/imgui/popup/item_properties.cpp +++ b/src/imgui/popup/item_properties.cpp @@ -202,7 +202,7 @@ namespace anm2ed::imgui::popup { int addId{-1}; - document.snapshot(localize.get(EDIT_ADD_ITEM)); + document.anm2_snapshot(localize.get(EDIT_ADD_ITEM)); if (queuedType == LAYER) addId = document.anm2.layer_animation_add( queuedAnimationIndex, queuedAddItemID, queuedInsertBeforeID, queuedAddItemName, diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 0106506..3e7c4ae 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -29,12 +29,10 @@ namespace anm2ed::imgui Options save_options_get(Settings& settings) { - Flags flags{}; - if (settings.fileIsSerializeGroups) flags |= SERIALIZE_GROUPS; - if (settings.fileIsSerializeRegions) flags |= SERIALIZE_REGIONS; - if (settings.fileIsSerializeSounds) flags |= SERIALIZE_SOUNDS; + Flags flags{SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS}; if (settings.fileIsKeepRedundantFrameRegionValues) flags |= SERIALIZE_REDUNDANT_FRAME_REGION_VALUES; if (settings.fileIsBakeSpecialInterpolatedFrames) flags |= SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES; + if (settings.isFileBakeGroupFrames) flags |= SERIALIZE_BAKE_GROUP_FRAMES; return {.flags = flags}; } @@ -186,7 +184,7 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [](Manager&, Document& document) { - document.snapshot(localize.get(EDIT_SCAN_AND_SET_REGIONS)); + document.anm2_snapshot(localize.get(EDIT_SCAN_AND_SET_REGIONS)); document.scan_and_set_regions(); document.change(Document::FRAMES); }}); @@ -301,7 +299,7 @@ namespace anm2ed::imgui [=](Manager&, Document& document) { if (queuedAnimationIndices.empty()) return; - document.snapshot(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); + document.anm2_snapshot(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); if (document.regions_generate_from_animations(queuedAnimationIndices, queuedFormat, queuedMapping)) document.anm2_change(queuedMapping == Document::RegionFrameMapping::SET diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index fa75e7d..ee8e35a 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -198,6 +198,19 @@ namespace anm2ed::imgui auto pathString = path::to_utf8(path); auto& type = settings.renderType; auto renderFrameRate = std::max(settings.playbackTickRate, 1); + auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation; + auto render_preview_restore = [&]() + { + if (!isRenderPreviewOverridden) return; + + settings = savedSettings; + pan = savedPan; + zoom = savedZoom; + overlayIndex = savedOverlayIndex; + isSizeTrySet = true; + hasPendingZoomPanAdjust = false; + isCheckerPanInitialized = false; + }; if (playback.time >= (float)end + 1.0f || playback.isFinished) { @@ -223,6 +236,9 @@ namespace anm2ed::imgui { auto& rows = settings.renderRows; auto& columns = settings.renderColumns; + auto layout = render::spritesheet_layout_get(rows, columns, (int)renderTempFrames.size()); + rows = layout.rows; + columns = layout.columns; if (renderTempFrames.empty()) { @@ -324,17 +340,7 @@ namespace anm2ed::imgui renderFrameSoundIDs.clear(); } - if (settings.renderIsRawAnimation) - { - settings = savedSettings; - - pan = savedPan; - zoom = savedZoom; - overlayIndex = savedOverlayIndex; - isSizeTrySet = true; - hasPendingZoomPanAdjust = false; - isCheckerPanInitialized = false; - } + render_preview_restore(); playback.isPlaying = false; playback.isFinished = false; @@ -349,8 +355,7 @@ namespace anm2ed::imgui { auto soundTime = (int)std::floor(playback.time); auto animation = anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); - if (soundTime != renderFrameSoundTimePrev && animation && - (!settings.timelineIsOnlyShowLayers || manager.isRecording)) + if (soundTime != renderFrameSoundTimePrev && animation) frameSoundID = trigger_sound_id_get(animation, playback.time); renderFrameSoundTimePrev = soundTime; } @@ -358,7 +363,7 @@ namespace anm2ed::imgui bind(); auto pixels = pixels_get(); - if (settings.renderIsRawAnimation) pixels_unpremultiply_alpha(pixels); + if (isRenderPreviewOverridden) pixels_unpremultiply_alpha(pixels); auto frameIndex = (int)renderTempFrames.size(); auto framePath = renderTempDirectory / render_frame_filename(settings.renderFormat, frameIndex); if (Texture::write_pixels_png(framePath, size, pixels.data())) @@ -376,6 +381,7 @@ namespace anm2ed::imgui if (type != render::PNGS) render_temp_cleanup(renderTempDirectory, renderTempFrames); renderTempFrameDurations.clear(); renderFrameSoundIDs.clear(); + render_preview_restore(); playback.isPlaying = false; playback.isFinished = false; manager.isRecording = false; @@ -388,7 +394,6 @@ namespace anm2ed::imgui { auto animation = anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); auto& isSound = settings.timelineIsSound; - auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; if (!animation) { @@ -400,9 +405,8 @@ namespace anm2ed::imgui { if (!manager.isRecording && !document.sounds.empty() && isSound) { - if (!isOnlyShowLayers || manager.isRecording) - if (auto soundID = trigger_sound_id_get(animation, playback.time); soundID != -1) - if (auto sound = document.sound_get(soundID)) sound->play(false, mixer); + if (auto soundID = trigger_sound_id_get(animation, playback.time); soundID != -1) + if (auto sound = document.sound_get(soundID)) sound->play(false, mixer); } auto info = element_first_get(anm2.root, ElementType::INFO); @@ -628,12 +632,29 @@ namespace anm2ed::imgui { savedSettings = settings; - if (settings.renderIsRawAnimation) + auto isRenderPreviewOverridden = settings.renderIsUseAnimationBounds || settings.renderIsUseIsolatedAnimation; + if (isRenderPreviewOverridden) { savedOverlayIndex = overlayIndex; savedZoom = zoom; savedPan = pan; + } + if (settings.renderIsUseIsolatedAnimation) + { + overlayIndex = -1; + settings.animationPreviewTransparent = true; + settings.timelineIsOnlyShowLayers = true; + settings.previewIsAxes = false; + settings.previewIsGrid = false; + settings.previewIsPivots = false; + settings.previewIsAltIcons = false; + settings.previewIsBorder = false; + settings.onionskinIsEnabled = false; + } + + if (settings.renderIsUseAnimationBounds) + { if (animation) if (auto rect = anm2.animation_rect(*animation, isRootTransform); rect != vec4(-1.0f)) { @@ -665,6 +686,17 @@ namespace anm2ed::imgui } if (renderTempDirectory.empty()) { + if (isRenderPreviewOverridden) + { + settings = savedSettings; + pan = savedPan; + zoom = savedZoom; + overlayIndex = savedOverlayIndex; + isSizeTrySet = true; + hasPendingZoomPanAdjust = false; + isCheckerPanInitialized = false; + } + auto pathString = path::to_utf8(settings.renderPath); toasts.push( std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString))); @@ -795,6 +827,27 @@ namespace anm2ed::imgui return true; }; + auto group_root_frame_get = [](const Element& container, const Element& track, float t) -> std::optional + { + if (track.groupId == -1) return std::nullopt; + auto group = element_child_id_get(container, ElementType::GROUP, track.groupId); + auto root = group ? element_child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr; + if (!root) return std::nullopt; + return frame_generate(*root, t); + }; + + auto group_transform_for_time = [&](const Element& container, const Element& track, float t, + const glm::mat4& sampleTransform) + { + auto itemTransform = sampleTransform; + if (isRootTransform) + if (auto groupRootFrame = group_root_frame_get(container, track, t)) + itemTransform *= math::quad_model_parent_get(groupRootFrame->position, {}, + math::percent_to_unit(groupRootFrame->scale), + groupRootFrame->rotation); + return itemTransform; + }; + auto draw_root = [&](float sampleTime, const glm::mat4& sampleTransform, vec3 sampleColor, float sampleAlpha, bool isOnion) { @@ -824,12 +877,52 @@ namespace anm2ed::imgui draw_root(time, transform, {}, 0.0f, false); + auto draw_group_root = [&](Element& group, int groupType, float sampleTime, + const glm::mat4& sampleTransform, vec3 sampleColor, float sampleAlpha, + bool isOnion) + { + auto groupRoot = element_child_first_get(group, ElementType::ROOT_ANIMATION); + if (!groupRoot) return; + auto rootFrame = frame_generate(*groupRoot, sampleTime); + if (isOnlyShowLayers || !rootFrame.isVisible || !groupRoot->isVisible) return; + + auto itemTransform = sampleTransform; + if (isRootTransform) + itemTransform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), + rootFrame.rotation); + + auto rootModel = isRootTransform + ? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) + : math::quad_model_get(TARGET_SIZE, rootFrame.position, TARGET_SIZE * 0.5f, + math::percent_to_unit(rootFrame.scale), rootFrame.rotation); + auto rootTransform = itemTransform * rootModel; + + auto isSelected = referenceItemType == ItemType::ROOT && reference.groupType == groupType && + reference.groupId == group.id; + vec4 color = isOnion ? vec4(sampleColor, sampleAlpha) : isSelected ? color::RED : ROOT_COLOR; + auto icon = isAltIcons ? icon::TARGET_ALT : icon::TARGET; + texture_render(shaderTexture, resources.icons[icon].id, rootTransform, color); + }; + if (auto layerAnimations = element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) { auto layer_animation_draw = [&](auto&& self, Element& layerAnimation, bool isParentVisible = true) -> void { if (layerAnimation.type == ElementType::GROUP) { + if (isParentVisible && layerAnimation.isVisible) + { + auto groupRoot = element_child_first_get(layerAnimation, ElementType::ROOT_ANIMATION); + if (layeredOnions && groupRoot) + for (auto& sample : *layeredOnions) + if (auto sampleTime = sample_time_for_item(*groupRoot, sample)) + { + auto sampleTransform = transform_for_time(*sampleTime); + draw_group_root(layerAnimation, LAYER, *sampleTime, sampleTransform, sample.colorOffset, + sample.alphaOffset, true); + } + draw_group_root(layerAnimation, LAYER, time, transform, {}, 0.0f, false); + } for (auto& child : layerAnimation.children) self(self, child, isParentVisible && layerAnimation.isVisible); return; @@ -864,7 +957,9 @@ namespace anm2ed::imgui auto layerModel = math::quad_model_get(size, frame.position, pivot, math::percent_to_unit(frame.scale), frame.rotation); - auto layerTransform = sampleTransform * layerModel; + auto itemTransform = group_transform_for_time(*layerAnimations, layerAnimation, sampleTime, + sampleTransform); + auto layerTransform = itemTransform * layerModel; auto uvMin = crop / texSize; auto uvMax = (crop + size) / texSize; @@ -878,12 +973,38 @@ namespace anm2ed::imgui frameColorOffset += rootFrame.colorOffset; frameTint *= rootFrame.tint; } + if (isRootTransform) + if (auto groupRootFrame = group_root_frame_get(*layerAnimations, layerAnimation, sampleTime)) + { + frameColorOffset += groupRootFrame->colorOffset; + frameTint *= groupRootFrame->tint; + } frameTint.a = std::max(0.0f, frameTint.a - (alphaOffset + sampleAlpha)); auto vertices = math::uv_vertices_get(uvMin, uvMax); + auto customShader = document.shader_get(layer->spritesheetId); + auto& layerShader = customShader ? *customShader : shaderTexture; - texture_render(shaderTexture, texture.id, layerTransform, frameTint, frameColorOffset, vertices.data()); + texture_render(layerShader, texture.id, layerTransform, frameTint, frameColorOffset, vertices.data(), + vec2(texture.size), sampleTime); + + for (auto& overlay : spritesheet->children) + { + if (overlay.type != ElementType::OVERLAY) continue; + if (!overlay.isVisible) continue; + auto overlayTexture = document.overlay_texture_get(overlay.id); + if (!overlayTexture || !overlayTexture->is_valid()) continue; + + auto overlayTexSize = vec2(overlayTexture->size); + if (overlayTexSize.x <= 0.0f || overlayTexSize.y <= 0.0f) continue; + + auto overlayUvMin = crop / overlayTexSize; + auto overlayUvMax = (crop + size) / overlayTexSize; + auto overlayVertices = math::uv_vertices_get(overlayUvMin, overlayUvMax); + texture_render(shaderTexture, overlayTexture->id, layerTransform, frameTint, frameColorOffset, + overlayVertices.data(), vec2(overlayTexture->size), sampleTime); + } auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) : is_layer_animation_selected(id) ? SELECTED_LAYER_BORDER_COLOR @@ -895,7 +1016,7 @@ namespace anm2ed::imgui { auto pivotModel = math::quad_model_get(PIVOT_SIZE, frame.position, PIVOT_SIZE * 0.5f, math::percent_to_unit(frame.scale), frame.rotation); - auto pivotTransform = sampleTransform * pivotModel; + auto pivotTransform = itemTransform * pivotModel; texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, color); } @@ -921,6 +1042,19 @@ namespace anm2ed::imgui { if (nullAnimation.type == ElementType::GROUP) { + if (isParentVisible && nullAnimation.isVisible) + { + auto groupRoot = element_child_first_get(nullAnimation, ElementType::ROOT_ANIMATION); + if (layeredOnions && groupRoot) + for (auto& sample : *layeredOnions) + if (auto sampleTime = sample_time_for_item(*groupRoot, sample)) + { + auto sampleTransform = transform_for_time(*sampleTime); + draw_group_root(nullAnimation, NULL_, *sampleTime, sampleTransform, sample.colorOffset, + sample.alphaOffset, true); + } + draw_group_root(nullAnimation, NULL_, time, transform, {}, 0.0f, false); + } for (auto& child : nullAnimation.children) self(self, child, isParentVisible && nullAnimation.isVisible); return; @@ -950,7 +1084,9 @@ namespace anm2ed::imgui auto nullModel = math::quad_model_get(size, frame.position, size * 0.5f, math::percent_to_unit(frame.scale), frame.rotation); - auto nullTransform = sampleTransform * nullModel; + auto itemTransform = group_transform_for_time(*nullAnimations, nullAnimation, sampleTime, + sampleTransform); + auto nullTransform = itemTransform * nullModel; texture_render(shaderTexture, resources.icons[icon].id, nullTransform, color); @@ -958,7 +1094,7 @@ namespace anm2ed::imgui { auto rectModel = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), frame.rotation); - auto rectTransform = sampleTransform * rectModel; + auto rectTransform = itemTransform * rectModel; rect_render(shaderLine, rectTransform, rectModel, color); } @@ -1074,9 +1210,10 @@ namespace anm2ed::imgui editItemType = static_cast(editReference.itemType); } - auto frame = - anm2.element_get(editReference.animationIndex, editItemType, editReference.frameIndex, editReference.itemID); - auto item = anm2.element_get(editReference.animationIndex, editItemType, editReference.itemID); + auto frame = anm2.element_get(editReference); + auto editItemReference = editReference; + editItemReference.frameIndex = -1; + auto item = anm2.element_get(editItemReference); auto nulls = anm2.element_get(ElementType::NULLS); auto selectedNull = editItemType == ItemType::NULL_ && nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, editReference.itemID) @@ -1105,8 +1242,10 @@ namespace anm2ed::imgui auto frame_snapshot = [&](auto message) { + auto queuedFrameReferences = selectedFrameReferences; manager.command_push({manager.selected, - [message](Manager&, Document& document) { document.snapshot(localize.get(message)); }}); + [message, queuedFrameReferences](Manager&, Document& document) + { document.frames_snapshot(localize.get(message), queuedFrameReferences); }}); }; auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { @@ -1116,15 +1255,16 @@ namespace anm2ed::imgui { std::map> groupedFrames{}; for (auto frameReference : queuedFrameReferences) - groupedFrames[{frameReference.animationIndex, frameReference.itemType, - frameReference.itemID, -1}] - .insert(frameReference.frameIndex); + { + auto itemReference = frameReference; + itemReference.frameIndex = -1; + groupedFrames[itemReference].insert(frameReference.frameIndex); + } for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference.animationIndex, itemType, - itemReference.itemID); + auto item = document.anm2.element_get(itemReference); if (!item) continue; frames_change(*item, frameChange, itemType, changeType, itemFrames); } diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 7016b91..10a5641 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -36,29 +36,26 @@ namespace anm2ed::imgui auto& anm2 = document.anm2; auto& reference = document.reference; auto& type = reference.itemType; - auto itemType = static_cast(type); - auto frame = anm2.element_get(reference.animationIndex, itemType, reference.frameIndex, reference.itemID); + auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; - auto frame_edit = [&](auto message, auto behavior) - { - auto queuedReference = reference; - manager.command_push({manager.selected, + auto frame_edit = [&](auto message, auto behavior) + { + auto queuedReference = reference; + manager.command_push({manager.selected, [=](Manager&, Document& document) mutable { - auto itemType = static_cast(queuedReference.itemType); - auto frame = document.anm2.element_get(queuedReference.animationIndex, itemType, - queuedReference.frameIndex, - queuedReference.itemID); - auto item = - document.anm2.element_get(queuedReference.animationIndex, itemType, - queuedReference.itemID); + if (queuedReference.frameIndex < 0) return; + auto frame = document.anm2.element_get(queuedReference); + auto itemReference = queuedReference; + itemReference.frameIndex = -1; + auto item = document.anm2.element_get(itemReference); if (!frame) return; - document.snapshot(localize.get(message)); + document.frames_snapshot(localize.get(message), {queuedReference}); behavior(document, *frame, item, queuedReference); document.anm2_change(Document::FRAMES); }}); - }; + }; auto persistent_edit = [&](auto state, auto message, auto behavior) { @@ -68,20 +65,18 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [=](Manager&, Document& document) mutable { - auto itemType = static_cast(queuedReference.itemType); - auto frame = document.anm2.element_get(queuedReference.animationIndex, itemType, - queuedReference.frameIndex, - queuedReference.itemID); - auto item = - document.anm2.element_get(queuedReference.animationIndex, itemType, - queuedReference.itemID); + if (queuedReference.frameIndex < 0) return; + auto frame = document.anm2.element_get(queuedReference); + auto itemReference = queuedReference; + itemReference.frameIndex = -1; + auto item = document.anm2.element_get(itemReference); if (!frame) return; - if (state == edit::START) document.snapshot(localize.get(message)); + if (state == edit::START) document.frames_snapshot(localize.get(message), {queuedReference}); behavior(document, *frame, item, queuedReference); if (state == edit::END) document.anm2_change(Document::FRAMES); }}); - }; + }; auto regionLabelsString = std::vector{localize.get(BASIC_NONE)}; auto regionLabels = std::vector{regionLabelsString[0].c_str()}; diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp new file mode 100644 index 0000000..14e3a71 --- /dev/null +++ b/src/imgui/window/shaders.cpp @@ -0,0 +1,430 @@ +#include "shaders.hpp" + +#include +#include +#include + +#include + +#include "path.hpp" +#include "strings.hpp" +#include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" + +using namespace anm2ed::resource; +using namespace anm2ed::util; + +namespace anm2ed::imgui +{ +#define SHADER_UNIFORM_BINDING_COMBO_VALUES \ + X(resource::shader::UNIFORM_BINDING_IGNORE) \ + X(resource::shader::UNIFORM_BINDING_MANUAL) \ + X(resource::shader::UNIFORM_BINDING_COLOR_OFFSET) \ + X(resource::shader::UNIFORM_BINDING_FRAME_TINT) \ + X(resource::shader::UNIFORM_BINDING_MAIN_TEXTURE) \ + X(resource::shader::UNIFORM_BINDING_COMPONENTS) \ + X(resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) \ + X(resource::shader::UNIFORM_BINDING_TEXTURE_SIZE) \ + X(resource::shader::UNIFORM_BINDING_TRANSFORM) + + inline constexpr resource::shader::UniformBinding SHADER_UNIFORM_BINDING_COMBO_ORDER[] = { +#define X(binding) binding, + SHADER_UNIFORM_BINDING_COMBO_VALUES +#undef X + }; +#undef SHADER_UNIFORM_BINDING_COMBO_VALUES + + std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& shaderPath) + { + auto loadPath = path::backslash_handle(shaderPath); + if (loadPath.empty() || loadPath.is_absolute()) return loadPath; + return document.directory_get() / loadPath; + } + + bool is_shader_reload_needed(Document& document, Element& spritesheet, Element* shader) + { + if (!shader || !shader->isEnabled || shader->fragment.empty()) return false; + if (!document.shader_get(spritesheet.id)) return true; + if (!document.shaderVertexPaths.contains(spritesheet.id) || !document.shaderFragmentPaths.contains(spritesheet.id)) + return true; + return document.shaderVertexPaths.at(spritesheet.id) != shader->vertex || + document.shaderFragmentPaths.at(spritesheet.id) != shader->fragment; + } + + Element* shader_spritesheet_get(Document& document) + { + if (document.spritesheet.selection.size() == 1) + return document.anm2.element_get(ElementType::SPRITESHEET, *document.spritesheet.selection.begin()); + return nullptr; + } + + Element* shader_element_get(Element& spritesheet, bool isCreate) + { + if (auto shader = element_child_first_get(spritesheet, ElementType::SHADER)) return shader; + if (!isCreate) return nullptr; + + spritesheet.children.push_back(element_make(ElementType::SHADER)); + return &spritesheet.children.back(); + } + + void shader_enabled_set(Document& document, Element& spritesheet, bool isEnabled) + { + if (auto shader = shader_element_get(spritesheet, true)) + { + shader->isEnabled = isEnabled; + document.change(Document::SPRITESHEETS); + } + } + + std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) + { + auto loadPath = path::backslash_handle(path); + return path::backslash_replace(path::make_relative(loadPath, document.directory_get())); + } + + void shader_path_edit(Document& document, Element& spritesheet, std::filesystem::path Element::* member, + const std::filesystem::path& value) + { + if (auto shader = shader_element_get(spritesheet, true)) + { + shader->*member = path::backslash_replace(value); + document.change(Document::SPRITESHEETS); + } + } + + void shader_dialog_update(ShadersWindow& window, Manager& manager, Dialog& dialog, Dialog::Type type, + std::filesystem::path Element::* member) + { + if (!dialog.is_selected(type)) return; + + auto dialogPath = dialog.path; + auto spritesheetId = window.dialogSpritesheetId; + manager.command_push({manager.selected, + [dialogPath, spritesheetId, member](Manager&, Document& document) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return; + shader_path_edit(document, *spritesheet, member, + shader_asset_path_get(document, dialogPath)); + }}); + window.dialogSpritesheetId = -1; + dialog.reset(); + } + + void shader_path_row_update(ShadersWindow& window, Document& document, Resources& resources, Dialog& dialog, + Element* spritesheet, std::filesystem::path Element::* member, Dialog::Type dialogType, + StringType label) + { + auto shader = spritesheet ? shader_element_get(*spritesheet, false) : nullptr; + auto shaderPath = shader ? shader->*member : std::filesystem::path{}; + auto isDefault = shaderPath.empty(); + auto displayPath = isDefault ? path::from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; + + if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), + resources.icons[icon::FOLDER].id, icon_size_get())) + { + if (spritesheet) + { + window.dialogSpritesheetId = spritesheet->id; + dialog.file_open(dialogType); + } + } + + ImGui::SameLine(); + + auto labelWidth = ImGui::CalcTextSize(localize.get(label)).x; + auto inputWidth = ImGui::GetContentRegionAvail().x - labelWidth - ImGui::GetStyle().ItemSpacing.x; + if (inputWidth < ImGui::GetFrameHeight()) inputWidth = ImGui::GetFrameHeight(); + ImGui::SetNextItemWidth(inputWidth); + ImGui::BeginDisabled(isDefault); + auto isEdited = input_text_path(std::format("##{} Path", localize.get(label)).c_str(), &displayPath); + ImGui::EndDisabled(); + if (isEdited && spritesheet) + shader_path_edit(document, *spritesheet, member, displayPath); + + ImGui::SameLine(); + ImGui::TextUnformatted(localize.get(label)); + } + + void shader_uniform_config_save(Document& document, Element& shaderElement, const resource::shader::Uniform& uniform) + { + auto config = shader_uniform_get(shaderElement, uniform.name, true); + if (!config) return; + + config->binding = std::string(resource::shader::uniform_binding_value_get(uniform.binding)); + config->value = resource::shader::uniform_value_string_get(uniform); + if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + { + for (int index = 0; index < (int)uniform.components.size(); ++index) + { + auto component = shader_uniform_component_get(*config, index, true); + if (!component) continue; + component->binding = std::string(resource::shader::uniform_binding_value_get(uniform.components[index].binding)); + component->value = std::format("{:.6g}", uniform.components[index].value); + } + } + else + std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; }); + document.change(Document::SPRITESHEETS); + } + + int shader_uniform_component_count_get(resource::shader::UniformValueType type) + { + if (type == resource::shader::UNIFORM_VALUE_VEC2) return 2; + if (type == resource::shader::UNIFORM_VALUE_VEC3) return 3; + if (type == resource::shader::UNIFORM_VALUE_VEC4) return 4; + return 0; + } + + void shader_uniform_components_from_value_set(resource::shader::Uniform& uniform) + { + uniform.components[0].value = uniform.value.x; + uniform.components[1].value = uniform.value.y; + uniform.components[2].value = uniform.value.z; + uniform.components[3].value = uniform.value.w; + } + + void shader_uniform_value_from_components_set(resource::shader::Uniform& uniform) + { + uniform.value.x = uniform.components[0].value; + uniform.value.y = uniform.components[1].value; + uniform.value.z = uniform.components[2].value; + uniform.value.w = uniform.components[3].value; + } + + bool shader_uniform_value_update(resource::shader::Uniform& uniform) + { + ImGui::SetNextItemWidth(-1.0f); + switch (uniform.valueType) + { + case resource::shader::UNIFORM_VALUE_FLOAT: + return ImGui::DragFloat("##Value", &uniform.value.x, 0.01f); + case resource::shader::UNIFORM_VALUE_INT: + case resource::shader::UNIFORM_VALUE_SAMPLER2D: + return ImGui::InputInt("##Value", &uniform.intValue); + case resource::shader::UNIFORM_VALUE_VEC2: + return ImGui::DragFloat2("##Value", &uniform.value.x, 0.01f); + case resource::shader::UNIFORM_VALUE_VEC3: + return ImGui::DragFloat3("##Value", &uniform.value.x, 0.01f); + case resource::shader::UNIFORM_VALUE_VEC4: + return ImGui::DragFloat4("##Value", &uniform.value.x, 0.01f); + default: + ImGui::TextUnformatted(localize.get(BASIC_NONE)); + return false; + } + } + + bool shader_uniform_component_binding_update(resource::shader::Uniform::Component& component) + { + auto bindingLabel = resource::shader::uniform_binding_label_get(component.binding); + ImGui::SetNextItemWidth(ImGui::GetFrameHeight() * 5.0f); + if (!ImGui::BeginCombo("##Component Binding", bindingLabel.data())) return false; + + bool isChanged{}; + constexpr resource::shader::UniformBinding bindings[] = {resource::shader::UNIFORM_BINDING_MANUAL, + resource::shader::UNIFORM_BINDING_PLAYBACK_TIME}; + for (auto binding : bindings) + { + auto isSelected = component.binding == binding; + auto label = resource::shader::uniform_binding_label_get(binding); + if (ImGui::Selectable(label.data(), isSelected)) + { + component.binding = binding; + isChanged = true; + } + if (isSelected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + return isChanged; + } + + bool shader_uniform_components_update(resource::shader::Uniform& uniform) + { + bool isChanged{}; + constexpr const char* labels[] = {"X", "Y", "Z", "W"}; + auto componentCount = shader_uniform_component_count_get(uniform.valueType); + + for (int index = 0; index < componentCount; ++index) + { + auto& component = uniform.components[index]; + ImGui::PushID(index); + if (index > 0) ImGui::Spacing(); + ImGui::TextUnformatted(labels[index]); + ImGui::SameLine(); + if (shader_uniform_component_binding_update(component)) isChanged = true; + ImGui::SameLine(); + ImGui::BeginDisabled(component.binding != resource::shader::UNIFORM_BINDING_MANUAL); + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::DragFloat("##Component Value", &component.value, 0.01f)) isChanged = true; + ImGui::EndDisabled(); + ImGui::PopID(); + } + + if (isChanged) shader_uniform_value_from_components_set(uniform); + return isChanged; + } + + void shader_uniforms_update(Document& document, Element* shaderElement, resource::Shader* runtime) + { + if (!shaderElement || !runtime) return; + + if (runtime->uniforms.empty()) + { + ImGui::TextUnformatted(localize.get(BASIC_NONE)); + return; + } + + auto flags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | + ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY; + auto tableSize = ImGui::GetContentRegionAvail(); + if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); + if (!ImGui::BeginTable("##Shader Uniforms", 4, flags, tableSize)) return; + + ImGui::TableSetupColumn(localize.get(BASIC_NAME)); + ImGui::TableSetupColumn(localize.get(LABEL_TYPE)); + ImGui::TableSetupColumn(localize.get(LABEL_BINDING)); + ImGui::TableSetupColumn(localize.get(LABEL_VALUE_COLUMN)); + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableHeadersRow(); + + for (auto& uniform : runtime->uniforms) + { + ImGui::PushID(uniform.name.c_str()); + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(uniform.name.c_str()); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(resource::shader::uniform_value_type_label_get(uniform.valueType).data()); + + ImGui::TableNextColumn(); + auto bindingLabel = resource::shader::uniform_binding_label_get(uniform.binding); + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::BeginCombo("##Binding", bindingLabel.data())) + { + for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) + { + if (!resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) continue; + auto isSelected = uniform.binding == binding; + auto label = resource::shader::uniform_binding_label_get(binding); + if (ImGui::Selectable(label.data(), isSelected)) + { + uniform.binding = binding; + if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + shader_uniform_components_from_value_set(uniform); + shader_uniform_config_save(document, *shaderElement, uniform); + } + if (isSelected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + ImGui::TableNextColumn(); + if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + { + if (shader_uniform_components_update(uniform)) shader_uniform_config_save(document, *shaderElement, uniform); + } + else + { + ImGui::BeginDisabled(uniform.binding != resource::shader::UNIFORM_BINDING_MANUAL); + if (shader_uniform_value_update(uniform)) + { + shader_uniform_components_from_value_set(uniform); + shader_uniform_config_save(document, *shaderElement, uniform); + } + ImGui::EndDisabled(); + } + + ImGui::PopID(); + } + + ImGui::EndTable(); + } + + void ShadersWindow::update(Manager& manager, Settings& settings, Resources& resources, Dialog& dialog) + { + if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) + { + auto document = manager.get(); + auto spritesheet = document ? shader_spritesheet_get(*document) : nullptr; + auto shader = spritesheet ? shader_element_get(*spritesheet, false) : nullptr; + auto isShaderEnabled = !shader || shader->isEnabled; + auto isReloadNeeded = document && spritesheet && is_shader_reload_needed(*document, *spritesheet, shader); + + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &Element::vertex); + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &Element::fragment); + + if (!spritesheet) + { + ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); + ImGui::End(); + return; + } + + auto contentSize = size_without_footer_get(); + if (contentSize.y < ImGui::GetFrameHeight()) contentSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shaders Child", contentSize, ImGuiChildFlags_Borders)) + { + ImGui::BeginDisabled(!isShaderEnabled); + if (ImGui::BeginTabBar("##Shaders Tabs")) + { + if (ImGui::BeginTabItem(localize.get(LABEL_FILES))) + { + if (document) + { + shader_path_row_update(*this, *document, resources, dialog, spritesheet, &Element::vertex, + Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); + shader_path_row_update(*this, *document, resources, dialog, spritesheet, &Element::fragment, + Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); + } + + if (isReloadNeeded) ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); + + ImGui::Separator(); + + auto consoleSize = ImGui::GetContentRegionAvail(); + if (consoleSize.y < ImGui::GetFrameHeight()) consoleSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shaders Console", consoleSize, ImGuiChildFlags_Borders)) + ImGui::TextWrapped("%s", status.c_str()); + ImGui::EndChild(); + + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem(localize.get(LABEL_UNIFORMS))) + { + shader_uniforms_update(*document, shader, document->shader_get(spritesheet->id)); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::EndDisabled(); + } + ImGui::EndChild(); + + auto widgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(isShaderEnabled ? BASIC_ENABLED : BASIC_DISABLED), widgetSize)) + { + auto spritesheetId = spritesheet->id; + auto isNextEnabled = !isShaderEnabled; + manager.command_push({manager.selected, + [spritesheetId, isNextEnabled](Manager&, Document& document) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (spritesheet) shader_enabled_set(document, *spritesheet, isNextEnabled); + }}); + } + + ImGui::SameLine(); + + ImGui::BeginDisabled(!isShaderEnabled || !document); + if (ImGui::Button(localize.get(BASIC_RELOAD), widgetSize) && document) + { + status.clear(); + document->shader_reload(spritesheet->id, &status); + } + ImGui::EndDisabled(); + } + ImGui::End(); + } +} diff --git a/src/imgui/window/shaders.hpp b/src/imgui/window/shaders.hpp new file mode 100644 index 0000000..21601db --- /dev/null +++ b/src/imgui/window/shaders.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "dialog.hpp" +#include "manager.hpp" +#include "resources.hpp" +#include "settings.hpp" + +namespace anm2ed::imgui +{ + class ShadersWindow + { + public: + std::string status{}; + int dialogSpritesheetId{-1}; + void update(Manager&, Settings&, Resources&, Dialog&); + }; +} diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 308512e..072f1f1 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -36,7 +36,6 @@ namespace anm2ed::imgui auto& anm2 = document.anm2; auto& reference = document.reference; auto& referenceSpritesheet = document.spritesheet.reference; - auto referenceItemType = static_cast(reference.itemType); auto& pan = document.editorPan; auto& zoom = document.editorZoom; auto& backgroundColor = settings.editorBackgroundColor; @@ -62,10 +61,17 @@ namespace anm2ed::imgui }; if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get(); selectedLayerSpritesheet != -1 && document.editTarget != Document::EditTarget::REGION && - document.editTarget != Document::EditTarget::SPRITESHEET) + document.editTarget != Document::EditTarget::OVERLAY && document.editTarget != Document::EditTarget::SPRITESHEET) referenceSpritesheet = selectedLayerSpritesheet; auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, referenceSpritesheet); - auto texture = document.texture_get(referenceSpritesheet); + auto baseTexture = document.texture_get(referenceSpritesheet); + auto activeOverlayId = -1; + auto activeOverlay = document.editTarget == Document::EditTarget::OVERLAY ? document.overlay_get() : nullptr; + if (activeOverlay && document.overlay_spritesheet_id_get(activeOverlay->id) == referenceSpritesheet) + activeOverlayId = activeOverlay->id; + else + activeOverlay = nullptr; + auto texture = activeOverlayId != -1 ? document.overlay_texture_get(activeOverlayId) : baseTexture; auto& tool = settings.tool; auto& shaderGrid = resources.shaders[shader::GRID]; auto& shaderTexture = resources.shaders[shader::TEXTURE]; @@ -226,17 +232,28 @@ namespace anm2ed::imgui viewport_set(); clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f)); - auto frame = - anm2.element_get(reference.animationIndex, referenceItemType, reference.frameIndex, reference.itemID); + auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; - if (spritesheet && texture && texture->is_valid()) + auto viewTexture = baseTexture && baseTexture->is_valid() ? baseTexture : texture; + + if (spritesheet && viewTexture && viewTexture->is_valid()) { auto transform = transform_get(zoom, pan); - auto spritesheetModel = math::quad_model_get(texture->size); + auto spritesheetModel = math::quad_model_get(viewTexture->size); auto spritesheetTransform = transform * spritesheetModel; - texture_render(shaderTexture, texture->id, spritesheetTransform); + if (baseTexture && baseTexture->is_valid()) texture_render(shaderTexture, baseTexture->id, spritesheetTransform); + + for (auto& overlay : spritesheet->children) + { + if (overlay.type != ElementType::OVERLAY) continue; + if (!overlay.isVisible) continue; + auto overlayTexture = document.overlay_texture_get(overlay.id); + if (!overlayTexture || !overlayTexture->is_valid()) continue; + auto overlayTransform = transform * math::quad_model_get(overlayTexture->size); + texture_render(shaderTexture, overlayTexture->id, overlayTransform); + } if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); @@ -376,10 +393,10 @@ namespace anm2ed::imgui auto editReference = reference; if (!selectedFrameReferences.contains(reference) && !selectedFrameReferences.empty()) editReference = *selectedFrameReferences.begin(); - auto editReferenceItemType = static_cast(editReference.itemType); - auto frame = anm2.element_get(editReference.animationIndex, editReferenceItemType, editReference.frameIndex, - editReference.itemID); - auto item = anm2.element_get(editReference.animationIndex, editReferenceItemType, editReference.itemID); + auto frame = editReference.frameIndex >= 0 ? anm2.element_get(editReference) : nullptr; + auto itemReference = editReference; + itemReference.frameIndex = -1; + auto item = anm2.element_get(itemReference); auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, editReference.itemID); bool isReferenceLayerOnSpritesheet = frame && editReference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; @@ -423,11 +440,28 @@ namespace anm2ed::imgui auto fraction = current - glm::floor(current); return glm::floor(value) + fraction; }; - auto snapshot_push = [&](StringType messageType) + auto frame_snapshot_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 region_snapshot_push = [&](StringType messageType, const std::set& regionIds) + { + auto message = std::string(localize.get(messageType)); + auto queuedSpritesheet = referenceSpritesheet; + auto queuedRegionIds = regionIds; + manager.command_push({manager.selected, + [message, queuedSpritesheet, queuedRegionIds](Manager&, Document& document) + { document.regions_snapshot(message, queuedSpritesheet, queuedRegionIds); }}); + }; + auto texture_snapshot_push = [&](StringType messageType) { auto message = std::string(localize.get(messageType)); manager.command_push( - {manager.selected, [message](Manager&, Document& document) { document.snapshot(message); }}); + {manager.selected, [message](Manager&, Document& document) { document.textures_snapshot(message); }}); }; auto document_change_push = [&](Document::ChangeType changeType) { @@ -443,13 +477,16 @@ namespace anm2ed::imgui { std::map> groupedFrames{}; for (auto frameReference : queuedFrameReferences) - groupedFrames[{frameReference.animationIndex, frameReference.itemType, frameReference.itemID, -1}] - .insert(frameReference.frameIndex); + { + auto itemReference = frameReference; + itemReference.frameIndex = -1; + groupedFrames[itemReference].insert(frameReference.frameIndex); + } for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference.animationIndex, itemType, itemReference.itemID); + auto item = document.anm2.element_get(itemReference); if (!item) continue; frames_change(*item, frameChange, itemType, changeType, itemFrames); } @@ -461,24 +498,26 @@ namespace anm2ed::imgui ChangeType changeType = ChangeType::ADJUST) { auto queuedReference = editReference; - auto queuedReferenceItemType = editReferenceItemType; auto queuedFrameReferences = frameReferences; manager.command_push( {manager.selected, [=](Manager&, Document& document) { - auto frame = document.anm2.element_get(queuedReference.animationIndex, queuedReferenceItemType, - queuedReference.frameIndex, queuedReference.itemID); + if (queuedReference.frameIndex < 0) return; + auto frame = document.anm2.element_get(queuedReference); if (!frame) return; std::map> groupedFrames{}; for (auto frameReference : queuedFrameReferences) - groupedFrames[{frameReference.animationIndex, frameReference.itemType, frameReference.itemID, -1}] - .insert(frameReference.frameIndex); + { + auto itemReference = frameReference; + itemReference.frameIndex = -1; + groupedFrames[itemReference].insert(frameReference.frameIndex); + } for (auto& [itemReference, itemFrames] : groupedFrames) { auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference.animationIndex, itemType, itemReference.itemID); + auto item = document.anm2.element_get(itemReference); if (!item) continue; frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames); } @@ -602,9 +641,11 @@ namespace anm2ed::imgui auto texture_line_apply = [&](ivec2 start, ivec2 end, vec4 color) { auto queuedSpritesheet = referenceSpritesheet; + auto queuedOverlay = activeOverlayId; manager.command_push({manager.selected, [=](Manager&, Document& document) { - auto texture = document.texture_get(queuedSpritesheet); + auto texture = queuedOverlay != -1 ? document.overlay_texture_get(queuedOverlay) + : document.texture_get(queuedSpritesheet); if (!texture) return; texture->pixel_line(start, end, color); }}); @@ -612,8 +653,15 @@ namespace anm2ed::imgui auto texture_change_push = [&]() { auto queuedSpritesheet = referenceSpritesheet; + auto queuedOverlay = activeOverlayId; manager.command_push( - {manager.selected, [=](Manager&, Document& document) { document.texture_change(queuedSpritesheet); }}); + {manager.selected, [=](Manager&, Document& document) + { + if (queuedOverlay != -1) + document.overlay_texture_change(queuedOverlay); + else + document.texture_change(queuedSpritesheet); + }}); }; auto region_selection_set = [&](int id) @@ -701,7 +749,7 @@ namespace anm2ed::imgui region_selection_set(hoveredRegionId); if (isReferenceLayerOnSpritesheet) { - snapshot_push(EDIT_FRAME_REGION); + frame_snapshot_push(EDIT_FRAME_REGION, selectedFrameReferences); FrameChange change{}; change.regionId = hoveredRegionId; if (auto region = region_get(hoveredRegionId)) @@ -726,7 +774,7 @@ namespace anm2ed::imgui auto region = region_get(regionReference); if (!region) break; - if (isBegin) snapshot_push(EDIT_REGION_MOVE); + if (isBegin) region_snapshot_push(EDIT_REGION_MOVE, {regionReference}); if (isMouseDown) region_pivot_set(regionReference, pivot_snap(mousePos - region->crop, region->pivot)); if (isLeftPressed) region_pivot_offset(regionReference, vec2(-step, 0)); if (isRightPressed) region_pivot_offset(regionReference, vec2(step, 0)); @@ -749,7 +797,7 @@ namespace anm2ed::imgui } if (!item || !frame || selectedFrameToolReferences.empty() || isRegionInUse) break; - if (isBegin) snapshot_push(EDIT_FRAME_PIVOT); + if (isBegin) frame_snapshot_push(EDIT_FRAME_PIVOT, selectedFrameToolReferences); if (isMouseDown) { auto pivot = pivot_snap(mousePos - frame->crop, frame->pivot); @@ -784,7 +832,7 @@ namespace anm2ed::imgui if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && !regionSelection.empty()) { if (!spritesheet || regionSelection.empty()) break; - if (isBegin) snapshot_push(EDIT_REGION_CROP); + if (isBegin) region_snapshot_push(EDIT_REGION_CROP, regionSelection); if (isMouseClicked) { @@ -825,7 +873,7 @@ namespace anm2ed::imgui } if (!item || !frame || selectedFrameToolReferences.empty() || isRegionInUse) break; - if (isBegin) snapshot_push(EDIT_FRAME_CROP); + if (isBegin) frame_snapshot_push(EDIT_FRAME_CROP, selectedFrameToolReferences); if (isMouseClicked) { @@ -880,7 +928,7 @@ namespace anm2ed::imgui { if (!texture) break; auto color = useTool == tool::DRAW ? toolColor : vec4(); - if (isMouseClicked) snapshot_push(useTool == tool::DRAW ? EDIT_DRAW : EDIT_ERASE); + if (isMouseClicked) texture_snapshot_push(useTool == tool::DRAW ? EDIT_DRAW : EDIT_ERASE); if (isMouseDown) texture_line_apply(ivec2(previousMousePos), ivec2(mousePos), color); if (isMouseReleased) texture_change_push(); break; diff --git a/src/imgui/window/timeline.cpp b/src/imgui/window/timeline.cpp index 3175345..9b75e37 100644 --- a/src/imgui/window/timeline.cpp +++ b/src/imgui/window/timeline.cpp @@ -108,6 +108,8 @@ namespace anm2ed::imgui int id{-1}; int index{-1}; int groupId{-1}; + int rootGroupType{NONE}; + int rootGroupId{-1}; int depth{}; bool isGroup{}; }; @@ -140,16 +142,56 @@ namespace anm2ed::imgui 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) - { return animation ? animation_item_get(*animation, item_type_get(type), id) : nullptr; }; + 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 = [&]() { - return anm2.element_get(reference.animationIndex, item_type_get(reference.itemType), reference.frameIndex, - reference.itemID); + if (reference.frameIndex < 0) return (Element*)nullptr; + return anm2.element_get(reference); }; auto selected_item_get = [&]() - { return anm2.element_get(reference.animationIndex, item_type_get(reference.itemType), reference.itemID); }; - auto item_frames_count = [](const Element* item) { return item ? (int)item->children.size() : 0; }; + { + 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) { @@ -208,15 +250,21 @@ namespace anm2ed::imgui 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) + 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) : nullptr; + 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) { - return document.anm2.element_get(targetReference.animationIndex, static_cast(targetReference.itemType), - targetReference.frameIndex, targetReference.itemID); + 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); }; @@ -224,7 +272,8 @@ namespace anm2ed::imgui { 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) { return Reference{reference.animationIndex, type, id}; }; + 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; @@ -233,7 +282,7 @@ namespace anm2ed::imgui auto is_same_item = [](const Reference& left, const Reference& right) { return left.animationIndex == right.animationIndex && left.itemType == right.itemType && - left.itemID == right.itemID; + 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); }; @@ -248,7 +297,11 @@ namespace anm2ed::imgui { std::set result = document.items.references; if (result.empty() && reference.itemType != NONE) - result.insert(item_reference_get(reference.itemType, reference.itemID)); + { + auto itemReference = reference; + itemReference.frameIndex = -1; + result.insert(itemReference); + } return result; }; auto frames_selection_sync_for = [&](Document& targetDocument) @@ -302,8 +355,7 @@ namespace anm2ed::imgui if (!is_same_item(firstReference, lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) return false; - auto item = command_item_get(targetDocument, lastReference.animationIndex, lastReference.itemType, - lastReference.itemID); + 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()) @@ -316,7 +368,11 @@ namespace anm2ed::imgui : std::set{}; for (int i = firstIndex; i <= lastIndex; ++i) - selectedFrames.insert({lastReference.animationIndex, lastReference.itemType, lastReference.itemID, i}); + { + auto frameReference = lastReference; + frameReference.frameIndex = i; + selectedFrames.insert(frameReference); + } targetDocument.reference = lastReference; targetDocument.frame_references_set(std::move(selectedFrames)); @@ -373,18 +429,19 @@ namespace anm2ed::imgui frames_selection_reset_for(targetDocument); targetDocument.items.references.clear(); }; - auto reference_set_item_for = [=](Document& targetDocument, int type, int id) + auto reference_set_item_reference_for = [=](Document& targetDocument, Reference itemReference) { - targetDocument.reference = {targetDocument.reference.animationIndex, type, id}; + itemReference.frameIndex = -1; + targetDocument.reference = itemReference; frames_selection_reset_for(targetDocument); - item_selection_set_for(targetDocument, targetDocument.reference); + item_selection_set_for(targetDocument, itemReference); }; - auto reference_set_timeline_item_for = [=](Document& targetDocument, int type, int id) + auto reference_set_timeline_item_reference_for = [=](Document& targetDocument, Reference itemReference) { - if (type == LAYER) - if (auto layer = command_layer_get(targetDocument, id)) + if (itemReference.itemType == LAYER) + if (auto layer = command_layer_get(targetDocument, itemReference.itemID)) targetDocument.spritesheet.reference = layer->spritesheetId; - reference_set_item_for(targetDocument, type, id); + reference_set_item_reference_for(targetDocument, itemReference); }; auto command_push = [&](auto run) { @@ -394,8 +451,17 @@ namespace anm2ed::imgui auto snapshot_command_push = [&](StringType messageType) { auto message = std::string(localize.get(messageType)); - manager.command_push( - {manager.selected, [message](Manager&, Document& document) { document.snapshot(message); }}); + manager.command_push({manager.selected, + [message](Manager&, Document& document) + { document.anm2_snapshot(message); }}); + }; + 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 edit_command_push = [&](StringType messageType, Document::ChangeType changeType, auto run) { @@ -403,7 +469,8 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [=](Manager& manager, Document& document) mutable { - document.snapshot(message); + (void)changeType; + document.anm2_snapshot(message); run(manager, document); document.anm2_change(changeType); }}); @@ -477,16 +544,14 @@ namespace anm2ed::imgui { auto targetReference = reference; auto targetFrameTime = document.frameTime; - if (!animation || !command_item_get(document, targetReference.animationIndex, targetReference.itemType, - targetReference.itemID)) + if (!animation || !command_item_reference_get(document, targetReference)) return; edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, [=, this](Manager&, Document& document) mutable { auto animation = command_animation_get(document, targetReference.animationIndex); - auto item = command_item_get(document, targetReference.animationIndex, - targetReference.itemType, targetReference.itemID); + auto item = command_item_reference_get(document, targetReference); if (!animation || !item) return; auto newReference = targetReference; @@ -505,19 +570,19 @@ namespace anm2ed::imgui 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, (int)item->children.size()); - item->children.insert(item->children.begin() + insertIndex, addFrame); + 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 (!item->children.empty()) + else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) { - auto addFrame = item->children.back(); - item->children.emplace_back(addFrame); - newReference.frameIndex = (int)item->children.size() - 1; + item->children.emplace_back(*lastFrame); + newReference.frameIndex = framesCount; } else { @@ -544,19 +609,17 @@ namespace anm2ed::imgui for (auto& [itemReference, indices] : groupedFrames) { - auto item = command_item_get(document, itemReference.animationIndex, itemReference.itemType, - itemReference.itemID); + auto item = command_item_reference_get(document, itemReference); if (!item) continue; for (auto it = indices.rbegin(); it != indices.rend(); ++it) { - auto i = *it; - if (i >= 0 && i < (int)item->children.size()) item->children.erase(item->children.begin() + i); + auto childIndex = item_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); } } - auto item = command_item_get(document, document.reference.animationIndex, document.reference.itemType, - document.reference.itemID); + auto item = command_item_reference_get(document, document.reference); if (!item || item->children.empty()) { document.reference.frameIndex = -1; @@ -600,32 +663,33 @@ namespace anm2ed::imgui for (auto& [itemReference, indices] : groupedFrames) { - auto item = command_item_get(document, itemReference.animationIndex, - itemReference.itemType, itemReference.itemID); + auto item = command_item_reference_get(document, itemReference); if (!item) continue; std::vector validIndices{}; std::vector duplicatedFrames{}; for (auto i : indices) { - if (!vector::in_bounds(item->children, i)) continue; + auto frame = track_frame_get(*item, i); + if (!frame) continue; validIndices.push_back(i); - duplicatedFrames.push_back(item->children[i]); + duplicatedFrames.push_back(*frame); } if (validIndices.empty()) continue; auto insertIndex = validIndices.back() + 1; - item->children.insert(item->children.begin() + insertIndex, + 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 = Reference{itemReference.animationIndex, itemReference.itemType, - itemReference.itemID, insertIndex + offset}; + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; duplicatedSelection.insert(targetReference); - auto sourceReference = Reference{itemReference.animationIndex, itemReference.itemType, - itemReference.itemID, validIndices[offset]}; + auto sourceReference = itemReference; + sourceReference.frameIndex = validIndices[offset]; if (sourceReference == document.reference) { newReference = targetReference; @@ -637,8 +701,7 @@ namespace anm2ed::imgui if (duplicatedSelection.empty()) return; document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); document.frame_references_set(std::move(duplicatedSelection)); - if (auto item = command_item_get(document, document.reference.animationIndex, - document.reference.itemType, document.reference.itemID)) + 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; @@ -685,37 +748,41 @@ namespace anm2ed::imgui for (auto& [itemReference, indices] : groupedFrames) { - auto item = command_item_get(document, itemReference.animationIndex, - itemReference.itemType, itemReference.itemID); + auto item = command_item_reference_get(document, itemReference); if (!item || indices.size() < 2) continue; std::vector validIndices{}; std::vector reversedFrames{}; for (auto i : indices) { - if (!vector::in_bounds(item->children, i)) continue; + auto frame = track_frame_get(*item, i); + if (!frame) continue; validIndices.push_back(i); - reversedFrames.push_back(std::move(item->children[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) - item->children.erase(item->children.begin() + *it); + { + auto childIndex = item_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } std::ranges::reverse(reversedFrames); - item->children.insert(item->children.begin() + insertIndex, + 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 = Reference{itemReference.animationIndex, itemReference.itemType, - itemReference.itemID, insertIndex + offset}; + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; reversedSelection.insert(targetReference); auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; - auto sourceReference = Reference{itemReference.animationIndex, itemReference.itemType, - itemReference.itemID, sourceIndex}; + auto sourceReference = itemReference; + sourceReference.frameIndex = sourceIndex; if (sourceReference == document.reference) { newReference = targetReference; @@ -727,8 +794,7 @@ namespace anm2ed::imgui if (reversedSelection.empty()) return; document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); document.frame_references_set(std::move(reversedSelection)); - if (auto item = command_item_get(document, document.reference.animationIndex, - document.reference.itemType, document.reference.itemID)) + 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; @@ -762,26 +828,28 @@ namespace anm2ed::imgui std::set bakedSelection{}; for (auto& [itemReference, indices] : groupedFrames) { - auto item = command_item_get(document, itemReference.animationIndex, - itemReference.itemType, itemReference.itemID); + auto item = command_item_reference_get(document, itemReference); if (!item) continue; int insertedBefore = 0; for (auto originalIndex : indices) { auto i = originalIndex + insertedBefore; - if (!vector::in_bounds(item->children, i)) continue; + auto frame = track_frame_get(*item, i); + if (!frame) continue; - auto originalDuration = item->children[i].duration; + 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) - bakedSelection.insert( - {itemReference.animationIndex, itemReference.itemType, itemReference.itemID, - i + offset}); + { + auto frameReference = itemReference; + frameReference.frameIndex = i + offset; + bakedSelection.insert(frameReference); + } insertedBefore += bakedCount - 1; } @@ -840,7 +908,8 @@ namespace anm2ed::imgui } if (item.type != trackType) return; auto itemID = itemType == LAYER ? item.layerId : item.nullId; - result.insert({animationIndex, itemType, itemID, -1}); + 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); @@ -901,7 +970,10 @@ namespace anm2ed::imgui { auto animation = command_animation_get(document, document.reference.animationIndex); if (!animation) return; - auto root = command_item_get(document, document.reference.animationIndex, ROOT, -1); + 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{}; @@ -920,30 +992,36 @@ namespace anm2ed::imgui for (auto itemReference : targetItems) { - auto item = command_item_get(document, itemReference.animationIndex, - itemReference.itemType, itemReference.itemID); + auto item = command_item_reference_get(document, itemReference); if (!item) continue; if (isMatchRootInterpolation) { std::vector bakeIndices{}; - for (auto [i, frame] : std::views::enumerate(item->children)) + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) { - auto frameStart = (int)frame_time_from_index_get(*item, (int)i); + 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((int)i); + bakeIndices.push_back(frameIndex); break; } + ++frameIndex; } for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); } - for (auto [i, frame] : std::views::enumerate(item->children)) + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (auto& frame : item->children) { - auto frameStart = (int)frame_time_from_index_get(*item, (int)i); + 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) @@ -951,10 +1029,15 @@ namespace anm2ed::imgui isInsideSpan = true; break; } - if (!isInsideSpan) continue; + if (!isInsideSpan) + { + ++frameIndex; + continue; + } auto rootFrame = frame_generate(*root, (float)frameStart); frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, isUseRootPivot); + ++frameIndex; } } @@ -977,8 +1060,9 @@ namespace anm2ed::imgui if (defaultDuration <= 0) return; auto frame = element_make(ElementType::FRAME); frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); - defaultRootSelection.insert({document.reference.animationIndex, ROOT, -1, - rewrittenFrameIndex}); + auto defaultRootReference = rootItemReference; + defaultRootReference.frameIndex = rewrittenFrameIndex; + defaultRootSelection.insert(defaultRootReference); rootFrames.push_back(frame); ++rewrittenFrameIndex; defaultDuration = 0; @@ -1031,8 +1115,7 @@ namespace anm2ed::imgui { if (targetReference.itemType == TRIGGER) return; - auto item = command_item_get(document, targetReference.animationIndex, - targetReference.itemType, targetReference.itemID); + auto item = command_item_reference_get(document, targetReference); auto frame = command_frame_get(document, targetReference); if (!item || !frame) return; @@ -1081,7 +1164,8 @@ namespace anm2ed::imgui } frame->duration = firstDuration; - item->children.insert(item->children.begin() + targetReference.frameIndex + 1, splitFrame); + 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); }); @@ -1093,10 +1177,10 @@ namespace anm2ed::imgui reference_clear_for(document); }; - auto reference_set_timeline_item = [&](int type, int id) + auto reference_set_timeline_item_reference = [&](Reference itemReference) { group_selection_reset_for(document); - reference_set_timeline_item_for(document, type, id); + reference_set_timeline_item_reference_for(document, itemReference); }; auto timeline_item_rows_get = [&]() @@ -1106,16 +1190,23 @@ namespace anm2ed::imgui 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{}; @@ -1145,7 +1236,11 @@ namespace anm2ed::imgui if (item.type == ElementType::GROUP) { group_row_push(item, LAYER, i); - if (item.isExpanded) layer_track_push(item.id, 1); + 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())) @@ -1172,7 +1267,11 @@ namespace anm2ed::imgui if (item.type == ElementType::GROUP) { group_row_push(item, NULL_, i); - if (item.isExpanded) null_track_push(item.id, 1); + 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())) @@ -1190,7 +1289,8 @@ namespace anm2ed::imgui for (const auto& row : timeline_item_rows_get()) { if (row.isGroup) continue; - itemReferences.push_back({reference.animationIndex, row.type, row.id}); + itemReferences.push_back( + {reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); } return itemReferences; }; @@ -1200,11 +1300,12 @@ namespace anm2ed::imgui auto row_reference_get = [&](const TimelineItemRow& row) { - return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, row.index, row.isGroup}; + 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}; }; + { return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; }; auto timeline_row_references_get = [&]() { @@ -1225,8 +1326,8 @@ namespace anm2ed::imgui auto is_row_selected = [&](const TimelineItemRow& row) { if (row.isGroup) return is_group_selected(row); - auto itemReference = item_reference_get(row.type, row.id); - auto isReferenced = reference.itemType == row.type && reference.itemID == row.id; + 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); }; @@ -1325,14 +1426,14 @@ namespace anm2ed::imgui auto it = std::find_if( itemReferences.begin(), itemReferences.end(), [&](const Reference& itemReference) - { return itemReference.itemType == reference.itemType && itemReference.itemID == reference.itemID; }); + { 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(itemReference.itemType, itemReference.itemID); + reference_set_timeline_item_reference(itemReference); }; auto selected_row_references_get = [&]() @@ -1489,6 +1590,9 @@ namespace anm2ed::imgui 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) @@ -1574,13 +1678,34 @@ namespace anm2ed::imgui } 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; - targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); + 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; @@ -1658,7 +1783,8 @@ namespace anm2ed::imgui std::string clipboardString{}; for (auto frameReference : selectedFrames) { - auto item = item_get(frameReference.itemType, frameReference.itemID); + 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)); @@ -1678,19 +1804,18 @@ namespace anm2ed::imgui auto paste = [&]() { - if (clipboard.is_empty()) return; 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 { - document.snapshot(message); + document.anm2_snapshot(message); auto animation = command_animation_get(document, targetReference.animationIndex); if (!animation) return; - if (auto item = command_item_get(document, targetReference.animationIndex, - targetReference.itemType, targetReference.itemID)) + if (auto item = command_item_reference_get(document, targetReference)) { std::set indices{}; std::string errorString{}; @@ -1814,7 +1939,8 @@ namespace anm2ed::imgui [&](const Reference& frameReference) { if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID); + 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); @@ -1825,7 +1951,7 @@ namespace anm2ed::imgui makeManyRegionsPopup.open(); }; - auto item = item_get(reference.itemType, reference.itemID); + auto item = selected_item_get(); auto frame = frame_get(); auto selectedFrames = frame_references_for_current_get(); auto selectedBakeFrames = selectedFrames; @@ -1837,7 +1963,8 @@ namespace anm2ed::imgui [&](const Reference& frameReference) { if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID); + 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); @@ -2034,6 +2161,8 @@ namespace anm2ed::imgui 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); @@ -2226,7 +2355,7 @@ namespace anm2ed::imgui return; } - auto item = item_get(type, id); + auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); if (type != NONE && !item) { ImGui::PopID(); @@ -2234,9 +2363,11 @@ namespace anm2ed::imgui } 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 = reference.itemType == type && reference.itemID == id; + auto isReferenced = is_same_item(reference, row_reference_make()); auto isItemSelected = is_row_selected(row); auto label = [&]() -> std::string @@ -2446,10 +2577,13 @@ namespace anm2ed::imgui 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); + auto item = command_item_get(document, animationIndex, targetType, targetID, + targetGroupType, targetGroupId); if (!item) return; item->isVisible = !item->isVisible; }); @@ -2650,6 +2784,8 @@ namespace anm2ed::imgui int frameMoveDropType = NONE; int frameMoveDropItemID = -1; + int frameMoveDropGroupType = NONE; + int frameMoveDropGroupId = -1; int frameMoveDropIndex = -1; bool isFrameMoveDropTarget = false; @@ -2657,9 +2793,15 @@ namespace anm2ed::imgui { frameMoveDrag = {}; frameSelectionLocked.clear(); + frameMoveDropType = NONE; + frameMoveDropItemID = -1; + frameMoveDropGroupType = NONE; + frameMoveDropGroupId = -1; + frameMoveDropIndex = -1; + isFrameMoveDropTarget = false; }; - auto frames_move_to = [&](int targetType, int targetID, int insertIndex) + 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; @@ -2668,7 +2810,8 @@ namespace anm2ed::imgui 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.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; @@ -2676,7 +2819,9 @@ namespace anm2ed::imgui edit_command_push(EDIT_MOVE_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable { - auto targetItem = command_item_get(document, drag.animationIndex, targetType, targetID); + auto targetItem = + command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, + targetGroupId); if (!targetItem) return; std::map> groupedFrames{}; @@ -2690,36 +2835,37 @@ namespace anm2ed::imgui std::vector movedFrames; for (auto& [itemReference, indices] : groupedFrames) { - auto sourceItem = command_item_get(document, itemReference.animationIndex, - itemReference.itemType, itemReference.itemID); + auto sourceItem = command_item_reference_get(document, itemReference); if (!sourceItem) continue; for (auto i : indices) { - if (i < 0 || i >= (int)sourceItem->children.size()) continue; - movedFrames.push_back(std::move(sourceItem->children[i])); + 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 i = *it; - if (i >= 0 && i < (int)sourceItem->children.size()) - sourceItem->children.erase(sourceItem->children.begin() + i); + 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, (int)targetItem->children.size()); + int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); desired -= removedBeforeTarget; - desired = std::clamp(desired, 0, (int)targetItem->children.size()); + desired = std::clamp(desired, 0, item_frames_count(targetItem)); auto insertPosResult = desired; auto insertedCount = (int)movedFrames.size(); - targetItem->children.insert(targetItem->children.begin() + insertPosResult, + 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())); @@ -2727,9 +2873,11 @@ namespace anm2ed::imgui std::set movedSelection{}; for (int offset = 0; offset < insertedCount; ++offset) - movedSelection.insert({drag.animationIndex, targetType, targetID, insertPosResult + offset}); + movedSelection.insert({drag.animationIndex, targetType, targetID, insertPosResult + offset, + targetGroupType, targetGroupId}); - document.reference = {drag.animationIndex, targetType, targetID, insertPosResult}; + 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(), @@ -2800,6 +2948,8 @@ namespace anm2ed::imgui { 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) { @@ -2815,10 +2965,12 @@ namespace anm2ed::imgui return; } - auto item = item_get(type, id); + 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; @@ -2868,9 +3020,12 @@ namespace anm2ed::imgui auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; auto rowMaxY = rowMinY + childSize.y; float selectionFrameTime{}; - for (auto [i, frame] : std::views::enumerate(item->children)) + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) { - auto frameReference = Reference{reference.animationIndex, type, id, (int)i}; + 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); @@ -2878,6 +3033,7 @@ namespace anm2ed::imgui if (is_frame_box_overlapping(frameContentMin, frameContentMax, boxMin, boxMax)) frameBoxSelection.insert(frameReference); if (type != TRIGGER) selectionFrameTime += frame.duration; + ++frameIndex; } } @@ -3019,12 +3175,15 @@ namespace anm2ed::imgui { auto mouseX = mousePos.x - cursorScreenPos.x; auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = (int)item->children.size(); + int dropIndex = item_frames_count(item); float dropFrameTime{}; float frameTime{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; - for (auto [i, frame] : std::views::enumerate(item->children)) + 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) @@ -3038,17 +3197,20 @@ namespace anm2ed::imgui auto midpoint = frameStart + ((float)frame.duration * 0.5f); if (targetTime < midpoint) { - dropIndex = (int)i; + dropIndex = frameIndex; dropFrameTime = frameStart; break; } frameTime = frameEnd; dropFrameTime = frameTime; + ++frameIndex; } frameMoveDropType = type; frameMoveDropItemID = id; + frameMoveDropGroupType = row.rootGroupType; + frameMoveDropGroupId = row.rootGroupId; frameMoveDropIndex = dropIndex; isFrameMoveDropTarget = true; @@ -3060,16 +3222,21 @@ namespace anm2ed::imgui } } - for (auto [i, frame] : std::views::enumerate(item->children)) + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) { - ImGui::PushID((int)i); + auto& frame = item->children[childIndex]; + if (frame.type != frameType) continue; + ImGui::PushID(childIndex); - auto frameReference = Reference{reference.animationIndex, type, id, (int)i}; + 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((int)i) && - reference.itemType == type && reference.itemID == id); + (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; @@ -3080,11 +3247,12 @@ namespace anm2ed::imgui { if (type != TRIGGER) frameTime += frame.duration; ImGui::PopID(); + ++frameIndex; continue; } auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); - if (frameFocusRequested && frameFocusIndex == (int)i && reference == frameReference) + if (frameFocusRequested && frameFocusIndex == frameIndex && reference == frameReference) frameFocusRequested = false; ImGui::SetCursorPos(buttonPos); @@ -3103,8 +3271,8 @@ namespace anm2ed::imgui ImGui::SetNextItemAllowOverlap(); ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); - ImGui::SetNextItemSelectionUserData((int)i); - bool isDifferentItem = reference.itemType != type || reference.itemID != id; + ImGui::SetNextItemSelectionUserData(frameIndex); + bool isDifferentItem = !is_same_item(reference, frameReference); if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) { if (type == LAYER) @@ -3172,7 +3340,7 @@ namespace anm2ed::imgui isDraggedFrameActive = true; draggedFrameReference = frameReference; draggedFrameType = type; - draggedFrameIndex = (int)i; + draggedFrameIndex = frameIndex; draggedFrameStart = hoveredTime; if (type != TRIGGER) draggedFrameStartDuration = frame.duration; draggedFrameStartDurations.clear(); @@ -3185,7 +3353,8 @@ namespace anm2ed::imgui if (selectedReferences.empty()) selectedReferences = {frameReference}; for (auto selectedReference : selectedReferences) { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID); + auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, + selectedReference.groupType, selectedReference.groupId); auto selectedFrame = selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; if (selectedFrame) @@ -3211,7 +3380,8 @@ namespace anm2ed::imgui int dragDuration = 0; for (auto selectedReference : selectedReferences) { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID); + 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; @@ -3222,7 +3392,9 @@ namespace anm2ed::imgui .type = type, .itemID = id, .animationIndex = reference.animationIndex, - .frameIndex = (int)i, + .groupType = row.rootGroupType, + .groupId = row.rootGroupId, + .frameIndex = frameIndex, .duration = dragDuration, .indices = {}, .references = {selectedReferences.begin(), selectedReferences.end()}, @@ -3273,6 +3445,7 @@ namespace anm2ed::imgui if (type != TRIGGER) frameTime += frame.duration; ImGui::PopID(); + ++frameIndex; } if (isFrameMovePreview) @@ -3297,12 +3470,13 @@ namespace anm2ed::imgui { std::set lockedSelection{}; for (int idx : frameSelectionLocked) - lockedSelection.insert({reference.animationIndex, type, id, idx}); + lockedSelection.insert(row_reference_make(idx)); document.frame_references_set(std::move(lockedSelection)); isFrameSelectionLocked = false; frameSelectionLocked.clear(); } - if (reference.itemType == type && reference.itemID == id) + 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; @@ -3324,7 +3498,18 @@ namespace anm2ed::imgui if (!isDraggedFrameSnapshot && isDraggedFrameChanged) { isDraggedFrameSnapshot = true; - snapshot_command_push(draggedFrameType == TRIGGER ? EDIT_TRIGGER_AT_FRAME : EDIT_FRAME_DURATION); + if (draggedFrameType == TRIGGER) + snapshot_command_push(EDIT_TRIGGER_AT_FRAME); + 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) @@ -3340,8 +3525,7 @@ namespace anm2ed::imgui auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; command_push([=](Manager&, Document& document) { - auto item = command_item_get(document, targetReference.animationIndex, - targetReference.itemType, targetReference.itemID); + auto item = command_item_reference_get(document, targetReference); auto frame = command_frame_get(document, targetReference); if (!item || !frame) return; @@ -3383,8 +3567,7 @@ namespace anm2ed::imgui auto targetType = draggedFrameType; command_push([=](Manager&, Document& document) { - auto item = command_item_get(document, targetReference.animationIndex, - targetReference.itemType, targetReference.itemID); + auto item = command_item_reference_get(document, targetReference); if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); document.anm2_change(Document::FRAMES); }); @@ -3741,7 +3924,9 @@ namespace anm2ed::imgui frames_child(); if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) { - if (isFrameMoveDropTarget) frames_move_to(frameMoveDropType, frameMoveDropItemID, frameMoveDropIndex); + if (isFrameMoveDropTarget) + frames_move_to(frameMoveDropType, frameMoveDropItemID, frameMoveDropGroupType, frameMoveDropGroupId, + frameMoveDropIndex); frame_move_drag_clear(); } items_child(); diff --git a/src/imgui/window/timeline.hpp b/src/imgui/window/timeline.hpp index ac0d211..2502044 100644 --- a/src/imgui/window/timeline.hpp +++ b/src/imgui/window/timeline.hpp @@ -21,6 +21,8 @@ namespace anm2ed::imgui int type{NONE}; int id{-1}; int index{-1}; + int groupType{NONE}; + int groupId{-1}; bool isGroup{}; auto operator<=>(const TimelineRowReference&) const = default; @@ -31,6 +33,8 @@ namespace anm2ed::imgui int type{NONE}; int itemID{-1}; int animationIndex{-1}; + int groupType{NONE}; + int groupId{-1}; int frameIndex{-1}; int duration{1}; std::vector indices{}; diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 5f6ddbf..ec12136 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -18,6 +18,7 @@ #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" #include "util/imgui/tooltip.hpp" +#include "util/imgui/tree.hpp" #include "vector.hpp" #include "working_directory.hpp" @@ -100,6 +101,13 @@ namespace anm2ed::imgui destination.children.push_back(item); } + void window_group_root_push(Element& group) + { + auto root = element_make(ElementType::ROOT_ANIMATION); + root.children.push_back(element_make(ElementType::FRAME)); + group.children.push_back(root); + } + Element window_track_container_shell_copy(const Element* source, ElementType containerType, ElementType trackType) { auto destination = element_make(containerType); @@ -120,6 +128,7 @@ namespace anm2ed::imgui group.name = sourceItem.name; group.isExpanded = sourceItem.isExpanded; group.isVisible = sourceItem.isVisible; + window_group_root_push(group); destination.children.push_back(group); for (const auto& child : sourceItem.children) @@ -130,14 +139,14 @@ namespace anm2ed::imgui void window_edit(Window& window, Document& document, const std::string& message, auto behavior) { - document.snapshot(message); + document.anm2_snapshot(message); behavior(); document.anm2_change(window.changeType); } void window_edit(Document& document, Document::ChangeType changeType, const std::string& message, auto behavior) { - document.snapshot(message); + document.anm2_snapshot(message); behavior(); document.anm2_change(changeType); } @@ -160,7 +169,7 @@ namespace anm2ed::imgui element = element_child_id_get(*container, elementType, key); if (!element || element->name == name) return; - document.snapshot(localize.get(renameEdit)); + document.anm2_snapshot(localize.get(renameEdit)); element->name = name; if (renameFinish) renameFinish(document, *element, key, count); document.anm2_change(changeType); @@ -214,7 +223,7 @@ namespace anm2ed::imgui if (pasted.deserialize(window.elementType, clipboard.get(), true, &errorString, document.directory_get())) { - document.snapshot(localize.get(window.pasteEdit)); + document.anm2_snapshot(localize.get(window.pasteEdit)); document.anm2 = std::move(pasted); container = window_container_get(window, document.anm2); auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; @@ -336,7 +345,199 @@ namespace anm2ed::imgui return count; } - int window_animations_merge(Document& document, const AnimationMergeOptions& options) + int window_animation_child_index_get(const Element& animations, int animationIndex) + { + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + if (animations.children[i].type != ElementType::ANIMATION) continue; + if (current == animationIndex) return i; + ++current; + } + return -1; + } + + int window_animation_child_insert_index_get(const Element& animations, int animationIndex) + { + if (animationIndex <= 0) + { + for (int i = 0; i < (int)animations.children.size(); ++i) + if (animations.children[i].type == ElementType::ANIMATION) return i; + return (int)animations.children.size(); + } + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + if (animations.children[i].type != ElementType::ANIMATION) continue; + if (current == animationIndex) return i; + ++current; + } + return (int)animations.children.size(); + } + + int window_animation_index_from_child_index_get(const Element& animations, int childIndex) + { + int current{}; + for (int i = 0; i < (int)animations.children.size(); ++i) + { + if (animations.children[i].type != ElementType::ANIMATION) continue; + if (i == childIndex) return current; + ++current; + } + return -1; + } + + std::set window_animation_group_ids_get(const Element& animations) + { + std::set result{}; + for (const auto& item : animations.children) + if (item.type == ElementType::GROUP) result.insert(item.id); + return result; + } + + bool is_window_animation_grouped(const std::set& groupIds, const Element& animation) + { + return animation.groupId != -1 && groupIds.contains(animation.groupId); + } + + std::vector window_animation_groupable_indices_get(Document& document) + { + std::vector result{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations || document.animation.selection.empty()) return result; + + auto groupIds = window_animation_group_ids_get(*animations); + int index{}; + for (const auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (document.animation.selection.contains(index)) + { + if (is_window_animation_grouped(groupIds, animation)) return {}; + result.push_back(index); + } + ++index; + } + if (result.size() != document.animation.selection.size()) return {}; + return result; + } + + int window_animation_group_key_get(int groupId) { return -groupId - 2; } + + bool is_window_animation_group_key(int key) { return key <= -2; } + + int window_animation_group_id_from_key_get(int key) { return -key - 2; } + + bool is_window_animation_group_selected(const Window& window) + { + return window.elementType == ElementType::ANIMATION && !window.selection.empty(); + } + + std::set window_animation_group_indices_get(const Element& animations, int groupId) + { + std::set result{}; + int animationIndex{}; + for (const auto& animation : animations.children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (animation.groupId == groupId) result.insert(animationIndex); + ++animationIndex; + } + return result; + } + + std::set window_animation_selected_indices_get(Document& document, const Window& window) + { + std::set result(document.animation.selection.begin(), document.animation.selection.end()); + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations || window.elementType != ElementType::ANIMATION) return result; + + for (auto groupId : window.selection) + { + auto indices = window_animation_group_indices_get(*animations, groupId); + result.insert(indices.begin(), indices.end()); + } + return result; + } + + std::set window_animation_merge_indices_get(Document& document, const std::set& keys, int reference) + { + std::set result{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + + for (auto key : keys) + { + if (is_window_animation_group_key(key)) + { + if (!animations) continue; + auto indices = window_animation_group_indices_get(*animations, window_animation_group_id_from_key_get(key)); + result.insert(indices.begin(), indices.end()); + } + else + result.insert(key); + } + + result.erase(reference); + return result; + } + + void window_animation_groups_remove(Document& document, const std::set& groupIds) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations || groupIds.empty()) return; + + for (auto& item : animations->children) + if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; + std::erase_if(animations->children, [&](const Element& item) + { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); + } + + std::string window_animation_clipboard_text_get(Document& document, const Window& window) + { + std::string clipboardText{}; + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + if (!animations) return clipboardText; + + int animationIndex{}; + for (const auto& item : animations->children) + { + if (item.type == ElementType::GROUP) + { + if (window.selection.contains(item.id)) clipboardText += element_to_string(item); + } + else if (item.type == ElementType::ANIMATION) + { + if (document.animation.selection.contains(animationIndex) || window.selection.contains(item.groupId)) + clipboardText += element_to_string(item); + ++animationIndex; + } + } + + return clipboardText; + } + + bool is_window_item_selected(Window& window, Document& document) + { + return !window.storage_get(document).selection.empty() || is_window_animation_group_selected(window); + } + + bool is_window_item_renameable(Window& window, Document& document) + { + auto& selection = window.storage_get(document).selection; + return selection.size() == 1 || + (window.elementType == ElementType::ANIMATION && selection.empty() && window.selection.size() == 1); + } + + bool is_window_merge_available(Window& window, Document& document) + { + auto& selection = window.storage_get(document).selection; + if (window.elementType != ElementType::ANIMATION) return !selection.empty(); + return !window_animation_selected_indices_get(document, window).empty(); + } + + int window_animations_merge(Document& document, const AnimationMergeOptions& options, + const std::set* quickSelection = nullptr, + const std::set* quickGroupSelection = nullptr) { auto& anm2 = document.anm2; auto& selection = document.animation.selection; @@ -344,17 +545,21 @@ namespace anm2ed::imgui auto& overlayIndex = document.overlayIndex; int merged{-1}; - document.snapshot(localize.get(EDIT_MERGE_ANIMATIONS)); + document.anm2_snapshot(localize.get(EDIT_MERGE_ANIMATIONS)); if (options.selection.empty()) { - if (selection.contains(overlayIndex)) overlayIndex = -1; + auto selected = quickSelection ? *quickSelection : std::set(selection.begin(), selection.end()); + auto isQuickGroupMerge = quickGroupSelection && !quickGroupSelection->empty(); + if (selected.contains(overlayIndex)) overlayIndex = -1; - if (selection.size() > 1) - merged = anm2.animations_merge(*selection.begin(), selection); - else if (selection.size() == 1 && *selection.begin() != window_animation_count_get(anm2) - 1) + if (selected.size() > 1) + merged = anm2.animations_merge(*selected.begin(), selected); + else if (selected.size() == 1 && isQuickGroupMerge) + merged = *selected.begin(); + else if (selected.size() == 1 && *selected.begin() != window_animation_count_get(anm2) - 1) { - auto start = *selection.begin(); - auto next = *selection.begin() + 1; + auto start = *selected.begin(); + auto next = *selected.begin() + 1; std::set animationSet{}; animationSet.insert(start); animationSet.insert(next); @@ -362,11 +567,14 @@ namespace anm2ed::imgui } else return -1; + + if (isQuickGroupMerge) window_animation_groups_remove(document, *quickGroupSelection); } else { - if (options.selection.contains(overlayIndex)) overlayIndex = -1; - auto mergeSelection = options.selection; + auto mergeSelection = window_animation_merge_indices_get(document, options.selection, options.reference); + if (mergeSelection.empty()) return -1; + if (mergeSelection.contains(overlayIndex)) overlayIndex = -1; merged = anm2.animations_merge(options.reference, mergeSelection, options.type, options.isDeleteAnimationsAfter); } @@ -402,7 +610,7 @@ namespace anm2ed::imgui } }; - document.snapshot(localize.get(EDIT_MERGE_SPRITESHEETS)); + document.anm2_textures_snapshot(localize.get(EDIT_MERGE_SPRITESHEETS)); behavior(); document.change(Document::ALL); } @@ -431,7 +639,7 @@ namespace anm2ed::imgui } }; - document.snapshot(localize.get(EDIT_PACK_SPRITESHEET)); + document.anm2_textures_snapshot(localize.get(EDIT_PACK_SPRITESHEET)); behavior(); document.change(Document::SPRITESHEETS); } @@ -464,6 +672,87 @@ namespace anm2ed::imgui } } + void window_overlays_save(Document& document, const std::set& ids) + { + if (ids.empty()) return; + + for (auto& id : ids) + { + auto overlay = document.overlay_get(id); + auto texture = document.overlay_texture_get(id); + if (!overlay || !texture) continue; + auto pathString = path::to_utf8(overlay->path); + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(overlay->path.parent_path()); + if (texture->write_png(overlay->path)) + { + document.overlay_hash_set_saved(id); + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY), std::make_format_args(id, pathString))); + logger.info( + std::vformat(localize.get(TOAST_SAVE_OVERLAY, anm2ed::ENGLISH), std::make_format_args(id, pathString))); + } + else + { + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED), std::make_format_args(id, pathString))); + logger.error(std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } + } + } + + int window_overlay_next_id_get(const Document& document) + { + int nextId{}; + if (auto spritesheets = document.anm2.element_get(ElementType::SPRITESHEETS)) + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + for (auto& overlay : spritesheet.children) + if (overlay.type == ElementType::OVERLAY) nextId = std::max(nextId, overlay.id + 1); + } + return nextId; + } + + void window_overlays_context_actions_add(Window& window, Manager& manager, Settings& settings, Document& document, + Clipboard& clipboard, Actions& actions) + { + auto& selection = document.overlay.selection; + actions_undo_redo_add(actions, manager, document); + actions.separator(); + actions.add(ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); + actions.add(ACTION_SET_FILE_PATH, [&]() { return selection.size() == 1 && (bool)window.path_set; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.path_set); }); + actions.add(ACTION_ADD, [&]() { return (bool)window.add; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); + actions.add(ACTION_REMOVE, [&]() { return !selection.empty() && (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, + TOOLTIP_REMOVE_OVERLAYS); + actions.add(ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }, + TOOLTIP_RELOAD_OVERLAYS); + actions.add(ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }, + TOOLTIP_REPLACE_OVERLAY); + actions.add(ACTION_SAVE, [&]() { return !selection.empty(); }, + [&]() + { + if (settings.fileIsWarnOverwrite) + { + window.selection2 = selection; + window.popup.open(); + } + else if (window.save) + window_command_run(window, manager, settings, document, clipboard, window.save); + }, + TOOLTIP_SAVE_OVERLAYS); + actions.separator(); + actions.add(ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); + actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); + } + int window_footer_button_count_get(const Window& window) { int count{}; @@ -487,21 +776,31 @@ namespace anm2ed::imgui [&]() { window_add(window, manager, settings, document, clipboard); }, window.addTooltip); if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add(ACTION_DUPLICATE, [&]() { return !selection.empty(); }, + actions.add(ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }, window.duplicateTooltip); if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add(ACTION_MERGE, [&]() { return selection.size() == 1; }, + actions.add(ACTION_MERGE, [&]() { - window_command_run(window, manager, settings, document, clipboard, - window.merge_open ? window.merge_open : window.merge); + if (window.elementType == ElementType::ANIMATION) + { + if (is_window_animation_group_selected(window)) return is_window_merge_available(window, document); + return selection.size() == 1; + } + return selection.size() == 1; + }, + [&]() + { + auto command = window.merge_open && !is_window_animation_group_selected(window) ? window.merge_open + : window.merge; + window_command_run(window, manager, settings, document, clipboard, command); }, window.mergeTooltip); if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add(ACTION_REMOVE, [&]() { return !selection.empty(); }, + actions.add(ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, window.removeTooltip); @@ -531,8 +830,14 @@ namespace anm2ed::imgui } if (window_flag_has(window.flags, WINDOW_RENAME)) - actions.add(ACTION_RENAME, [&]() { return selection.size() == 1; }, - [&]() { window.renameQueued = *selection.begin(); }); + actions.add(ACTION_RENAME, [&]() { return is_window_item_renameable(window, document); }, + [&]() + { + if (selection.size() == 1) + window.renameQueued = *selection.begin(); + else if (window.elementType == ElementType::ANIMATION && window.selection.size() == 1) + window.renameQueued = window_animation_group_key_get(*window.selection.begin()); + }); if (window_flag_has(window.flags, WINDOW_PROPERTIES)) actions.add(ACTION_PROPERTIES, [&]() { return selection.size() == 1; }, [&]() { window_properties(window, manager, *selection.begin()); }); @@ -540,13 +845,22 @@ namespace anm2ed::imgui actions.add(ACTION_ADD, []() { return true; }, [&]() { window_add(window, manager, settings, document, clipboard); }); if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add(ACTION_DUPLICATE, [&]() { return !selection.empty(); }, + actions.add(ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }); if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add(ACTION_MERGE, [&]() { return !selection.empty(); }, + actions.add(ACTION_MERGE, [&]() { return is_window_merge_available(window, document); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge); }); + if (window_flag_has(window.flags, WINDOW_GROUP)) + actions.add(ACTION_GROUP, + [&]() + { + if (window.elementType == ElementType::ANIMATION) + return !window_animation_groupable_indices_get(document).empty(); + return !selection.empty(); + }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.group); }); if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add(ACTION_REMOVE, [&]() { return !selection.empty(); }, + actions.add(ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) actions.add(ACTION_REMOVE_UNUSED, []() { return true; }, @@ -558,10 +872,10 @@ namespace anm2ed::imgui actions.separator(); if (window_flag_has(window.flags, WINDOW_CUT)) - actions.add(ACTION_CUT, [&]() { return !selection.empty(); }, + actions.add(ACTION_CUT, [&]() { return is_window_item_selected(window, document); }, [&]() { window_command_run(window, manager, settings, document, clipboard, window.cut); }); if (window_flag_has(window.flags, WINDOW_COPY)) - actions.add(ACTION_COPY, [&]() { return !selection.empty(); }, + actions.add(ACTION_COPY, [&]() { return is_window_item_selected(window, document); }, [&]() { window_copy(window, manager, settings, document, clipboard); }); if (window_flag_has(window.flags, WINDOW_PASTE)) actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, @@ -655,10 +969,11 @@ namespace anm2ed::imgui auto isRenaming = window.renameId == key; auto& name = isRenaming ? window.renameText : element.name; + bool isActivated{}; if (selectable_input_text(label, window_rename_format_get(window, manager, key), name, isSelected, ImGuiSelectableFlags_None, window.renameState)) { - if (window.row_select) window.row_select(window, document, key); + isActivated = true; if (window.renameState == RENAME_BEGIN) { window.renameId = key; @@ -671,11 +986,22 @@ namespace anm2ed::imgui window.renameText.clear(); } } + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) + { + storage.reference = key; + if (window.row_select) window.row_select(window, document, key); + } } else { - if (ImGui::Selectable(label.c_str(), isSelected)) + auto isActivated = ImGui::Selectable(label.c_str(), isSelected); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) + { + storage.reference = key; if (window.row_select) window.row_select(window, document, key); + } } if (isFontPushed) ImGui::PopFont(); @@ -801,7 +1127,7 @@ namespace anm2ed::imgui window.renameEdit = SNAPSHOT_RENAME_ANIMATION; window.pasteEdit = EDIT_PASTE_ANIMATIONS; window.deserializeFailedToast = TOAST_DESERIALIZE_ANIMATIONS_FAILED; - window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_REMOVE | WINDOW_DEFAULT | WINDOW_CUT | + window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_GROUP | WINDOW_REMOVE | WINDOW_DEFAULT | WINDOW_CUT | WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; window.popup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); window.storage_get = [](Document& document) -> Storage& { return document.animation; }; @@ -883,15 +1209,39 @@ namespace anm2ed::imgui if (payload->IsDelivery()) { auto targetIndex = index + (isDropAfter ? 1 : 0); - manager.command_push({manager.selected, [&window, indices, targetIndex](Manager&, Document& document) mutable + auto targetGroupId = -1; + if (auto targetAnimation = anm2.element_get(ElementType::ANIMATION, index)) + targetGroupId = targetAnimation->groupId; + manager.command_push({manager.selected, [&window, indices, targetIndex, targetGroupId](Manager&, Document& document) mutable { auto move = [&]() { auto items = window_container_get(window, document.anm2); - if (items) - document.animation.selection = - anm2ed::util::vector::move_indices_to_position(items->children, indices, - targetIndex); + if (!items) return; + + auto groupIds = window_animation_group_ids_get(*items); + auto groupId = groupIds.contains(targetGroupId) ? targetGroupId : -1; + std::vector childIndices{}; + childIndices.reserve(indices.size()); + for (auto animationIndex : indices) + { + auto childIndex = window_animation_child_index_get(*items, animationIndex); + if (childIndex == -1) continue; + if (auto animation = vector::find(items->children, childIndex)) + animation->groupId = groupId; + childIndices.push_back(childIndex); + } + + auto targetChildIndex = window_animation_child_insert_index_get(*items, targetIndex); + auto movedChildIndices = + anm2ed::util::vector::move_indices_to_position(items->children, childIndices, + targetChildIndex); + document.animation.selection.clear(); + for (auto childIndex : movedChildIndices) + { + auto animationIndex = window_animation_index_from_child_index_get(*items, childIndex); + if (animationIndex != -1) document.animation.selection.insert(animationIndex); + } }; window_edit(window, document, localize.get(EDIT_MOVE_ANIMATIONS), move); }}); @@ -904,6 +1254,297 @@ namespace anm2ed::imgui return false; }; + window.rows_update = [](Window& window, Manager& manager, Settings&, Resources& resources, Clipboard&, + Document& document, ImVec2) + { + auto container = window_container_get(window, document.anm2); + auto& storage = window.storage_get(document); + auto& selection = storage.selection; + auto& groupSelection = window.selection; + auto count = window_element_count_get(window, container); + auto groupIds = container ? window_animation_group_ids_get(*container) : std::set{}; + std::erase_if(groupSelection, [&](int groupId) { return !groupIds.contains(groupId); }); + std::vector visibleIds{}; + int visibleIndex{}; + + auto visible_group_children_push = [&](int groupId) + { + int animationIndex{}; + for (auto& child : container->children) + { + if (child.type != ElementType::ANIMATION) continue; + if (child.groupId == groupId) visibleIds.push_back(animationIndex); + ++animationIndex; + } + }; + + if (container) + for (auto& child : container->children) + { + if (child.type == ElementType::GROUP) + { + if (child.isExpanded) visible_group_children_push(child.id); + } + else if (child.type == ElementType::ANIMATION) + { + if (!is_window_animation_grouped(groupIds, child)) visibleIds.push_back(visibleIndex); + ++visibleIndex; + } + } + + int scrollTargetId = -1; + int arrowSelectionId = -1; + + selection.start(count); + if (container && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + { + selection.clear(); + for (int i = 0; i < count; ++i) + selection.insert(i); + groupSelection = groupIds; + } + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && + (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) + { + auto nextId = window_arrow_selection_get(visibleIds, storage.reference, selection); + if (nextId != -1) + { + arrowSelectionId = nextId; + scrollTargetId = nextId; + } + } + + auto animation_row_draw = [&](Element& element, int key) + { + auto isSelected = selection.contains(key) || arrowSelectionId == key; + auto font = window.row_font_get ? window.row_font_get(document, element, key) : resource::font::REGULAR; + auto isFontPushed = font != resource::font::REGULAR; + + ImGui::PushID(key); + ImGui::SetNextItemSelectionUserData(key); + auto label = window.row_label_get ? window.row_label_get(document, element) : element.name; + if (isFontPushed) ImGui::PushFont(resources.fonts[font].get(), resource::font::SIZE); + if (scrollTargetId == key) ImGui::SetKeyboardFocusHere(); + + if (window_flag_has(window.flags, WINDOW_RENAME)) + { + if (window.newElementId == key || window.renameQueued == key) + { + window.renameState = RENAME_FORCE_EDIT; + window.renameQueued = -1; + } + + auto isRenaming = window.renameId == key; + auto& name = isRenaming ? window.renameText : element.name; + bool isActivated{}; + if (selectable_input_text(label, window_rename_format_get(window, manager, key), name, isSelected, + ImGuiSelectableFlags_None, window.renameState)) + { + isActivated = true; + if (window.renameState == RENAME_BEGIN) + { + window.renameId = key; + window.renameText = element.name; + } + else if (window.renameState == RENAME_FINISHED) + { + if (isRenaming) window_rename_finish(window, manager, key, count, window.renameText); + window.renameId = -1; + window.renameText.clear(); + } + } + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) + { + auto& io = ImGui::GetIO(); + if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); + storage.reference = key; + if (window.row_select) window.row_select(window, document, key); + } + } + else + { + auto isActivated = ImGui::Selectable(label.c_str(), isSelected); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) + { + auto& io = ImGui::GetIO(); + if (!io.KeyCtrl && !io.KeyShift) groupSelection.clear(); + storage.reference = key; + if (window.row_select) window.row_select(window, document, key); + } + } + + if (isFontPushed) ImGui::PopFont(); + + if (window.newElementId == key || window.scrollQueued == key || scrollTargetId == key) + { + ImGui::SetScrollHereY(0.5f); + if (window.newElementId == key) window.newElementId = -1; + if (window.scrollQueued == key) window.scrollQueued = -1; + } + + bool isBreak{}; + if (window.row_drag_drop_update && window.row_drag_drop_update(window, manager, document, element, key)) + isBreak = true; + + if (window.tooltip_draw) + { + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); + if (ImGui::BeginItemTooltip()) + { + window.tooltip_draw(document, resources, element); + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(2); + } + + ImGui::PopID(); + return isBreak; + }; + + auto group_reference_clear = [&]() + { + storage.reference = -1; + document.reference = {}; + document.frames.clear(); + }; + + auto group_selection_apply = [&](int groupId) + { + auto& io = ImGui::GetIO(); + auto isSelected = groupSelection.contains(groupId); + if (!io.KeyCtrl) + { + selection.clear(); + groupSelection.clear(); + } + + if (io.KeyCtrl && isSelected) + { + groupSelection.erase(groupId); + if (selection.empty() && groupSelection.empty()) group_reference_clear(); + return; + } + + groupSelection.insert(groupId); + if (!io.KeyCtrl || selection.empty()) group_reference_clear(); + }; + + bool isRowsDone{}; + if (container) + { + int animationIndex{}; + for (auto& item : container->children) + { + if (item.type == ElementType::GROUP) + { + ImGui::PushID("Animation Group"); + ImGui::PushID(item.id); + auto label = item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name; + auto isGroupSelected = groupSelection.contains(item.id); + auto renameKey = window_animation_group_key_get(item.id); + auto isRenaming = window.renameId == renameKey; + auto& name = isRenaming ? window.renameText : item.name; + if (window.renameQueued == renameKey) + { + window.renameState = RENAME_FORCE_EDIT; + window.renameQueued = -1; + } + ImGui::SetNextItemOpen(item.isExpanded, ImGuiCond_Always); + auto treeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; + auto tree = + tree_node_input_text(label, std::format("###Document #{} Animation Group #{}", manager.selected, + item.id), + name, isGroupSelected, treeFlags, window.renameState); + auto isGroupOpen = tree.isOpen; + auto isGroupClicked = tree.isClicked; + if (tree.isRenameStarted) + { + window.renameId = renameKey; + window.renameText = item.name; + } + else if (tree.isRenameFinished) + { + if (isRenaming && item.name != window.renameText) + { + auto targetGroupId = item.id; + auto targetName = window.renameText; + manager.command_push({manager.selected, [targetGroupId, targetName](Manager&, Document& document) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto group = animations ? element_child_id_get(*animations, ElementType::GROUP, + targetGroupId) + : nullptr; + if (!group || group->name == targetName) return; + document.anm2_snapshot(localize.get(EDIT_RENAME_GROUP)); + group->name = targetName; + document.anm2_change(Document::ANIMATIONS); + }}); + } + window.renameId = -1; + window.renameText.clear(); + } + if (isGroupOpen != item.isExpanded) + { + auto targetGroupId = item.id; + manager.command_push({manager.selected, [targetGroupId, isGroupOpen](Manager&, Document& document) + { + auto animations = document.anm2.element_get(ElementType::ANIMATIONS); + auto group = animations ? element_child_id_get(*animations, ElementType::GROUP, + targetGroupId) + : nullptr; + if (!group || group->isExpanded == isGroupOpen) return; + document.anm2_snapshot(localize.get(EDIT_TOGGLE_GROUP_EXPANDED)); + group->isExpanded = isGroupOpen; + document.anm2_change(Document::ANIMATIONS); + }}); + } + if (isGroupClicked) group_selection_apply(item.id); + + if (isGroupOpen) + { + int groupAnimationIndex{}; + for (auto& animation : container->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (animation.groupId == item.id) + if (animation_row_draw(animation, groupAnimationIndex)) + { + isRowsDone = true; + break; + } + ++groupAnimationIndex; + } + ImGui::TreePop(); + } + ImGui::PopID(); + ImGui::PopID(); + if (isRowsDone) break; + } + else if (item.type == ElementType::ANIMATION) + { + if (!is_window_animation_grouped(groupIds, item)) + if (animation_row_draw(item, animationIndex)) + { + isRowsDone = true; + break; + } + ++animationIndex; + } + } + } + + selection.finish(); + if (arrowSelectionId != -1) + { + groupSelection.clear(); + selection = {arrowSelectionId}; + storage.reference = arrowSelectionId; + if (window.row_select) window.row_select(window, document, arrowSelectionId); + } + }; window.add = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& anm2 = document.anm2; @@ -917,6 +1558,10 @@ namespace anm2ed::imgui { auto items = animations(); if (!items) return; + auto groupIds = window_animation_group_ids_get(*items); + auto targetGroupId = + window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() + : -1; auto animation = element_make(ElementType::ANIMATION); animation.name = localize.get(TEXT_NEW_ANIMATION); @@ -946,10 +1591,23 @@ namespace anm2ed::imgui auto count = animation_count(); auto index = count; if (!selection.empty()) index = std::min(*selection.rbegin() + 1, count); + else if (targetGroupId != -1) + { + auto groupIndices = window_animation_group_indices_get(*items, targetGroupId); + if (!groupIndices.empty()) index = std::min(*groupIndices.rbegin() + 1, count); + } + if (!selection.empty()) + if (auto selectedAnimation = anm2.element_get(ElementType::ANIMATION, *selection.rbegin())) + { + if (groupIds.contains(selectedAnimation->groupId)) animation.groupId = selectedAnimation->groupId; + } + if (selection.empty() && targetGroupId != -1) animation.groupId = targetGroupId; if (count == 0) items->defaultAnimation = animation.name; - items->children.insert(items->children.begin() + index, animation); + auto childIndex = window_animation_child_insert_index_get(*items, index); + items->children.insert(items->children.begin() + childIndex, animation); selection = {index}; + window.selection.clear(); reference = {index}; window.newElementId = index; window.scrollQueued = index; @@ -962,23 +1620,34 @@ namespace anm2ed::imgui auto& selection = document.animation.selection; auto& reference = document.reference; auto& overlayIndex = document.overlayIndex; + auto groupSelection = window.selection; auto behavior = [&]() { auto items = document.anm2.element_get(ElementType::ANIMATIONS); - if (!items || selection.empty()) return; + if (!items || (selection.empty() && groupSelection.empty())) return; + if (!groupSelection.empty()) + { + for (auto& item : items->children) + if (item.type == ElementType::ANIMATION && groupSelection.contains(item.groupId)) item.groupId = -1; + std::erase_if(items->children, [&](const Element& item) + { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); + } for (auto it = selection.rbegin(); it != selection.rend(); ++it) { auto i = *it; - if (i < 0 || i >= (int)items->children.size()) continue; + auto childIndex = window_animation_child_index_get(*items, i); + if (childIndex == -1) continue; if (overlayIndex == i) overlayIndex = -1; if (reference.animationIndex == i) reference.animationIndex = -1; - items->children.erase(items->children.begin() + i); + items->children.erase(items->children.begin() + childIndex); } selection.clear(); + window.selection.clear(); }; - window_edit(window, document, localize.get(EDIT_REMOVE_ANIMATIONS), behavior); + auto edit = groupSelection.empty() ? EDIT_REMOVE_ANIMATIONS : EDIT_REMOVE_GROUP; + window_edit(window, document, localize.get(edit), behavior); }; window.duplicate = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { @@ -987,16 +1656,38 @@ namespace anm2ed::imgui auto behavior = [&]() { auto items = document.anm2.element_get(ElementType::ANIMATIONS); - if (!items || selection.empty()) return; - auto duplicated = selection; - auto end = *duplicated.rbegin(); - for (auto& id : duplicated) + auto clipboardText = window_animation_clipboard_text_get(document, window); + if (!items || clipboardText.empty()) return; + + auto selectedIndices = window_animation_selected_indices_get(document, window); + auto count = window_element_count_get(window, items); + auto start = selectedIndices.empty() ? count : std::min(*selectedIndices.rbegin() + 1, count); + std::set indices{}; + std::set groupIds{}; + std::string errorString{}; + if (!document.anm2.animations_deserialize(clipboardText, start, indices, &errorString, &groupIds)) return; + + if (!groupIds.empty()) { - if (id < 0 || id >= (int)items->children.size()) continue; - items->children.insert(items->children.begin() + end, items->children[id]); - selection.insert(++end); - selection.erase(id); + selection.clear(); + window.selection = groupIds; + document.reference = {}; + window.newElementId = -1; } + else + { + selection = indices; + window.selection.clear(); + } + if (!indices.empty() && groupIds.empty()) + { + auto index = *indices.rbegin(); + document.reference = {index}; + window.newElementId = indices.size() == 1 && groupIds.empty() ? index : -1; + window.scrollQueued = index; + } + else if (!indices.empty()) + window.scrollQueued = *indices.rbegin(); }; window_edit(window, document, localize.get(EDIT_DUPLICATE_ANIMATIONS), behavior); @@ -1005,11 +1696,20 @@ namespace anm2ed::imgui { auto& mergeSelection = document.merge.selection; auto& mergeReference = document.merge.reference; + auto quickSelection = mergeSelection.empty() ? window_animation_selected_indices_get(document, window) + : std::set{}; + auto quickGroupSelection = mergeSelection.empty() ? window.selection : std::set{}; auto merged = window_animations_merge(document, {.selection = mergeSelection, .reference = mergeReference, .type = (merge::Type)settings.mergeType, - .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}); - if (merged != -1) window.scrollQueued = merged; + .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}, + mergeSelection.empty() ? &quickSelection : nullptr, + mergeSelection.empty() ? &quickGroupSelection : nullptr); + if (merged != -1) + { + window.scrollQueued = merged; + window.selection.clear(); + } mergeSelection.clear(); }; window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) @@ -1020,6 +1720,46 @@ namespace anm2ed::imgui document.merge.selection.clear(); document.merge.reference = *selection.begin(); }; + window.group = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto targetIndices = window_animation_groupable_indices_get(document); + if (targetIndices.empty()) return; + + auto behavior = [&]() + { + auto items = document.anm2.element_get(ElementType::ANIMATIONS); + if (!items) return; + + std::set targetSet(targetIndices.begin(), targetIndices.end()); + auto group = element_make(ElementType::GROUP); + group.id = element_child_next_id_get(*items, ElementType::GROUP); + group.name = localize.get(TEXT_NEW_GROUP); + group.isExpanded = true; + int insertIndex = (int)items->children.size(); + int animationIndex{}; + + for (int i = 0; i < (int)items->children.size(); ++i) + { + auto& item = items->children[i]; + if (item.type != ElementType::ANIMATION) continue; + if (targetSet.contains(animationIndex)) + { + insertIndex = std::min(insertIndex, i); + item.groupId = group.id; + } + ++animationIndex; + } + + if (insertIndex == (int)items->children.size()) return; + items->children.insert(items->children.begin() + insertIndex, group); + document.animation.selection = targetSet; + window.selection = {group.id}; + document.reference = {*targetSet.begin()}; + window.scrollQueued = *targetSet.begin(); + }; + + window_edit(window, document, localize.get(EDIT_GROUP_ITEMS), behavior); + }; window.default_set = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& selection = document.animation.selection; @@ -1034,33 +1774,35 @@ namespace anm2ed::imgui window_edit(window, document, localize.get(EDIT_DEFAULT_ANIMATION), behavior); }; - window.copy = [](Window&, Manager&, Settings&, Document& document, Clipboard& clipboard) + window.copy = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) { - auto& selection = document.animation.selection; - if (selection.empty()) return; - - std::string clipboardText{}; - for (auto& i : selection) - if (auto animation = document.anm2.element_get(ElementType::ANIMATION, i)) - clipboardText += element_to_string(*animation); - clipboard.set(clipboardText); + auto clipboardText = window_animation_clipboard_text_get(document, window); + if (!clipboardText.empty()) clipboard.set(clipboardText); }; window.cut = [](Window& window, Manager& manager, Settings& settings, Document& document, Clipboard& clipboard) { if (window.copy) window.copy(window, manager, settings, document, clipboard); auto& selection = document.animation.selection; + auto groupSelection = window.selection; + auto selectedIndices = window_animation_selected_indices_get(document, window); auto behavior = [&]() { auto items = document.anm2.element_get(ElementType::ANIMATIONS); if (!items) return; - for (auto it = selection.rbegin(); it != selection.rend(); ++it) + for (auto it = selectedIndices.rbegin(); it != selectedIndices.rend(); ++it) { auto i = *it; - if (i < 0 || i >= (int)items->children.size()) continue; - items->children.erase(items->children.begin() + i); + auto childIndex = window_animation_child_index_get(*items, i); + if (childIndex == -1) continue; + if (document.overlayIndex == i) document.overlayIndex = -1; + if (document.reference.animationIndex == i) document.reference.animationIndex = -1; + items->children.erase(items->children.begin() + childIndex); } + std::erase_if(items->children, [&](const Element& item) + { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); selection.clear(); + window.selection.clear(); }; window_edit(window, document, localize.get(EDIT_CUT_ANIMATIONS), behavior); @@ -1079,18 +1821,43 @@ namespace anm2ed::imgui { auto clipboardText = clipboard.get(); auto start = selection.empty() ? animation_count() : *selection.rbegin() + 1; - std::set indices{}; - std::string errorString{}; - if (anm2.animations_deserialize(clipboardText, start, indices, &errorString)) + auto items = anm2.element_get(ElementType::ANIMATIONS); + auto groupIdsBefore = items ? window_animation_group_ids_get(*items) : std::set{}; + auto targetGroupId = + selection.empty() && window.selection.size() == 1 && groupIdsBefore.contains(*window.selection.begin()) + ? *window.selection.begin() + : -1; + if (selection.empty() && targetGroupId != -1) { - if (!indices.empty()) + auto groupIndices = window_animation_group_indices_get(*items, targetGroupId); + if (!groupIndices.empty()) start = std::min(*groupIndices.rbegin() + 1, animation_count()); + } + std::set indices{}; + std::set groupIds{}; + std::string errorString{}; + if (anm2.animations_deserialize(clipboardText, start, indices, &errorString, &groupIds)) + { + if (targetGroupId != -1 && groupIds.empty()) + for (auto index : indices) + if (auto animation = anm2.element_get(ElementType::ANIMATION, index)) animation->groupId = targetGroupId; + + if (!groupIds.empty()) + { + selection.clear(); + window.selection = groupIds; + reference = {}; + window.newElementId = -1; + } + else if (!indices.empty()) { auto index = *indices.rbegin(); selection = {index}; + window.selection.clear(); reference = {index}; window.newElementId = indices.size() == 1 ? index : -1; window.scrollQueued = index; } + if (!indices.empty()) window.scrollQueued = *indices.rbegin(); } else { @@ -1112,7 +1879,6 @@ namespace anm2ed::imgui [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard&, Document& document) { auto animations = [&]() { return document.anm2.element_get(ElementType::ANIMATIONS); }; - auto animation_count = [&]() { return window_element_count_get(window, animations()); }; auto& mergeSelection = document.merge.selection; auto& mergeReference = document.merge.reference; @@ -1128,6 +1894,51 @@ namespace anm2ed::imgui auto& type = settings.mergeType; auto& isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter; + struct AnimationMergeCandidate + { + int key{}; + std::string label{}; + }; + std::vector candidates{}; + auto items = animations(); + auto groupIds = items ? window_animation_group_ids_get(*items) : std::set{}; + + if (items) + { + auto candidate_animation_push = [&](const Element& animation, int animationIndex, bool isGrouped) + { + if (animationIndex == mergeReference) return; + auto label = isGrouped ? std::format(" {}", animation.name) : animation.name; + candidates.push_back({.key = animationIndex, .label = label}); + }; + + int animationIndex{}; + for (const auto& item : items->children) + { + if (item.type == ElementType::GROUP) + { + auto groupIndices = window_animation_group_indices_get(*items, item.id); + groupIndices.erase(mergeReference); + if (!groupIndices.empty()) + { + auto label = item.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : item.name; + candidates.push_back({.key = window_animation_group_key_get(item.id), .label = label}); + int groupAnimationIndex{}; + for (const auto& animation : items->children) + { + if (animation.type != ElementType::ANIMATION) continue; + if (animation.groupId == item.id) candidate_animation_push(animation, groupAnimationIndex, true); + ++groupAnimationIndex; + } + } + } + else if (item.type == ElementType::ANIMATION) + { + if (!is_window_animation_grouped(groupIds, item)) candidate_animation_push(item, animationIndex, false); + ++animationIndex; + } + } + } auto footerSize = footer_size_get(); auto optionsSize = child_size_get(2); @@ -1138,26 +1949,25 @@ namespace anm2ed::imgui if (ImGui::BeginChild(localize.get(LABEL_ANIMATIONS_CHILD), animationsSize, ImGuiChildFlags_Borders)) { - auto items = animations(); - mergeSelection.start(animation_count()); + std::vector candidateKeys{}; + candidateKeys.reserve(candidates.size()); + for (const auto& candidate : candidates) + candidateKeys.push_back(candidate.key); - if (items) + mergeSelection.set_index_map(&candidateKeys); + mergeSelection.start(candidates.size()); + + for (int i = 0; i < (int)candidates.size(); ++i) { - for (int i = 0; i < (int)items->children.size(); i++) - { - if (i == mergeReference) continue; - - auto& animation = items->children[i]; - if (animation.type != ElementType::ANIMATION) continue; - - ImGui::PushID(i); - ImGui::SetNextItemSelectionUserData(i); - ImGui::Selectable(animation.name.c_str(), mergeSelection.contains(i)); - ImGui::PopID(); - } + const auto& candidate = candidates[i]; + ImGui::PushID(candidate.key); + ImGui::SetNextItemSelectionUserData(i); + ImGui::Selectable(candidate.label.c_str(), mergeSelection.contains(candidate.key)); + ImGui::PopID(); } mergeSelection.finish(); + mergeSelection.set_index_map(nullptr); } ImGui::EndChild(); @@ -1189,7 +1999,7 @@ namespace anm2ed::imgui auto widgetSize = widget_size_with_row_get(2); - ImGui::BeginDisabled(mergeSelection.empty()); + ImGui::BeginDisabled(window_animation_merge_indices_get(document, mergeSelection, mergeReference).empty()); if (ImGui::Button(localize.get(LABEL_MERGE), widgetSize)) { auto queuedSelection = mergeSelection; @@ -1327,7 +2137,7 @@ namespace anm2ed::imgui } }; - document.snapshot(localize.get(EDIT_TRIM_REGIONS)); + document.anm2_snapshot(localize.get(EDIT_TRIM_REGIONS)); behavior(); document.change(Document::SPRITESHEETS); }; @@ -1358,7 +2168,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.regions_deserialize(spritesheetReference, clipboard.get(), true, &errorString)) { - document.snapshot(localize.get(EDIT_PASTE_REGIONS)); + document.anm2_snapshot(localize.get(EDIT_PASTE_REGIONS)); anm2 = std::move(pasted); if (auto pastedSpritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference)) { @@ -1482,7 +2292,9 @@ namespace anm2ed::imgui ImGui::SetNextItemSelectionUserData(i); ImGui::SetNextItemStorageID(id); if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - if (ImGui::Selectable("##Region Selectable", isSelected, 0, regionChildSize)) + auto isActivated = ImGui::Selectable("##Region Selectable", isSelected, 0, regionChildSize); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) { document.editTarget = Document::EditTarget::REGION; reference = id; @@ -1910,6 +2722,546 @@ namespace anm2ed::imgui return window; } + Window overlays_window_register() + { + Window window{}; + window.title = LABEL_OVERLAYS_WINDOW; + window.isOpen = &Settings::windowIsOverlays; + window.changeType = Document::SPRITESHEETS; + window.elementType = ElementType::OVERLAY; + window.childLabel = "##Overlays Child"; + window.footerRows = 2; + window.flags = 0; + window.isChildPaddingZero = true; + window.unavailableText = TEXT_SELECT_SPRITESHEET; + window.popup = PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT); + window.storage_get = [](Document& document) -> Storage& { return document.overlay; }; + window.is_available = [](Document& document) + { return document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); }; + window.add = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::OVERLAY_OPEN, true); + }; + window.replace = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_open(Dialog::OVERLAY_REPLACE); + }; + window.path_set = [](Window& window, Manager&, Settings&, Document&, Clipboard&) + { + if (window.dialog) window.dialog->file_save(Dialog::OVERLAY_PATH_SET); + }; + window.open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto& selection = document.overlay.selection; + if (selection.size() != 1 || !window.dialog) return; + if (auto overlay = document.overlay_get(*selection.begin())) window_directory_open(*window.dialog, document, overlay->path); + }; + window.remove = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) + { + auto selected = document.overlay.selection; + if (selected.empty()) return; + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); + if (!spritesheet) return; + + auto behavior = [&]() + { + for (auto id : selected) + { + auto overlay = element_child_id_get(*spritesheet, ElementType::OVERLAY, id); + if (!overlay) continue; + auto pathString = path::to_utf8(overlay->path); + toasts.push(std::vformat(localize.get(TOAST_REMOVE_OVERLAY), std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_REMOVE_OVERLAY, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + element_child_id_erase(*spritesheet, ElementType::OVERLAY, id); + } + document.overlay.reference = -1; + document.overlay.selection.clear(); + }; + + window_edit(window, document, localize.get(EDIT_REMOVE_OVERLAYS), behavior); + }; + window.reload = [](Window&, Manager&, Settings&, Document& document, Clipboard&) + { + auto selected = document.overlay.selection; + if (selected.empty()) return; + document.textures_snapshot(localize.get(EDIT_RELOAD_OVERLAYS)); + for (auto id : selected) + document.overlay_texture_reload(id); + document.change(Document::TEXTURES); + + for (auto id : selected) + { + auto overlay = document.overlay_get(id); + if (!overlay) continue; + document.overlay_hash_set_saved(id); + auto pathString = path::to_utf8(overlay->path); + toasts.push(std::vformat(localize.get(TOAST_RELOAD_OVERLAY), std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_RELOAD_OVERLAY, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } + }; + window.save = [](Window&, Manager&, Settings&, Document& document, Clipboard&) + { + window_overlays_save(document, document.overlay.selection); + }; + window.copy = [](Window&, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + auto& selection = document.overlay.selection; + if (selection.empty()) return; + + std::string clipboardText{}; + for (auto id : selection) + if (auto overlay = document.overlay_get(id)) clipboardText += element_to_string(*overlay); + clipboard.set(clipboardText); + }; + window.paste = [](Window& window, Manager&, Settings&, Document& document, Clipboard& clipboard) + { + if (clipboard.is_empty()) return; + + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); + if (!spritesheet) return; + + tinyxml2::XMLDocument xmlDocument{}; + std::string errorString{}; + if (xmlDocument.Parse(clipboard.get().c_str()) != tinyxml2::XML_SUCCESS) + { + errorString = xmlDocument.ErrorStr(); + toasts.push(std::vformat(localize.get(TOAST_DESERIALIZE_OVERLAYS_FAILED), std::make_format_args(errorString))); + logger.error(std::vformat(localize.get(TOAST_DESERIALIZE_OVERLAYS_FAILED, anm2ed::ENGLISH), + std::make_format_args(errorString))); + return; + } + + std::vector pasted{}; + for (auto xmlElement = xmlDocument.FirstChildElement("Overlay"); xmlElement; + xmlElement = xmlElement->NextSiblingElement("Overlay")) + { + auto overlay = element_read(xmlElement); + if (overlay.type == ElementType::OVERLAY) pasted.push_back(std::move(overlay)); + } + if (pasted.empty()) + { + errorString = "No valid Overlay(s)."; + toasts.push(std::vformat(localize.get(TOAST_DESERIALIZE_OVERLAYS_FAILED), std::make_format_args(errorString))); + logger.error(std::vformat(localize.get(TOAST_DESERIALIZE_OVERLAYS_FAILED, anm2ed::ENGLISH), + std::make_format_args(errorString))); + return; + } + + auto behavior = [&]() + { + std::set added{}; + for (auto overlay : pasted) + { + overlay.id = window_overlay_next_id_get(document); + overlay.path = path::backslash_handle(overlay.path); + added.insert(overlay.id); + spritesheet->children.push_back(std::move(overlay)); + document.overlay_texture_reload(*added.rbegin()); + } + + document.overlay.selection = added; + document.overlay.reference = added.empty() ? -1 : *added.rbegin(); + document.editTarget = Document::EditTarget::OVERLAY; + window.newElementId = document.overlay.reference; + }; + + window_edit(window, document, localize.get(EDIT_PASTE_OVERLAYS), behavior); + }; + window.rows_update = + [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard, + Document& document, ImVec2) + { + auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, document.spritesheet.reference); + if (!spritesheet) return; + + auto& selection = document.overlay.selection; + auto& reference = document.overlay.reference; + auto style = ImGui::GetStyle(); + auto overlayChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 4); + bool isContextMenuQueued{}; + int contextMenuTargetId{-1}; + StringType visibilityTooltip{STRING_UNDEFINED}; + + std::vector ids{}; + for (auto& overlay : spritesheet->children) + if (overlay.type == ElementType::OVERLAY) ids.push_back(overlay.id); + + if (reference != -1 && std::ranges::find(ids, reference) == ids.end()) + { + reference = -1; + selection.clear(); + } + + selection.start((int)ids.size()); + if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + { + selection.clear(); + for (auto id : ids) + selection.insert(id); + } + if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) + { + selection.clear(); + reference = -1; + } + + int scrollTargetId = -1; + int arrowSelectionId = -1; + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && + (ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) + { + auto nextId = window_arrow_selection_get(ids, reference, selection); + if (nextId != -1) + { + arrowSelectionId = nextId; + scrollTargetId = nextId; + } + } + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + for (auto& overlay : spritesheet->children) + { + if (overlay.type != ElementType::OVERLAY) continue; + auto id = overlay.id; + auto isNewOverlay = window.newElementId == id; + ImGui::PushID(id); + + window_scroll_to_item(overlayChildSize.y, scrollTargetId == id); + if (scrollTargetId == id) ImGui::SetNextWindowFocus(); + + if (ImGui::BeginChild("##Overlay Child", overlayChildSize, ImGuiChildFlags_Borders)) + { + auto isSelected = selection.contains(id) || arrowSelectionId == id; + auto isReferenced = id == reference || arrowSelectionId == id; + auto cursorPos = ImGui::GetCursorPos(); + auto textureInfo = document.overlay_texture_get(id); + bool isValid = textureInfo && textureInfo->is_valid(); + auto& texture = isValid ? *textureInfo : resources.icons[icon::NONE]; + auto tintColor = !isValid ? ImVec4(1.0f, 0.25f, 0.25f, 1.0f) + : overlay.isVisible ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) + : ImVec4(1.0f, 1.0f, 1.0f, 0.35f); + auto pathString = path::to_utf8(overlay.path); + auto pathCStr = pathString.c_str(); + auto visibleButtonSize = icon_size_get(); + + ImGui::SetNextItemSelectionUserData(id); + ImGui::SetNextItemStorageID(id); + if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); + auto isActivated = + ImGui::Selectable("##Overlay Selectable", isSelected, ImGuiSelectableFlags_AllowOverlap, + overlayChildSize); + auto isRowRightClicked = ImGui::IsItemClicked(ImGuiMouseButton_Right); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || isRowRightClicked; + if (isActivated || isClicked) + { + document.editTarget = Document::EditTarget::OVERLAY; + reference = id; + document.region.reference = -1; + document.region.selection.clear(); + } + if (isRowRightClicked) + { + isContextMenuQueued = true; + contextMenuTargetId = id; + } + if (scrollTargetId == id) ImGui::SetItemDefaultFocus(); + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.dialog) + window_directory_open(*window.dialog, document, overlay.path); + + auto imageSize = to_imvec2(vec2(overlayChildSize.y)); + auto aspectRatio = texture.size.y != 0 ? (float)texture.size.x / texture.size.y : 1.0f; + if (imageSize.x / imageSize.y > aspectRatio) + imageSize.x = imageSize.y * aspectRatio; + else + imageSize.y = imageSize.x / aspectRatio; + + ImGui::SetCursorPos(cursorPos); + ImGui::ImageWithBg(texture.id, imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); + + ImGui::SetCursorPos( + ImVec2(overlayChildSize.y + style.ItemSpacing.x, + overlayChildSize.y - overlayChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); + + if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + auto overlayLabel = std::vformat(localize.get(FORMAT_OVERLAY), std::make_format_args(id, pathCStr)); + if (document.overlay_is_dirty(id)) + overlayLabel = + std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(overlayLabel)); + ImGui::TextUnformatted(overlayLabel.c_str()); + if (isReferenced) ImGui::PopFont(); + + auto visibleIcon = overlay.isVisible ? icon::VISIBLE : icon::INVISIBLE; + auto visibleButtonPos = + ImVec2(overlayChildSize.x - visibleButtonSize.x - style.ItemSpacing.x, + overlayChildSize.y * 0.5f - visibleButtonSize.y * 0.5f); + ImGui::SetCursorPos(visibleButtonPos); + 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); + if (ImGui::ImageButton("##Overlay Visible Toggle", resources.icons[visibleIcon].id, visibleButtonSize)) + { + auto queuedId = id; + manager.command_push({manager.selected, + [queuedId](Manager&, Document& document) + { + auto behavior = [&]() + { + auto overlay = document.overlay_get(queuedId); + if (!overlay) return; + overlay->isVisible = !overlay->isVisible; + }; + window_edit(document, Document::SPRITESHEETS, + localize.get(EDIT_TOGGLE_ITEM_VISIBILITY), behavior); + }}); + } + auto isVisibleButtonHovered = ImGui::IsItemHovered(); + auto isVisibleButtonRightClicked = ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isVisibleButtonRightClicked) + { + document.editTarget = Document::EditTarget::OVERLAY; + reference = id; + document.region.reference = -1; + document.region.selection.clear(); + isContextMenuQueued = true; + contextMenuTargetId = id; + } + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + if (isVisibleButtonHovered) + visibilityTooltip = + overlay.isVisible ? TOOLTIP_ITEM_VISIBILITY_SHOWN : TOOLTIP_ITEM_VISIBILITY_HIDDEN; + } + + ImGui::EndChild(); + + if (isNewOverlay) + { + ImGui::SetScrollHereY(0.5f); + window.newElementId = -1; + } + + ImGui::PopID(); + } + ImGui::PopStyleVar(); + + if (visibilityTooltip != STRING_UNDEFINED) + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); + ImGui::SetTooltip("%s", localize.get(visibilityTooltip)); + ImGui::PopStyleVar(2); + } + + selection.finish(); + if (contextMenuTargetId != -1) + { + document.editTarget = Document::EditTarget::OVERLAY; + if (!selection.contains(contextMenuTargetId)) selection = {contextMenuTargetId}; + reference = contextMenuTargetId; + document.region.reference = -1; + document.region.selection.clear(); + } + if (arrowSelectionId != -1) + { + document.editTarget = Document::EditTarget::OVERLAY; + selection = {arrowSelectionId}; + reference = arrowSelectionId; + document.region.reference = -1; + document.region.selection.clear(); + } + if (shortcut(manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && reference != -1 && window.dialog) + if (auto overlay = document.overlay_get(reference)) window_directory_open(*window.dialog, document, overlay->path); + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) && + ImGui::IsMouseReleased(ImGuiMouseButton_Right) && !ImGui::IsAnyItemHovered()) + isContextMenuQueued = true; + if (isContextMenuQueued) ImGui::OpenPopup("##Overlay Context Menu"); + + Actions actions{}; + window_overlays_context_actions_add(window, manager, settings, document, clipboard, actions); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, window.tooltipWindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, window.tooltipItemSpacing); + actions_popup_draw("##Overlay Context Menu", actions, settings); + ImGui::PopStyleVar(2); + }; + window.context_update = + [](Window&, Manager&, Settings&, Resources&, Clipboard&, Document&) {}; + window.footer_update = + [](Window& window, Manager& manager, Settings& settings, Resources&, Clipboard& clipboard, Document& document) + { + auto& selection = document.overlay.selection; + + auto rowOneWidgetSize = widget_size_with_row_get(3); + Actions rowOneActions{}; + rowOneActions.add(ACTION_ADD, [&]() { return (bool)window.add; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }, + TOOLTIP_ADD_OVERLAY); + rowOneActions.add(ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }, + TOOLTIP_RELOAD_OVERLAYS); + rowOneActions.add(ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }, + TOOLTIP_REPLACE_OVERLAY); + + bool isSameLine{}; + for (auto& action : rowOneActions.items) + action_button_draw(action, manager, settings, rowOneWidgetSize, isSameLine); + + if (window.dialog && window.dialog->is_selected(Dialog::OVERLAY_OPEN)) + { + auto paths = window.dialog->paths; + manager.command_push({manager.selected, [&window, paths](Manager&, Document& document) + { + document.overlays_add(document.spritesheet.reference, paths); + document.region.reference = -1; + document.region.selection.clear(); + window.newElementId = document.overlay.reference; + }}); + window.dialog->reset(); + } + + if (window.dialog && window.dialog->is_selected(Dialog::OVERLAY_REPLACE)) + { + if (selection.size() == 1 && !window.dialog->path.empty()) + { + auto id = *selection.begin(); + auto dialogPath = window.dialog->path; + manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) + { + auto behavior = [&]() + { + auto overlay = document.overlay_get(id); + if (!overlay) return; + overlay->path = window_asset_path_get(document, dialogPath); + document.overlay_texture_reload(id); + }; + + window_edit(document, Document::SPRITESHEETS, localize.get(EDIT_REPLACE_OVERLAY), + behavior); + if (auto overlay = document.overlay_get(id)) + { + document.overlay_hash_set_saved(id); + auto pathString = path::to_utf8(overlay->path); + toasts.push(std::vformat(localize.get(TOAST_REPLACE_OVERLAY), + std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_REPLACE_OVERLAY, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + } + }}); + } + window.dialog->reset(); + } + + if (window.dialog && window.dialog->is_selected(Dialog::OVERLAY_PATH_SET)) + { + if (selection.size() == 1 && !window.dialog->path.empty()) + { + auto id = *selection.begin(); + auto dialogPath = window.dialog->path; + manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) + { + auto behavior = [&]() + { + auto overlay = document.overlay_get(id); + auto texture = document.overlay_texture_get(id); + if (!overlay || !texture) return; + auto newPath = window_asset_path_get(document, dialogPath); + auto pathString = path::to_utf8(newPath); + WorkingDirectory workingDirectory(document.directory_get()); + path::ensure_directory(newPath.parent_path()); + if (!texture->write_png(newPath)) + { + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED), + std::make_format_args(id, pathString))); + logger.error( + std::vformat(localize.get(TOAST_SAVE_OVERLAY_FAILED, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + return; + } + overlay->path = newPath; + document.overlayTexturePaths[id] = overlay->path; + document.overlay_hash_set_saved(id); + toasts.push(std::vformat(localize.get(TOAST_SAVE_OVERLAY), + std::make_format_args(id, pathString))); + logger.info(std::vformat(localize.get(TOAST_SAVE_OVERLAY, anm2ed::ENGLISH), + std::make_format_args(id, pathString))); + }; + + window_edit(document, Document::SPRITESHEETS, localize.get(EDIT_SET_OVERLAY_FILE_PATH), + behavior); + }}); + } + window.dialog->reset(); + } + + auto rowTwoWidgetSize = widget_size_with_row_get(2); + Actions rowTwoActions{}; + rowTwoActions.add(ACTION_REMOVE, [&]() { return !selection.empty() && (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, + TOOLTIP_REMOVE_OVERLAYS); + rowTwoActions.add(ACTION_SAVE, [&]() { return !selection.empty(); }, + [&]() + { + if (settings.fileIsWarnOverwrite) + { + window.selection2 = selection; + window.popup.open(); + } + else if (window.save) + window_command_run(window, manager, settings, document, clipboard, window.save); + }, + TOOLTIP_SAVE_OVERLAYS); + + isSameLine = false; + for (auto& action : rowTwoActions.items) + action_button_draw(action, manager, settings, rowTwoWidgetSize, isSameLine); + + if (shortcut(manager.chords[SHORTCUT_ADD], shortcut::FOCUSED) && window.add) + window_command_run(window, manager, settings, document, clipboard, window.add); + if (shortcut(manager.chords[SHORTCUT_REMOVE], shortcut::FOCUSED) && window.remove) + window_command_run(window, manager, settings, document, clipboard, window.remove); + if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && window.copy) + window_command_run(window, manager, settings, document, clipboard, window.copy); + if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && window.paste) + window_command_run(window, manager, settings, document, clipboard, window.paste); + }; + window.popup_update = + [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document&) + { + window.popup.trigger(); + if (ImGui::BeginPopupModal(window.popup.label(), &window.popup.isOpen, ImGuiWindowFlags_NoResize)) + { + ImGui::TextUnformatted(localize.get(LABEL_OVERWRITE_CONFIRMATION)); + + auto widgetSize = widget_size_with_row_get(2); + + if (ImGui::Button(localize.get(BASIC_YES), widgetSize)) + { + auto queuedSelection = window.selection2; + manager.command_push({manager.selected, [queuedSelection](Manager&, Document& document) mutable + { window_overlays_save(document, queuedSelection); }}); + window.selection2.clear(); + window.popup.close(); + } + + ImGui::SameLine(); + + if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) + { + window.selection2.clear(); + window.popup.close(); + } + + ImGui::EndPopup(); + } + window.popup.end(); + }; + return window; + } + Window spritesheets_window_register() { Window window{}; @@ -2044,7 +3396,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.deserialize(ElementType::SPRITESHEET, clipboard.get(), true, &errorString, document.directory_get())) { - document.snapshot(localize.get(EDIT_PASTE_SPRITESHEETS)); + document.anm2_snapshot(localize.get(EDIT_PASTE_SPRITESHEETS)); anm2 = std::move(pasted); if (auto pastedItems = anm2.element_get(ElementType::SPRITESHEETS)) { @@ -2145,7 +3497,9 @@ namespace anm2ed::imgui ImGui::SetNextItemSelectionUserData(id); ImGui::SetNextItemStorageID(id); if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - if (ImGui::Selectable("##Spritesheet Selectable", isSelected, 0, spritesheetChildSize)) + auto isActivated = ImGui::Selectable("##Spritesheet Selectable", isSelected, 0, spritesheetChildSize); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) { document.editTarget = Document::EditTarget::SPRITESHEET; reference = id; @@ -2701,7 +4055,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.deserialize(ElementType::SOUND_ELEMENT, clipboard.get(), true, &errorString, document.directory_get())) { - document.snapshot(localize.get(TOAST_SOUNDS_PASTE)); + document.anm2_snapshot(localize.get(TOAST_SOUNDS_PASTE)); anm2 = std::move(pasted); if (auto pastedSounds = anm2.element_get(ElementType::SOUNDS)) { @@ -2793,10 +4147,12 @@ namespace anm2ed::imgui ImGui::SetNextItemSelectionUserData(id); ImGui::SetNextItemStorageID(id); if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); - if (ImGui::Selectable("##Sound Selectable", isSelected, 0, soundChildSize)) + auto isActivated = ImGui::Selectable("##Sound Selectable", isSelected, 0, soundChildSize); + auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) { reference = id; - if (ImGui::IsMouseClicked(ImGuiMouseButton_Left)) play(id); + if (ImGui::IsItemClicked(ImGuiMouseButton_Left)) play(id); } if (scrollTargetId == id) ImGui::SetItemDefaultFocus(); if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left) && window.dialog) diff --git a/src/imgui/window/window.hpp b/src/imgui/window/window.hpp index d7006f4..c6317ce 100644 --- a/src/imgui/window/window.hpp +++ b/src/imgui/window/window.hpp @@ -29,7 +29,8 @@ namespace anm2ed::imgui WINDOW_PASTE = 1 << 8, WINDOW_RENAME = 1 << 9, WINDOW_PROPERTIES = 1 << 10, - WINDOW_REFERENCE_ITALIC = 1 << 11 + WINDOW_REFERENCE_ITALIC = 1 << 11, + WINDOW_GROUP = 1 << 12 }; using WindowFlags = int; @@ -108,6 +109,7 @@ namespace anm2ed::imgui Command duplicate{}; Command merge{}; Command merge_open{}; + Command group{}; Command default_set{}; Command cut{}; Command copy{}; @@ -137,5 +139,6 @@ namespace anm2ed::imgui Window layers_window_register(); Window nulls_window_register(); Window events_window_register(); + Window overlays_window_register(); void window_update(Window&, Manager&, Settings&, Resources&, Dialog&, Clipboard&); } diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index abb3a30..7fda1f5 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -84,7 +84,11 @@ namespace anm2ed::imgui::wizard { std::set result = itemReferences; if (result.empty() && document.reference.itemType != NONE) - result.insert({document.reference.animationIndex, document.reference.itemType, document.reference.itemID}); + { + auto itemReference = document.reference; + itemReference.frameIndex = -1; + result.insert(itemReference); + } std::erase_if(result, [&](const Reference& reference) { return !is_item_reference_changeable(reference); }); return result; }; @@ -396,12 +400,10 @@ namespace anm2ed::imgui::wizard groupedFrames[itemReference].insert(frameReference.frameIndex); } - document.snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto& [itemReference, selection] : groupedFrames) { - auto item = anm2.element_get(itemReference.animationIndex, - static_cast(itemReference.itemType), - itemReference.itemID); + auto item = anm2.element_get(itemReference); if (!item) continue; frames_change(*item, frameChange, static_cast(itemReference.itemType), changeType, selection); @@ -412,13 +414,12 @@ namespace anm2ed::imgui::wizard if (queuedIsItemsDestination) { - document.snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto itemReference : queuedItemReferences) { if (itemReference.itemType == TRIGGER) continue; - auto item = anm2.element_get(itemReference.animationIndex, - static_cast(itemReference.itemType), - itemReference.itemID); + itemReference.frameIndex = -1; + auto item = anm2.element_get(itemReference); if (!item) continue; auto selection = all_frames_selection(*item); frames_change(*item, frameChange, static_cast(itemReference.itemType), @@ -428,7 +429,7 @@ namespace anm2ed::imgui::wizard return; } - document.snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto animationIndex : queuedAnimations) { auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); diff --git a/src/imgui/wizard/configure.cpp b/src/imgui/wizard/configure.cpp index 315f8e3..dd718b5 100644 --- a/src/imgui/wizard/configure.cpp +++ b/src/imgui/wizard/configure.cpp @@ -69,15 +69,6 @@ namespace anm2ed::imgui::wizard ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_STACK_SIZE)); ImGui::SeparatorText(localize.get(LABEL_SERIALIZATION)); - ImGui::Checkbox(localize.get(LABEL_GROUPS), &temporary.fileIsSerializeGroups); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SERIALIZE_GROUPS)); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_REGIONS), &temporary.fileIsSerializeRegions); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SERIALIZE_REGIONS)); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_SOUNDS), &temporary.fileIsSerializeSounds); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SERIALIZE_SOUNDS)); - ImGui::Checkbox(localize.get(LABEL_KEEP_REDUNDANT_FRAME_REGION_VALUES), &temporary.fileIsKeepRedundantFrameRegionValues); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_KEEP_REDUNDANT_FRAME_REGION_VALUES)); @@ -86,6 +77,9 @@ namespace anm2ed::imgui::wizard &temporary.fileIsBakeSpecialInterpolatedFrames); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_SPECIAL_INTERPOLATED_FRAMES_ON_SAVE)); + ImGui::Checkbox(localize.get(LABEL_BAKE_GROUP_FRAMES_ON_SAVE), &temporary.isFileBakeGroupFrames); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_GROUP_FRAMES_ON_SAVE)); + ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); ImGui::Checkbox(localize.get(LABEL_OVERWRITE_WARNING), &temporary.fileIsWarnOverwrite); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERWRITE_WARNING)); diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index 3ab3037..07a34c4 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -162,8 +162,7 @@ namespace anm2ed::imgui::wizard bool isRegionsChanged{}; for (auto queuedReference : queuedLayerReferences) { - auto item = document.anm2.element_get(queuedReference.animationIndex, ItemType::LAYER, - queuedReference.itemID); + auto item = document.anm2.element_get(queuedReference); auto animation = document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex); auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, @@ -175,7 +174,7 @@ namespace anm2ed::imgui::wizard if (!isChanged) { - document.snapshot(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); + document.anm2_snapshot(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); isChanged = true; } auto frameIndexStart = (int)item->children.size(); diff --git a/src/imgui/wizard/render_animation.cpp b/src/imgui/wizard/render_animation.cpp index ed0e95b..58fdf57 100644 --- a/src/imgui/wizard/render_animation.cpp +++ b/src/imgui/wizard/render_animation.cpp @@ -1,5 +1,6 @@ #include "render_animation.hpp" +#include #include #include #include @@ -34,12 +35,14 @@ namespace anm2ed::imgui::wizard [&](const Reference& frameReference) { return frameReference.animationIndex != reference.animationIndex || - frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID; + frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID || + frameReference.groupType != reference.groupType || frameReference.groupId != reference.groupId; }); if (!frameReferences.empty()) { - auto itemType = static_cast(reference.itemType); - if (auto item = document.anm2.element_get(reference.animationIndex, itemType, reference.itemID)) + auto itemReference = reference; + itemReference.frameIndex = -1; + if (auto item = document.anm2.element_get(itemReference)) { int duration{}; int frameIndex{}; @@ -74,7 +77,8 @@ namespace anm2ed::imgui::wizard auto& path = settings.renderPath; auto& format = settings.renderFormat; auto& scale = settings.renderScale; - auto& isRaw = settings.renderIsRawAnimation; + auto& isUseAnimationBounds = settings.renderIsUseAnimationBounds; + auto& isUseIsolatedAnimation = settings.renderIsUseIsolatedAnimation; auto& type = settings.renderType; auto& start = manager.recordingStart; auto& end = manager.recordingEnd; @@ -83,6 +87,11 @@ namespace anm2ed::imgui::wizard auto& isRange = manager.isRecordingRange; auto& reference = document.reference; auto& frameNum = animation->frameNum; + auto animationFrameNum = std::max(frameNum, 1); + auto frameMax = animationFrameNum - 1; + start = std::clamp(start, 0, frameMax); + end = std::clamp(end, start, frameMax); + auto renderFrameNum = isRange ? render::frame_count_get(start, end) : animationFrameNum; auto widgetSize = widget_size_with_row_get(2); @@ -154,10 +163,10 @@ namespace anm2ed::imgui::wizard } else if (type == render::SPRITESHEET) { - input_int_range(localize.get(LABEL_GENERATE_ROWS), rows, 1, frameNum - 1); + input_int_range(localize.get(LABEL_GENERATE_ROWS), rows, 1, renderFrameNum); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROWS)); - input_int_range(localize.get(LABEL_GENERATE_COLUMNS), columns, 1, frameNum - 1); + input_int_range(localize.get(LABEL_GENERATE_COLUMNS), columns, 1, renderFrameNum); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLUMNS)); } @@ -181,19 +190,32 @@ namespace anm2ed::imgui::wizard ImGui::BeginDisabled(!isRange); { - input_int_range(localize.get(LABEL_START), start, 0, frameNum - 1); + input_int_range(localize.get(LABEL_START), start, 0, frameMax); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_START)); - input_int_range(localize.get(LABEL_END), end, start, frameNum - 1); + input_int_range(localize.get(LABEL_END), end, start, frameMax); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_END)); } ImGui::EndDisabled(); + renderFrameNum = isRange ? render::frame_count_get(start, end) : animationFrameNum; + + if (type == render::SPRITESHEET) + { + auto layout = render::spritesheet_layout_get(rows, columns, renderFrameNum); + rows = layout.rows; + columns = layout.columns; + } ImGui::Separator(); - ImGui::Checkbox(localize.get(LABEL_RAW), &isRaw); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RAW)); + ImGui::Checkbox(localize.get(LABEL_USE_ANIMATION_BOUNDS), &isUseAnimationBounds); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_USE_ANIMATION_BOUNDS)); - ImGui::BeginDisabled(!isRaw); + ImGui::SameLine(); + + ImGui::Checkbox(localize.get(LABEL_USE_ISOLATED_ANIMATION), &isUseIsolatedAnimation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_USE_ISOLATED_ANIMATION)); + + ImGui::BeginDisabled(!isUseAnimationBounds); { input_float_range(localize.get(BASIC_SCALE), scale, 0.1f, 100.0f, 1.0f, STEP_FAST, "%.1fx"); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SCALE_OUTPUT)); diff --git a/src/manager.hpp b/src/manager.hpp index ea96795..43713bc 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -53,8 +53,11 @@ namespace anm2ed std::vector anm2DragDropPaths{}; bool isAnm2DragDrop{}; + int anm2DragDropMergePreset{Document::FILE_MERGE_PRESET_MERGE_BY_NAME}; imgui::PopupHelper anm2DragDropPopup{ imgui::PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, imgui::POPUP_NORMAL, imgui::POPUP_BY_CURSOR)}; + imgui::PopupHelper anm2DragDropMergePopup{ + imgui::PopupHelper(LABEL_DOCUMENTS_MERGE_INTO_CURRENT, imgui::POPUP_NORMAL_NO_HEIGHT)}; std::filesystem::path spritesheetDragDropPath{}; bool isSpritesheetDragDrop{}; diff --git a/src/render.hpp b/src/render.hpp index 5c6639b..de7ce97 100644 --- a/src/render.hpp +++ b/src/render.hpp @@ -1,5 +1,8 @@ #pragma once +#include +#include + #include "audio_stream.hpp" #include "texture.hpp" @@ -31,6 +34,40 @@ namespace anm2ed::render RENDER_LIST #undef X }; + + struct SpritesheetLayout + { + int rows{}; + int columns{}; + }; + + inline int frame_count_get(int start, int end) { return std::max(end - start + 1, 1); } + + inline SpritesheetLayout spritesheet_layout_get(int rows, int columns, int frameCount) + { + frameCount = std::max(frameCount, 1); + rows = std::max(rows, 0); + columns = std::max(columns, 0); + + if (rows == 0 && columns == 0) + { + columns = std::max((int)std::ceil(std::sqrt((float)frameCount)), 1); + rows = (frameCount + columns - 1) / columns; + } + else if (rows == 0) + rows = (frameCount + columns - 1) / columns; + else if (columns == 0) + columns = (frameCount + rows - 1) / rows; + else if (rows * columns < frameCount) + { + if (rows <= columns) + columns = (frameCount + rows - 1) / rows; + else + rows = (frameCount + columns - 1) / columns; + } + + return {rows, columns}; + } } namespace anm2ed diff --git a/src/resource/shader.cpp b/src/resource/shader.cpp index db0631a..7afcf58 100644 --- a/src/resource/shader.cpp +++ b/src/resource/shader.cpp @@ -1,16 +1,398 @@ #include "shader.hpp" +#include +#include +#include +#include + #include "log.hpp" +namespace anm2ed::resource::shader +{ +#define SHADER_GLES_WORD_REPLACEMENTS \ + X("texture2D", "texture") \ + X("gl_FragColor", "fragColor") + + struct UniformAlias + { + UniformBinding binding{}; + const char* name{}; + }; + +#define RESOURCE_SHADER_UNIFORM_ALIASES \ + X(UNIFORM_BINDING_MAIN_TEXTURE, UNIFORM_TEXTURE) \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "texture0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \ + X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \ + X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ + X(UNIFORM_BINDING_TRANSFORM, "Transform") \ + X(UNIFORM_BINDING_TRANSFORM, "MVP") \ + X(UNIFORM_BINDING_TRANSFORM, "Matrix") \ + X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ + X(UNIFORM_BINDING_FRAME_TINT, "Tint") \ + X(UNIFORM_BINDING_FRAME_TINT, "Color") \ + X(UNIFORM_BINDING_FRAME_TINT, "Color0") \ + X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ + X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \ + X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "TextureSize") \ + X(UNIFORM_BINDING_TEXTURE_SIZE, "TexSize") + + constexpr UniformAlias UNIFORM_ALIASES[] = { +#define X(binding, name) {binding, name}, + RESOURCE_SHADER_UNIFORM_ALIASES +#undef X + }; + + bool is_shader_identifier(char character) + { + return std::isalnum((unsigned char)character) || character == '_'; + } + + std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) + { + if (from.empty()) return string; + std::size_t position{}; + while ((position = string.find(from, position)) != std::string::npos) + { + string.replace(position, from.size(), to.data(), to.size()); + position += to.size(); + } + return string; + } + + std::string shader_word_replace(std::string string, std::string_view from, std::string_view to) + { + if (from.empty()) return string; + + std::size_t position{}; + while ((position = string.find(from, position)) != std::string::npos) + { + auto after = position + from.size(); + auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); + auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); + if (!isBeforeIdentifier && !isAfterIdentifier) + { + string.replace(position, from.size(), to.data(), to.size()); + position += to.size(); + continue; + } + position = after; + } + return string; + } + + std::string shader_space_collapse(std::string_view string) + { + std::string out{}; + bool isSpace{}; + for (auto character : string) + { + if (std::isspace((unsigned char)character)) + { + if (!out.empty() && !isSpace) out.push_back(' '); + isSpace = true; + continue; + } + out.push_back(character); + isSpace = false; + } + if (!out.empty() && out.back() == ' ') out.pop_back(); + return out; + } + + std::string shader_trim_get(std::string_view line) + { + std::size_t begin{}; + while (begin < line.size() && std::isspace((unsigned char)line[begin])) + ++begin; + + auto end = line.size(); + while (end > begin && std::isspace((unsigned char)line[end - 1])) + --end; + + return std::string(line.substr(begin, end - begin)); + } + + bool is_shader_word_present(std::string_view string, std::string_view word) + { + std::size_t position{}; + while ((position = string.find(word, position)) != std::string_view::npos) + { + auto after = position + word.size(); + auto isBeforeIdentifier = position > 0 && is_shader_identifier(string[position - 1]); + auto isAfterIdentifier = after < string.size() && is_shader_identifier(string[after]); + if (!isBeforeIdentifier && !isAfterIdentifier) return true; + position = after; + } + return false; + } + + bool is_shader_line_skipped(std::string_view line) + { + auto normalized = shader_space_collapse(shader_trim_get(line)); + if (normalized.starts_with("#version")) return true; + if (normalized.starts_with("precision ")) return true; + if (normalized == "#define lowp" || normalized == "# define lowp") return true; + if (normalized == "#define mediump" || normalized == "# define mediump") return true; + if (normalized == "#define highp" || normalized == "# define highp") return true; + if (normalized == "#define texture texture2D" || normalized == "# define texture texture2D") return true; + if (normalized == "#define fragColor gl_FragColor" || normalized == "# define fragColor gl_FragColor") return true; + return false; + } + + std::string shader_precision_erase(std::string line) + { + line = shader_word_replace(std::move(line), "lowp", ""); + line = shader_word_replace(std::move(line), "mediump", ""); + line = shader_word_replace(std::move(line), "highp", ""); + return line; + } + + std::string shader_line_convert(std::string line, ShaderStage stage) + { + line = shader_precision_erase(std::move(line)); + line = shader_word_replace(std::move(line), "attribute", "in"); + line = shader_word_replace(std::move(line), "varying", stage == SHADER_STAGE_VERTEX ? "out" : "in"); +#define X(from, to) line = shader_word_replace(std::move(line), from, to); + SHADER_GLES_WORD_REPLACEMENTS +#undef X + return line; + } + + std::string shader_fragment_declarations_get(std::string_view body) + { + if (!is_shader_word_present(body, "fragColor")) return {}; + if (body.find("out vec4 fragColor") != std::string_view::npos) return {}; + return "out vec4 fragColor;\n"; + } + + std::string uniform_name_clean_get(std::string name) + { + if (name.ends_with("[0]")) name.erase(name.size() - 3); + return name; + } + + std::string uniform_float_string_get(float value) { return std::format("{:.6g}", value); } + + UniformBinding uniform_binding_auto_get(std::string_view name, UniformValueType type) + { + for (const auto& alias : UNIFORM_ALIASES) + if (name == alias.name && is_uniform_binding_valid(alias.binding, type)) return alias.binding; + if (type == UNIFORM_VALUE_SAMPLER2D) return UNIFORM_BINDING_MAIN_TEXTURE; + if (is_uniform_value_editable(type)) return UNIFORM_BINDING_MANUAL; + return UNIFORM_BINDING_IGNORE; + } + + UniformBinding uniform_binding_get(std::string_view value) + { + for (const auto& info : UNIFORM_BINDING_INFOS) + if (value == info.value) return info.binding; + return UNIFORM_BINDING_IGNORE; + } + + std::string_view uniform_binding_value_get(UniformBinding binding) + { + for (const auto& info : UNIFORM_BINDING_INFOS) + if (binding == info.binding) return info.value; + return UNIFORM_BINDING_INFOS[0].value; + } + + std::string_view uniform_binding_label_get(UniformBinding binding) + { + for (const auto& info : UNIFORM_BINDING_INFOS) + if (binding == info.binding) return info.label; + return UNIFORM_BINDING_INFOS[0].label; + } + + UniformValueType uniform_value_type_get(GLenum type) + { + switch (type) + { + case GL_FLOAT: + return UNIFORM_VALUE_FLOAT; + case GL_INT: + case GL_BOOL: + return UNIFORM_VALUE_INT; + case GL_FLOAT_VEC2: + return UNIFORM_VALUE_VEC2; + case GL_FLOAT_VEC3: + return UNIFORM_VALUE_VEC3; + case GL_FLOAT_VEC4: + return UNIFORM_VALUE_VEC4; + case GL_FLOAT_MAT4: + return UNIFORM_VALUE_MAT4; + case GL_SAMPLER_2D: + return UNIFORM_VALUE_SAMPLER2D; + default: + return UNIFORM_VALUE_UNKNOWN; + } + } + + std::string_view uniform_value_type_label_get(UniformValueType type) + { + for (const auto& info : UNIFORM_VALUE_TYPE_INFOS) + if (type == info.type) return info.label; + return UNIFORM_VALUE_TYPE_INFOS[0].label; + } + + bool is_uniform_value_editable(UniformValueType type) + { + return type == UNIFORM_VALUE_FLOAT || type == UNIFORM_VALUE_INT || type == UNIFORM_VALUE_VEC2 || + type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4 || type == UNIFORM_VALUE_SAMPLER2D; + } + + bool is_uniform_value_vector(UniformValueType type) + { + return type == UNIFORM_VALUE_VEC2 || type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4; + } + + bool is_uniform_binding_valid(UniformBinding binding, UniformValueType type) + { + switch (binding) + { + case UNIFORM_BINDING_IGNORE: + return true; + case UNIFORM_BINDING_MANUAL: + return is_uniform_value_editable(type); + case UNIFORM_BINDING_MAIN_TEXTURE: + return type == UNIFORM_VALUE_SAMPLER2D; + case UNIFORM_BINDING_TRANSFORM: + return type == UNIFORM_VALUE_MAT4; + case UNIFORM_BINDING_FRAME_TINT: + case UNIFORM_BINDING_COLOR_OFFSET: + case UNIFORM_BINDING_TEXTURE_SIZE: + case UNIFORM_BINDING_PLAYBACK_TIME: + return type == UNIFORM_VALUE_FLOAT || is_uniform_value_vector(type); + case UNIFORM_BINDING_COMPONENTS: + return is_uniform_value_vector(type); + default: + return false; + } + } + + void uniform_value_parse(Uniform& uniform, std::string_view value) + { + if (value.empty()) return; + + std::stringstream stream{std::string(value)}; + if (uniform.valueType == UNIFORM_VALUE_INT || uniform.valueType == UNIFORM_VALUE_SAMPLER2D) + { + stream >> uniform.intValue; + return; + } + + stream >> uniform.value.x >> uniform.value.y >> uniform.value.z >> uniform.value.w; + uniform.components[0].value = uniform.value.x; + uniform.components[1].value = uniform.value.y; + uniform.components[2].value = uniform.value.z; + uniform.components[3].value = uniform.value.w; + } + + std::string uniform_value_string_get(const Uniform& uniform) + { + switch (uniform.valueType) + { + case UNIFORM_VALUE_FLOAT: + return uniform_float_string_get(uniform.value.x); + case UNIFORM_VALUE_INT: + case UNIFORM_VALUE_SAMPLER2D: + return std::format("{}", uniform.intValue); + case UNIFORM_VALUE_VEC2: + return std::format("{} {}", uniform_float_string_get(uniform.value.x), uniform_float_string_get(uniform.value.y)); + case UNIFORM_VALUE_VEC3: + return std::format("{} {} {}", uniform_float_string_get(uniform.value.x), + uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z)); + case UNIFORM_VALUE_VEC4: + return std::format("{} {} {} {}", uniform_float_string_get(uniform.value.x), + uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z), + uniform_float_string_get(uniform.value.w)); + default: + return {}; + } + } + + std::vector uniforms_get(GLuint id) + { + GLint count{}; + GLint maxLength{}; + glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &count); + glGetProgramiv(id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLength); + + std::vector uniforms{}; + if (count <= 0 || maxLength <= 0) return uniforms; + + std::string name((std::size_t)maxLength, '\0'); + for (GLint index = 0; index < count; ++index) + { + GLsizei length{}; + GLint size{}; + GLenum type{}; + glGetActiveUniform(id, (GLuint)index, maxLength, &length, &size, &type, name.data()); + + auto uniformName = uniform_name_clean_get(std::string(name.data(), (std::size_t)length)); + auto valueType = uniform_value_type_get(type); + + Uniform uniform{}; + uniform.name = uniformName; + uniform.location = glGetUniformLocation(id, uniformName.c_str()); + uniform.glType = type; + uniform.size = size; + uniform.valueType = valueType; + uniform.binding = uniform_binding_auto_get(uniformName, valueType); + uniform.components[0].value = uniform.value.x; + uniform.components[1].value = uniform.value.y; + uniform.components[2].value = uniform.value.z; + uniform.components[3].value = uniform.value.w; + uniforms.push_back(std::move(uniform)); + } + + return uniforms; + } + + std::string gles_convert(std::string_view source, ShaderStage stage) + { + auto normalized = shader_text_replace(std::string(source), "\r\n", "\n"); + normalized = shader_text_replace(std::move(normalized), "\r", "\n"); + + std::string body{}; + std::size_t position{}; + while (position <= normalized.size()) + { + auto end = normalized.find('\n', position); + auto isEnd = end == std::string::npos; + auto line = normalized.substr(position, isEnd ? std::string::npos : end - position); + if (!is_shader_line_skipped(line)) body += shader_line_convert(std::move(line), stage) + "\n"; + if (isEnd) break; + position = end + 1; + } + + auto declarations = stage == SHADER_STAGE_FRAGMENT ? shader_fragment_declarations_get(body) : std::string{}; + return "#version 330 core\n" + declarations + body; + } + + std::string gles_fragment_convert(std::string_view source) + { + return gles_convert(source, SHADER_STAGE_FRAGMENT); + } + + std::string gles_vertex_convert(std::string_view source) + { + return gles_convert(source, SHADER_STAGE_VERTEX); + } +} + namespace anm2ed::resource { - Shader::Shader() = default; - - Shader::Shader(const char* vertex, const char* fragment) + ShaderCompileResult shader_compile(const char* vertex, const char* fragment) { - id = glCreateProgram(); + ShaderCompileResult result{}; + result.id = glCreateProgram(); - auto compile = [&](const GLuint& id, const char* text) + auto compile = [&](const GLuint& id, const char* text, const char* label) { int isCompile{}; glShaderSource(id, 1, &text, nullptr); @@ -19,9 +401,12 @@ namespace anm2ed::resource if (!isCompile) { - std::string compileLog(255, '\0'); - glGetShaderInfoLog(id, 255, nullptr, compileLog.data()); - logger.error(std::format("Unable to compile shader {}: {}", id, compileLog.c_str())); + GLint length{}; + glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); + if (length <= 0) length = 1; + std::string compileLog((std::size_t)length, '\0'); + glGetShaderInfoLog(id, length, nullptr, compileLog.data()); + result.output += std::format("{} shader compile log:\n{}\n", label, compileLog.c_str()); return false; } return true; @@ -30,31 +415,66 @@ namespace anm2ed::resource auto vertexHandle = glCreateShader(GL_VERTEX_SHADER); auto fragmentHandle = glCreateShader(GL_FRAGMENT_SHADER); - if (!(compile(vertexHandle, vertex) && compile(fragmentHandle, fragment))) return; - - glAttachShader(id, vertexHandle); - glAttachShader(id, fragmentHandle); - - glLinkProgram(id); - - auto isLinked = GL_FALSE; - glGetProgramiv(id, GL_LINK_STATUS, &isLinked); - if (!isLinked) + auto isVertexCompiled = compile(vertexHandle, vertex, "Vertex"); + auto isFragmentCompiled = compile(fragmentHandle, fragment, "Fragment"); + result.isCompiled = isVertexCompiled && isFragmentCompiled; + if (result.isCompiled) { - glDeleteProgram(id); - id = 0; + glAttachShader(result.id, vertexHandle); + glAttachShader(result.id, fragmentHandle); + + for (const auto& alias : shader::ATTRIBUTE_ALIASES) + glBindAttribLocation(result.id, alias.index, alias.name); + + glLinkProgram(result.id); + + auto isLinked = GL_FALSE; + glGetProgramiv(result.id, GL_LINK_STATUS, &isLinked); + result.isLinked = isLinked == GL_TRUE; + if (!result.isLinked) + { + GLint length{}; + glGetProgramiv(result.id, GL_INFO_LOG_LENGTH, &length); + if (length <= 0) length = 1; + std::string linkLog((std::size_t)length, '\0'); + glGetProgramInfoLog(result.id, length, nullptr, linkLog.data()); + result.output += std::format("Shader link log:\n{}\n", linkLog.c_str()); + } + else + result.uniforms = shader::uniforms_get(result.id); } glDeleteShader(vertexHandle); glDeleteShader(fragmentHandle); + + if (!result.isLinked) + { + glDeleteProgram(result.id); + result.id = 0; + } + + return result; } + Shader::Shader() = default; + + Shader::Shader(const char* vertex, const char* fragment) + { + auto result = shader_compile(vertex, fragment); + id = result.id; + uniforms = std::move(result.uniforms); + if (!result.output.empty()) logger.error(result.output); + } + + Shader::Shader(Shader&& other) noexcept { *this = std::move(other); } + Shader& Shader::operator=(Shader&& other) noexcept { if (this != &other) { if (is_valid()) glDeleteProgram(id); id = other.id; + uniforms = std::move(other.uniforms); other.id = 0; } return *this; diff --git a/src/resource/shader.hpp b/src/resource/shader.hpp index 38c1044..6068a02 100644 --- a/src/resource/shader.hpp +++ b/src/resource/shader.hpp @@ -1,6 +1,12 @@ #pragma once #include +#include + +#include +#include +#include +#include namespace anm2ed::resource::shader { @@ -23,6 +29,24 @@ namespace anm2ed::resource::shader } )"; + inline constexpr auto TEXTURE_COMPATIBILITY_VERTEX = R"( + #version 330 core + layout (location = 0) in vec2 i_position; + layout (location = 1) in vec2 i_uv; + out vec2 i_uv_out; + out vec2 TexCoord0; + out vec4 Color0; + uniform mat4 u_transform; + uniform vec4 u_tint; + void main() + { + i_uv_out = i_uv; + TexCoord0 = i_uv; + Color0 = u_tint; + gl_Position = u_transform * vec4(i_position, 0.0, 1.0); + } + )"; + inline constexpr auto AXIS_VERTEX = R"( #version 330 core layout (location = 0) in vec2 i_position; // full screen line segment: -1..1 @@ -203,6 +227,122 @@ namespace anm2ed::resource::shader constexpr auto UNIFORM_DASH_GAP = "u_dash_gap"; constexpr auto UNIFORM_DASH_OFFSET = "u_dash_offset"; +#define RESOURCE_SHADER_ATTRIBUTE_ALIASES \ + X(0, "i_position") \ + X(0, "a_position") \ + X(0, "Position") \ + X(0, "Position0") \ + X(1, "i_uv") \ + X(1, "a_uv") \ + X(1, "TexCoord") \ + X(1, "TexCoord0") \ + X(1, "TextureCoord") \ + X(1, "UV") \ + X(1, "UV0") \ + X(2, "i_color") \ + X(2, "a_color") \ + X(2, "Color") \ + X(2, "Color0") + + struct AttributeAlias + { + GLuint index{}; + const char* name{}; + }; + + inline constexpr AttributeAlias ATTRIBUTE_ALIASES[] = { +#define X(index, name) {index, name}, + RESOURCE_SHADER_ATTRIBUTE_ALIASES +#undef X + }; + +#define RESOURCE_SHADER_UNIFORM_BINDINGS \ + X(IGNORE, "Ignore", "Ignore") \ + X(MAIN_TEXTURE, "MainTexture", "Main Texture") \ + X(TRANSFORM, "Transform", "Transform") \ + X(FRAME_TINT, "FrameTint", "Frame Tint") \ + X(COLOR_OFFSET, "ColorOffset", "Color Offset") \ + X(TEXTURE_SIZE, "TextureSize", "Texture Size") \ + X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \ + X(COMPONENTS, "Components", "Per Component") \ + X(MANUAL, "Manual", "Manual") + + enum UniformBinding + { +#define X(symbol, value, label) UNIFORM_BINDING_##symbol, + RESOURCE_SHADER_UNIFORM_BINDINGS +#undef X + UNIFORM_BINDING_COUNT + }; + + struct UniformBindingInfo + { + UniformBinding binding{}; + const char* value{}; + const char* label{}; + }; + + inline constexpr UniformBindingInfo UNIFORM_BINDING_INFOS[] = { +#define X(symbol, value, label) {UNIFORM_BINDING_##symbol, value, label}, + RESOURCE_SHADER_UNIFORM_BINDINGS +#undef X + }; + +#define RESOURCE_SHADER_UNIFORM_VALUE_TYPES \ + X(UNKNOWN, "Unknown") \ + X(FLOAT, "Float") \ + X(INT, "Int") \ + X(VEC2, "Vec2") \ + X(VEC3, "Vec3") \ + X(VEC4, "Vec4") \ + X(MAT4, "Mat4") \ + X(SAMPLER2D, "Sampler2D") + + enum UniformValueType + { +#define X(symbol, label) UNIFORM_VALUE_##symbol, + RESOURCE_SHADER_UNIFORM_VALUE_TYPES +#undef X + UNIFORM_VALUE_COUNT + }; + + struct UniformValueTypeInfo + { + UniformValueType type{}; + const char* label{}; + }; + + inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = { +#define X(symbol, label) {UNIFORM_VALUE_##symbol, label}, + RESOURCE_SHADER_UNIFORM_VALUE_TYPES +#undef X + }; + + struct Uniform + { + struct Component + { + UniformBinding binding{UNIFORM_BINDING_MANUAL}; + float value{}; + }; + + std::string name{}; + GLint location{-1}; + GLenum glType{}; + GLint size{}; + UniformValueType valueType{UNIFORM_VALUE_UNKNOWN}; + UniformBinding binding{UNIFORM_BINDING_IGNORE}; + glm::vec4 value{}; + int intValue{}; + std::array components{}; + }; + + enum ShaderStage + { + SHADER_STAGE_VERTEX, + SHADER_STAGE_FRAGMENT + }; + enum ShaderType { LINE, @@ -218,17 +358,45 @@ namespace anm2ed::resource::shader {VERTEX, TEXTURE_FRAGMENT}, {AXIS_VERTEX, FRAGMENT}, {GRID_VERTEX, GRID_FRAGMENT}}; + + UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); + UniformBinding uniform_binding_get(std::string_view); + std::string_view uniform_binding_value_get(UniformBinding); + std::string_view uniform_binding_label_get(UniformBinding); + UniformValueType uniform_value_type_get(GLenum); + std::string_view uniform_value_type_label_get(UniformValueType); + bool is_uniform_value_editable(UniformValueType); + bool is_uniform_value_vector(UniformValueType); + bool is_uniform_binding_valid(UniformBinding, UniformValueType); + void uniform_value_parse(Uniform&, std::string_view); + std::string uniform_value_string_get(const Uniform&); + std::string gles_convert(std::string_view, ShaderStage); + std::string gles_fragment_convert(std::string_view); + std::string gles_vertex_convert(std::string_view); } namespace anm2ed::resource { + struct ShaderCompileResult + { + GLuint id{}; + std::string output{}; + std::vector uniforms{}; + bool isCompiled{}; + bool isLinked{}; + }; + + ShaderCompileResult shader_compile(const char*, const char*); + class Shader { public: GLuint id{}; + std::vector uniforms{}; Shader(); Shader(const char*, const char*); + Shader(Shader&&) noexcept; Shader& operator=(Shader&&) noexcept; ~Shader(); bool is_valid() const; diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index b4ed9ec..901d87e 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -48,6 +48,7 @@ namespace anm2ed X(BASIC_CROP, "Crop", "Recortar", "Обрезать", "裁剪", "자르기") \ X(BASIC_CUT, "Cut", "Cortar", "Вырезать", "剪切", "잘라내기") \ X(BASIC_DEFAULT, "Default", "Predeterminado", "По умолчанию", "默认", "기본값") \ + X(BASIC_DISABLED, "Disabled", "Desactivado", "Отключено", "禁用", "비활성화") \ X(BASIC_DUPLICATE, "Duplicate", "Duplicar", "Дублировать", "拷贝", "복제") \ X(BASIC_DURATION, "Duration", "Duracion", "Продолжительность", "时长", "유지 시간") \ X(BASIC_ENABLED, "Enabled", "Activado", "Включено", "开启", "활성화") \ @@ -107,6 +108,7 @@ namespace anm2ed X(EDIT_ADD_ITEM, "Add Item", "Añadir Item", "Добавить предмет", "添加物品", "항목 추가") \ X(EDIT_ADD_LAYER, "Add Layer", "Añadir Capa", "Добавить слой", "添加动画层", "레이어 추가") \ X(EDIT_ADD_NULL, "Add Null", "Añadir Null", "Добавить нуль", "添加Null", "Null 추가") \ + X(EDIT_ADD_OVERLAY, "Add Overlay", "Add Overlay", "Add Overlay", "Add Overlay", "Add Overlay") \ X(EDIT_ADD_SPRITESHEET, "Add Spritesheet", "Añadir Spritesheet", "Добавить спрайт-лист", "添加图集", "스프라이트 시트 추가") \ X(EDIT_ADD_SOUND, "Add Sound", "Añadir Sonido", "Добавить звук", "添加声音", "사운드 추가") \ X(EDIT_ADD_TRIGGER_SOUND, "Add Trigger Sound", "Añadir Sonido del Trigger", "Добавить звук триггера", "添加事件触发器声音", "트리거 사운드 추가") \ @@ -128,6 +130,7 @@ namespace anm2ed X(EDIT_FIT_ANIMATION_LENGTH, "Fit Animation Length", "Encajar Largo de animacion", "Подогнать к длине анимации", "匹配动画时长", "애니메이션 길이 맞추기") \ X(EDIT_FPS, "FPS", "FPS", "FPS", "每秒帧数(FPS)", "FPS") \ X(EDIT_GROUP_ITEMS, "Group Item(s)", "Agrupar item(s)", "Сгруппировать элементы", "将项目分组", "항목 그룹화") \ + X(EDIT_REMOVE_GROUP, "Remove Group", "Eliminar grupo", "Удалить группу", "删除组", "그룹 삭제") \ X(EDIT_TOGGLE_GROUP_EXPANDED, "Toggle Group Expanded", "Alternar grupo expandido", "Развернуть/свернуть группу", "展开/折叠组", "그룹 펼침 전환") \ X(EDIT_FRAME_COLOR_OFFSET, "Frame Color Offset", "Offset de color de Frame", "Смещение цвета кадра", "帧颜色偏移", "프레임 색상 오프셋") \ X(EDIT_FRAME_CROP, "Frame Crop", "Recorte de Frame", "Обрезка кадра", "帧裁剪", "프레임 자르기") \ @@ -162,8 +165,10 @@ namespace anm2ed X(EDIT_PASTE_LAYERS, "Paste Layer(s)", "Pegar Capa(s)", "Вставить слои", "粘贴动画层", "레이어 붙여넣기") \ X(EDIT_PASTE_REGIONS, "Paste Region(s)", "Pegar Región(es)", "Вставить регионы", "粘贴区域", "영역 붙여넣기") \ X(EDIT_PASTE_NULLS, "Paste Null(s)", "Pegar Null(s)", "Вставить нули", "粘贴Null", "Null 붙여넣기") \ + X(EDIT_PASTE_OVERLAYS, "Paste Overlay(s)", "Paste Overlay(s)", "Paste Overlay(s)", "Paste Overlay(s)", "Paste Overlay(s)") \ X(EDIT_PASTE_SOUNDS, "Paste Sound(s)", "Pegar Sonido(s)", "Вставить звук(и)", "粘贴声音", "사운드 붙여넣기") \ X(EDIT_PASTE_SPRITESHEETS, "Paste Spritesheet(s)", "Pegar Spritesheet(s)", "Вставить спрайт-листы", "粘贴图集", "스프라이트 시트 붙여넣기") \ + X(EDIT_RELOAD_OVERLAYS, "Reload Overlay(s)", "Reload Overlay(s)", "Reload Overlay(s)", "Reload Overlay(s)", "Reload Overlay(s)") \ X(EDIT_RELOAD_SPRITESHEETS, "Reload Spritesheet(s)", "Recargar Spritesheet(s)", "Перезагрузить спрайт-листы", "重新加载图集", "스프라이트 시트 다시 불러오기") \ X(EDIT_RELOAD_SOUNDS, "Reload Sound(s)", "Recargar Sonido(s)", "Перезагрузить звук(и)", "重新加载声音", "사운드 다시 불러오기") \ X(EDIT_REMOVE_ANIMATIONS, "Remove Animation(s)", "Remover Animacion(es)", "Удалить анимации", "删除动画层", "애니메이션 제거") \ @@ -175,10 +180,13 @@ namespace anm2ed X(EDIT_REMOVE_UNUSED_NULLS, "Remove Unused Nulls", "Remover Nulls No Utilizados", "Удалить неизпользуемые нули", "删除未使用的Null", "미사용 Null 제거") \ X(EDIT_REMOVE_UNUSED_SOUNDS, "Remove Unused Sounds", "Remover Sonidos No Utilizados", "Удалить неизпользуемые звуки", "删除未使用的声音", "미사용 사운드 제거") \ X(EDIT_REMOVE_UNUSED_SPRITESHEETS, "Remove Unused Spritesheets", "Remover Spritesheets No Utilizadas", "Удалить неизпользуемые спрайт-листы", "删除未使用的图集", "미사용 스프라이트 시트 제거") \ + X(EDIT_REMOVE_OVERLAYS, "Remove Overlay(s)", "Remove Overlay(s)", "Remove Overlay(s)", "Remove Overlay(s)", "Remove Overlay(s)") \ X(EDIT_RENAME_GROUP, "Rename Group", "Renombrar grupo", "Переименовать группу", "重命名组", "그룹 이름 바꾸기") \ X(EDIT_RENAME_EVENT, "Rename Event", "Renombrar Evento", "Переименовать событие", "重命名事件", "이벤트 이름 바꾸기") \ X(EDIT_REPLACE_SPRITESHEET, "Replace Spritesheet", "Reemplazar Spritesheet", "Заменить спрайт-лист", "替换图集", "스프라이트 시트 교체") \ + X(EDIT_REPLACE_OVERLAY, "Replace Overlay", "Replace Overlay", "Replace Overlay", "Replace Overlay", "Replace Overlay") \ X(EDIT_REPLACE_SOUND, "Replace Sound", "Reemplazar Sonido", "Заменить звук", "替换声音", "사운드 교체") \ + X(EDIT_SET_OVERLAY_FILE_PATH, "Set Overlay File Path", "Set Overlay File Path", "Set Overlay File Path", "Set Overlay File Path", "Set Overlay File Path") \ X(EDIT_SET_SPRITESHEET_FILE_PATH, "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path") \ X(EDIT_SET_LAYER_PROPERTIES, "Set Layer Properties", "Establecer Propiedades de Capa", "Установить свойства слоя", "更改动画层属性", "레이어 속성 설정") \ X(EDIT_SET_REGION_PROPERTIES, "Set Region Properties", "Establecer propiedades de región", "Установить свойства региона", "更改区域属性", "영역 속성 설정") \ @@ -211,6 +219,7 @@ namespace anm2ed X(FORMAT_LOOP, "Loop: {0}", "Loop: {0}", "Цикл: {0}", "循环: {0}", "반복: {0}") \ X(FORMAT_NOT_SAVED, "{0} [Not Saved]", "{0} [Not Saved]", "{0} [Не сохранено]", "{0} [未保存]", "{0} [저장되지 않음]") \ X(FORMAT_NULL, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ + X(FORMAT_OVERLAY, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ X(FORMAT_PIVOT, "Pivot: ({0}, {1})", "Pivote", "Точка вращения: ({0}, {1})", "枢轴: ({0}, {1})", "중심점: ({0}, {1})") \ X(FORMAT_POSITION, "Position: ({0}, {1})", "Posicion: ({0}, {1})", "Позиция: ({0}, {1})", "位置: ({0}, {1})", "위치: ({0}, {1})") \ X(FORMAT_POSITION_SPACED, "Position: ({0:3}, {1:3})", "Posicion: ({0:3}, {1:3})", "Позиция: ({0:3}, {1:3})", "位置: ({0:3}, {1:3})", "위치: ({0:3}, {1:3})") \ @@ -243,7 +252,7 @@ namespace anm2ed X(LABEL_ANIMATION_LENGTH, "Animation Length", "Duracion de Animacion", "Длина анимации", "动画时长", "애니메이션 길이") \ X(LABEL_ANIMATION_PREVIEW_WINDOW, "Animation Preview###Animation Preview", "Vista Previa de Animacion###Animation Preview", "Предпросмотр анимации###Animation Preview", "动画预放###Animation Preview", "애니메이션 프리뷰###Animation Preview") \ X(LABEL_APPEND_FRAMES, "Append Frames", "Anteponer Frames", "Добавить кадры к концу", "在后面添加帧", "뒷프레임에 추가") \ - X(LABEL_APPLICATION_NAME, "Anm2Ed Version 2.5", "Anm2Ed Version 2.5", "Anm2Ed Версия 2.5", "Anm2Ed 2.5版本", "Anm2Ed 버전 2.5") \ + X(LABEL_APPLICATION_NAME, "Anm2Ed", "Anm2Ed", "Anm2Ed", "Anm2Ed", "Anm2Ed") \ X(LABEL_AUTHOR, "Author", "Autor", "Автор", "制作者", "작성자") \ X(LABEL_AUTOSAVE, "Autosave", "Autoguardado", "Автосохранение", "自动保存", "자동저장") \ X(LABEL_AXES, "Axes", "Ejes", "Оси", "坐标轴", "가로/세로 축") \ @@ -252,6 +261,7 @@ namespace anm2ed X(LABEL_BAKE_INTO_OTHER_FRAMES, "Bake into Other Frames", "Bake en otros frames", "Запечь в другие кадры", "烘焙到其他帧", "다른 프레임에 베이크") \ X(LABEL_BAKE_MATCH_ROOT_INTERPOLATION, "Bake other frames to match interpolation", "Bake otros frames para coincidir con interpolación", "Запечь другие кадры для соответствия интерполяции", "烘焙其他帧以匹配插值", "보간에 맞게 다른 프레임 베이크") \ X(LABEL_BAKE_USE_ROOT_PIVOT, "Use root pivot", "Usar pivote root", "Использовать корневой пивот", "使用根枢轴", "Root 중심점 사용") \ + X(LABEL_BINDING, "Binding", "Binding", "Binding", "Binding", "Binding") \ X(LABEL_SPLIT, "Split", "Dividir", "Разделить", "拆分", "분할") \ X(LABEL_BORDER, "Border", "Borde", "Границы", "边框", "경계선") \ X(LABEL_CHANGE_ALL_FRAME_PROPERTIES, "Change All Frame Properties", "Cambiar todas las propiedades de frame", "Изменить все свойства кадра", "更改所有帧属性", "모든 프레임 속성 변경") \ @@ -265,6 +275,7 @@ namespace anm2ed X(LABEL_REGIONS, "Regions", "Regiones", "Регионы", "区域", "영역") \ X(LABEL_KEEP_REDUNDANT_FRAME_REGION_VALUES, "Keep redundant frame information for frames with regions", "Mantener información redundante en frames con regiones", "Сохранять избыточные данные кадров с регионами", "保留带区域帧的冗余信息", "영역이 있는 프레임의 중복 정보 유지") \ X(LABEL_BAKE_SPECIAL_INTERPOLATED_FRAMES_ON_SAVE, "Automatically bake frames with special interpolation modes", "Hornear frames con interpolación especial al guardar", "Запекать кадры со специальной интерполяцией при сохранении", "保存时烘焙特殊插值帧", "저장 시 특수 보간 프레임 베이크") \ + X(LABEL_BAKE_GROUP_FRAMES_ON_SAVE, "Bake frames inside groups if applicable", "Hornear frames dentro de grupos si corresponde", "Запекать кадры внутри групп при необходимости", "适用时烘焙组内帧", "필요 시 그룹 안의 프레임 베이크") \ X(LABEL_CUSTOM_RANGE, "Custom Range", "Rango Personalizado", "Пользовательский диапазон", "自定义范围", "길이 맞춤설정") \ X(LABEL_DELETE, "Delete", "Borrar", "Удалить", "删除", "삭제") \ X(LABEL_DELETE_ANIMATIONS_AFTER, "Delete Animations After", "Borrar Animaciones Despues", "Удалить анимации после", "删除之后的动画", "기존 애니메이션 삭제") \ @@ -285,11 +296,13 @@ namespace anm2ed X(LABEL_EXPLORE_XML_LOCATION, "Explore XML Location", "Explorar Localizacion de XML", "Открыть местоположение XML", "探索XML位置", "XML 경로로 탐색기 열기") \ X(LABEL_FFMPEG_PATH, "FFmpeg Path", "Localizacion de FFmpeg", "Путь к FFmpeg", "FFmpeg路径", "FFmpeg 경로") \ X(LABEL_FILE_MENU, "File", "Archivo", "Файл", "文件", "파일") \ + X(LABEL_FILES, "Files", "Archivos", "Файлы", "文件", "파일") \ X(LABEL_FIT, "Fit", "Encajar", "Подогнать по размеру", "匹配", "맞추기") \ X(LABEL_FIT_ANIMATION_LENGTH, "Fit Animation Length", "Encajar Largo de animacion", "Подогнать к длине анимации", "匹配动画时长", "애니메이션 길이 맞추기") \ X(LABEL_FLIP_X, "Flip X", "Invertir X", "Отразить по X", "X轴翻转", "수평 뒤집기") \ X(LABEL_FLIP_Y, "Flip Y", "Invertir Y", "Отразить по Y", "Y轴翻转", "수직 뒤집기") \ X(LABEL_FORMAT, "Format", "Formato", "Формат", "格式", "파일 포맷") \ + X(LABEL_FRAGMENT, "Fragment", "Fragment", "Fragment", "Fragment", "Fragment") \ X(LABEL_FPS, "FPS", "FPS", "FPS", "FPS", "FPS") \ X(LABEL_FRAME_PROPERTIES_WINDOW, "Frame Properties###Frame Properties", "Propiedades de Frame###Frame Properties", "Свойства кадра###Frame Properties", "帧属性###Frame Properties", "프레임 속성###Frame Properties") \ X(LABEL_GENERATE, "Generate", "Generar", "Сгенерировать", "生成", "생성") \ @@ -300,6 +313,7 @@ namespace anm2ed X(LABEL_GENERATE_REGIONS_FROM_ANIMATIONS, "Generate Regions from Animations", "Generar regiones desde animaciones", "Создать регионы из анимаций", "从动画生成区域", "애니메이션에서 영역 생성") \ X(LABEL_GENERATE_ROWS, "Rows", "Filas", "Ряды", "行", "행") \ X(LABEL_GENERATE_START_POSITION, "Start Position", "Poscicion de Inicio", "Начальная позиция", "起始位置", "시작 위치") \ + X(LABEL_GENERAL, "General", "General", "General", "General", "General") \ X(LABEL_ALL, "All", "Todo", "Все", "全部", "전체") \ X(LABEL_ALL_ANIMATIONS, "All Animations", "Todas las Animaciones", "Все анимации", "所有动画", "모든 애니메이션") \ X(LABEL_HELP_MENU, "Help", "Ayuda", "Помощь", "帮助", "도움말") \ @@ -334,6 +348,10 @@ namespace anm2ed X(LABEL_MANAGER_NULL_PROPERTIES, "Null Properties", "Propiedades Null", "Свойства нуля", "Null属性", "Null 속성") \ X(LABEL_MANAGER_RENDERING_PROGRESS, "Rendering...", "Renderizando...", "Рендеринг...", "渲染中...", "렌더링 중...") \ X(LABEL_MERGE, "Merge", "Combinar", "Соединить", "合并", "병합") \ + X(LABEL_MERGE_PRESET, "Preset", "Preset", "Preset", "Preset", "Preset") \ + X(LABEL_MERGE_PRESET_APPEND_AS_NEW, "Append as New", "Append as New", "Append as New", "Append as New", "Append as New") \ + X(LABEL_MERGE_PRESET_MERGE_BY_NAME, "Merge by Name", "Merge by Name", "Merge by Name", "Merge by Name", "Merge by Name") \ + X(LABEL_MERGE_PRESET_REPLACE_MATCHING, "Replace Matching", "Replace Matching", "Replace Matching", "Replace Matching", "Replace Matching") \ X(LABEL_MERGE_SPRITESHEETS_APPEND_RIGHT, "Top Right", "Arriba a la derecha", "Сверху справа", "右上", "우측 상단") \ X(LABEL_MERGE_SPRITESHEETS_APPEND_BOTTOM, "Bottom Left", "Abajo a la izquierda", "Снизу слева", "左下", "좌측 하단") \ X(LABEL_MERGE_MAKE_SPRITESHEET_REGIONS, "Make Spritesheet Regions", "Crear regiones de spritesheet", "Создать регионы спрайт-листа", "生成图集区域", "스프라이트 시트 영역 만들기") \ @@ -349,6 +367,7 @@ namespace anm2ed X(LABEL_OUTPUT_DIRECTORY, "Directory", "Directorio", "Директория", "目录", "디렉터리") \ X(LABEL_OUTPUT_PATH, "Path", "Ruta", "Путь", "路径", "경로") \ X(LABEL_OVERLAY, "Overlay", "Overlay", "Наложение", "动画叠加", "오버레이") \ + X(LABEL_OVERLAYS_WINDOW, "Overlays###Overlays", "Overlays###Overlays", "Overlays###Overlays", "Overlays###Overlays", "Overlays###Overlays") \ X(LABEL_OVERWRITE_CONFIRMATION, "Are you sure? This will overwrite the existing file.", "¿Estas Seguro? Esto sobreescribira el archivo existente.", "Вы уверены? Это перезапишет существующий файл.", "你确定吗? 这样会覆盖原本的文件.", "저장하시겠습니까? 기존 파일을 덮어쓰게 됩니다.") \ X(LABEL_OVERWRITE_WARNING, "Overwrite Warning", "Alerta de Sobreescribir", "Предупреждение о перезаписи", "覆盖提醒", "덮어쓰기 경고") \ X(LABEL_PAUSE, "Pause", "Pausar", "Пауза", "暂停", "일시정지") \ @@ -357,7 +376,6 @@ namespace anm2ed X(LABEL_PLAYBACK_ALWAYS_LOOP, "Always Loop", "Siempre Loopear", "Всегда воспроизводить циклично", "持续循环", "항상 반복") \ X(LABEL_PLAYBACK_MENU, "Playback", "Reproduccion", "Возпроизведение", "回放", "재생") \ X(LABEL_PREPEND_FRAMES, "Prepend Frames", "Anteponer Frames", "Добавить кадры", "在前面插入帧", "뒷프레임에 추가") \ - X(LABEL_RAW, "Raw", "En Crudo", "Необработанный", "原始", "Raw만") \ X(LABEL_RECT, "Rect", "Rect", "Прямоугольник", "矩形", "사각형") \ X(LABEL_RENDER, "Render", "Renderizar", "Рендер", "渲染", "렌더링") \ X(LABEL_REPEAT_DELAY, "Repeat Delay (seconds)", "Repetir Delay (segundos)", "Задержка повторения (секунды)", "键盘按键重复延迟 (秒)", "반복 입력 지연 시간 (초)") \ @@ -377,6 +395,14 @@ namespace anm2ed X(LABEL_SOUND, "Sound", "Sonido", "Звук", "声音", "사운드") \ X(LABEL_SOUNDS, "Sounds", "Sonidos", "Звук", "声音", "사운드") \ X(LABEL_SOUNDS_WINDOW, "Sounds###Sounds", "Sonidos###Sounds", "Звук###Sounds", "声音###Sounds", "사운드###Sounds") \ + X(LABEL_SHADERS_WINDOW, "Shaders###Shaders", "Shaders###Shaders", "Shaders###Shaders", "Shaders###Shaders", "Shaders###Shaders") \ + X(LABEL_SHADER_COMPILE_FAILED, "Shader compilation failed.", "Shader compilation failed.", "Shader compilation failed.", "Shader compilation failed.", "Shader compilation failed.") \ + X(LABEL_SHADER_COMPILE_SUCCEEDED, "Shader compilation succeeded.", "Shader compilation succeeded.", "Shader compilation succeeded.", "Shader compilation succeeded.", "Shader compilation succeeded.") \ + X(LABEL_SHADER_LINK_FAILED, "Shader linking failed.", "Shader linking failed.", "Shader linking failed.", "Shader linking failed.", "Shader linking failed.") \ + X(LABEL_SHADER_LINK_SUCCEEDED, "Shader linking succeeded.", "Shader linking succeeded.", "Shader linking succeeded.", "Shader linking succeeded.", "Shader linking succeeded.") \ + X(LABEL_SHADER_PATH_EMPTY, "Shader path is empty: {0}", "Shader path is empty: {0}", "Shader path is empty: {0}", "Shader path is empty: {0}", "Shader path is empty: {0}") \ + X(LABEL_SHADER_READ_FAILED, "Failed to read shader file: {0}", "Failed to read shader file: {0}", "Failed to read shader file: {0}", "Failed to read shader file: {0}", "Failed to read shader file: {0}") \ + X(LABEL_SHADER_RELOAD_NEEDED, "Shader changed; reload to apply.", "Shader changed; reload to apply.", "Shader changed; reload to apply.", "Shader changed; reload to apply.", "Shader changed; reload to apply.") \ X(LABEL_SOURCE, "Source", "Fuente", "Източник", "动画层来源", "소스") \ X(LABEL_SPRITESHEET, "Spritesheet", "Spritesheet", "Спрайт-лист", "图集", "스프라이트 시트") \ X(LABEL_SPRITESHEETS_WINDOW, "Spritesheets###Spritesheets", "Spritesheets###Spritesheets", "Спрайт-листы###Spritesheets", "图集###Spritesheets", "스프라이트 시트###Spritesheets") \ @@ -406,9 +432,13 @@ namespace anm2ed X(LABEL_TO_SELECTED_FRAMES, "To Selected Frames", "A Frames Selecionados", "К выбранным кадрам", "跳到所选的帧", "선택한 프레임에 맞춤") \ X(LABEL_TRANSPARENT, "Transparent", "Transparentes", "Прозрачный", "透明", "투명도") \ X(LABEL_TYPE, "Type", "Tipo", "Тип", "类型", "유형") \ + X(LABEL_UNIFORMS, "Uniforms", "Uniforms", "Uniforms", "Uniforms", "Uniforms") \ X(LABEL_UI_SCALE, "UI Scale", "Escala de la Interfaz", "Размер UI", "界面缩放", "UI 비율") \ + X(LABEL_USE_ANIMATION_BOUNDS, "Use Animation Bounds", "Use Animation Bounds", "Use Animation Bounds", "Use Animation Bounds", "Use Animation Bounds") \ X(LABEL_USE_DEFAULT_SETTINGS, "Use Default Settings", "Usar Opciones Predeterminadas", "Изпользовать настройки по умолчанию", "使用默认设置", "기본값으로 사용") \ + X(LABEL_USE_ISOLATED_ANIMATION, "Use Isolated Animation", "Use Isolated Animation", "Use Isolated Animation", "Use Isolated Animation", "Use Isolated Animation") \ X(LABEL_VALUE_COLUMN, "Value", "Valor", "Значение", "数值", "값") \ + X(LABEL_VERTEX, "Vertex", "Vertex", "Vertex", "Vertex", "Vertex") \ X(LABEL_VSYNC, "Vsync", "Vsync", "Вертикальная синхронизация (V-sync)", "垂直同步", "수직 동기화") \ X(LABEL_WELCOME_DESCRIPTION, "Select a recent file or open a new or existing document. You can also drag and drop files into the window to open them.", "Selecciona un archivo reciente o abre un documento existente o nuevo. También puedes arrastrar y soltar archivos a la ventana para abrirlos.", "Выберите недавний файл или откройте новый или существующий документ. Вы также можете перетащить файлы в это окно, чтобы их открыть.", "选择最近的文件, 或打开新的/已有的文档. 你也可以将文件拖拽到窗口中以打开它们.", "최근 파일을 선택하거나 새 파일 또는 기존 파일을 엽니다. 파일을 여기로 드래그하여 열 수 있습니다.") \ X(LABEL_WELCOME_RESTORE_POPUP, "Restore", "Restaurar", "Восстановиь", "恢复", "복원") \ @@ -486,6 +516,7 @@ namespace anm2ed X(TOAST_DESERIALIZE_LAYERS_FAILED, "Failed to deserialize layer(s):", "Falla al deserializar capas(s):", "Не удалось десериализировать слои: {0}", "反序列化动画层失败: {0}", "레이어 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_REGIONS_FAILED, "Failed to deserialize region(s): {0}", "Falla al deserializar región(es): {0}", "Не удалось десериализировать регионы: {0}", "反序列化区域失败: {0}", "영역 역직렬화 실패: {0}") \ X(TOAST_DESERIALIZE_NULLS_FAILED, "Failed to deserialize null(s): {0}", "Falla al deserializar null(s): {0}", "Не удалось десериализировать нули: {0}", "反序列化Null失败: {0}", "Null 역직렬화 실패: {0}") \ + X(TOAST_DESERIALIZE_OVERLAYS_FAILED, "Failed to deserialize overlay(s): {0}", "Failed to deserialize overlay(s): {0}", "Failed to deserialize overlay(s): {0}", "Failed to deserialize overlay(s): {0}", "Failed to deserialize overlay(s): {0}") \ X(TOAST_DESERIALIZE_SPRITESHEETS_FAILED, "Failed to deserialize spritesheet(s): {0}", "Falla al deserializar spritesheet(s): {0}", "Не удалось десериализировать спрайт-листы: {0}", "反序列化图集失败: {0}", "스프라이트 시트 역직렬화 실패: {0}") \ X(TOAST_EXPORT_RENDERED_ANIMATION, "Exported rendered animation to: {0}", "Se ha exportado la animacion renderizada a: {0}", "Рендерированные анимации экспортированы в: {0}", "渲染动画导出至: {0}", "{0}에 렌더링 된 애니메이션을 내보내기 했습니다.") \ X(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, "Could not output rendered animation: {0}", "No se pudo emitir la animacion renderizada: {0}", "Не удалось вывести рендерированную анимацию: {0}", "无法输出渲染动画: {0}", "{0}에 렌더링 된 애니메이션을 내보내기 할 수 없습니다.") \ @@ -493,6 +524,8 @@ namespace anm2ed X(TOAST_EXPORT_RENDERED_FRAMES_FAILED, "Could not export frames to: {0}", "No se pdo exportar Frames a: {0}", "Не удалось экспортировать кадры в: {0}", "无法导出帧至: {0}", "프레임을 내보내기 할 수 없습니다. {0}") \ X(TOAST_EXPORT_SPRITESHEET, "Exported spritesheet to: {0}", "Se ha exportado spritesheet a: {0}", "Спрайт-лист экспортирован в: {0}", "导出图集至: {0}", "{0}에 스프라이트 시트를 내보내기 했습니다.") \ X(TOAST_EXPORT_SPRITESHEET_FAILED, "Could not export spritesheet to: {0}", "No se pudo exportar spritesheet a: {0}", "Не удалось экспортировать спрайт-лист в: {0}", "无法导出图集至: {0}", "{0}에 스프라이트 시트를 내보내기 할 수 없습니다.") \ + X(TOAST_OVERLAY_INIT_FAILED, "Failed to initialize overlay: {0}", "Failed to initialize overlay: {0}", "Failed to initialize overlay: {0}", "Failed to initialize overlay: {0}", "Failed to initialize overlay: {0}") \ + X(TOAST_OVERLAY_INITIALIZED, "Initialized overlay #{0}: {1}", "Initialized overlay #{0}: {1}", "Initialized overlay #{0}: {1}", "Initialized overlay #{0}: {1}", "Initialized overlay #{0}: {1}") \ X(TOAST_ADD_SPRITESHEET_FAILED, "Failed to add spritesheet! Open a document first.", "¡Error a añadir spritesheet! Abre un documento primero.", "Не удалось добавить спрайт-лист! Сначала откройте документ.", "无法添加图集!请先打开文档。", "스프라이트 시트를 추가할 수 없습니다! 먼저 문서를 여세요.") \ X(TOAST_ADD_SOUND_FAILED, "Failed to add sound! Open a document first.", "¡Error al añadir sonido! Abre un documento primero.", "Не удалось добавить звук! Сначала откройте документ.", "无法添加声音!请先打开文档。", "사운드를 추가할 수 없습니다! 먼저 문서를 여세요.") \ X(TOAST_INVALID_FFMPEG, "Unable to run FFmpeg. Make sure the executable exists, has the proper permissions, and is a valid FFmpeg executable.", "No se pudo ejecutar FFmpeg. Asegúrate de que el ejecutable exista, tenga los permisos adecuados y sea un FFmpeg válido.", "Не удалось запустить FFmpeg. Убедитесь, что исполняемый файл существует, имеет нужные права и является корректным исполняемым FFmpeg.", "无法运行 FFmpeg。请确保可执行文件存在,具有正确的权限,并且是有效的 FFmpeg 可执行文件。", "FFmpeg을 실행할 수 없습니다. 실행 파일이 존재하고 올바른 권한을 가지며 유효한 FFmpeg 실행 파일인지 확인하세요.") \ @@ -504,6 +537,7 @@ namespace anm2ed X(TOAST_REDO, "Redo: {0}", "Rehacer: {0}", "Повтор: {0}", "重做: {0}", "다시 실행: {0}") \ X(ERROR_FILE_NOT_FOUND, "File not found!", "¡Archivo no encontrado!", "Файл не найден!", "找不到文件!", "파일을 찾을 수 없습니다!") \ X(ERROR_FILE_PERMISSIONS, "File does not have write permissions!", "¡El archivo no tiene permisos de escritura!", "У файла нет прав на запись!", "文件没有写入权限!", "파일에 쓰기 권한이 없습니다!") \ + X(TOAST_RELOAD_OVERLAY, "Reloaded overlay #{0}: {1}", "Reloaded overlay #{0}: {1}", "Reloaded overlay #{0}: {1}", "Reloaded overlay #{0}: {1}", "Reloaded overlay #{0}: {1}") \ X(TOAST_RELOAD_SPRITESHEET, "Reloaded spritesheet #{0}: {1}", "Se ha recargado spritesheet #{0}: {1}", "Спрайт-лист #{0} перезагружен: {1}", "重新加载了图集 #{0}: {1}", "{0}번 스프라이트 시트 다시 불러옴: {1}") \ X(TOAST_MERGE_SPRITESHEETS, "Merged selected spritesheets.", "Spritesheets seleccionados combinados.", "Выбранные спрайт-листы объединены.", "已合并所选图集。", "선택된 스프라이트 시트를 병합했습니다.") \ X(TOAST_MERGE_SPRITESHEETS_FAILED, "Failed to merge selected spritesheets.", "No se pudieron combinar los spritesheets seleccionados.", "Не удалось объединить выбранные спрайт-листы.", "合并所选图集失败。", "선택된 스프라이트 시트 병합에 실패했습니다.") \ @@ -511,11 +545,15 @@ namespace anm2ed X(TOAST_PACK_SPRITESHEET_FAILED, "Failed to pack spritesheet.", "No se pudo empaquetar el spritesheet.", "Не удалось упаковать спрайт-лист.", "图集打包失败。", "스프라이트 시트 패킹에 실패했습니다.") \ X(TOAST_RELOAD_SOUND, "Reloaded sound #{0}: {1}", "Se ha recargado sonido #{0}: {1}", "Звук #{0} перезагружен: {1}", "重新加载了声音 #{0}: {1}", "{0}번 사운드 다시 불러옴: {1}") \ X(TOAST_SCAN_AND_SET_REGIONS, "Matched regionless frames to candidate regions.", "Se emparejaron frames sin region con regiones candidatas.", "Кадры без региона сопоставлены с подходящими регионами.", "已将无区域帧匹配到候选区域。", "영역이 없는 프레임을 후보 영역에 매칭했습니다.") \ + X(TOAST_REMOVE_OVERLAY, "Removed overlay #{0}: {1}", "Removed overlay #{0}: {1}", "Removed overlay #{0}: {1}", "Removed overlay #{0}: {1}", "Removed overlay #{0}: {1}") \ X(TOAST_REMOVE_SPRITESHEET, "Removed spritesheet #{0}: {1}", "Se ha removido spritesheet #{0}: {1}", "Спрайт-лист #{0} удален: {1}", "去除了图集 #{0}: {1}", "{0}번 스프라이트 시트 제거됨: {1}") \ + X(TOAST_REPLACE_OVERLAY, "Replaced overlay #{0}: {1}", "Replaced overlay #{0}: {1}", "Replaced overlay #{0}: {1}", "Replaced overlay #{0}: {1}", "Replaced overlay #{0}: {1}") \ X(TOAST_REPLACE_SPRITESHEET, "Replaced spritesheet #{0}: {1}", "Se ha reemplazado spritesheet #{0}: {1}", "Спрайт-лист #{0} заменен: {1}", "替换了图集 #{0}: {1}", "{0}번 스프라이트 시트 교체됨: {1}") \ X(TOAST_REPLACE_SOUND, "Replaced sound #{0}: {1}", "Se ha reemplazado sonido #{0}: {1}", "Звук #{0} заменен: {1}", "已替换声音 #{0}: {1}", "{0}번 사운드 교체됨: {1}") \ X(TOAST_SAVE_DOCUMENT, "Saved document to: {0}", "Documento Guardado en: {0}", "Документ сохранен в: {0}", "保存文件至: {0}", "{0}에 파일을 저장했습니다.") \ X(TOAST_SAVE_DOCUMENT_FAILED, "Could not save document to: {0} ({1})", "No se pudo guardar el documento en: {0} ({1})", "Не удалось сохранить документ в: {0} ({1})", "无法保存文件至: {0} ({1})", "{0}에 파일을 저장할 수 없습니다.") \ + X(TOAST_SAVE_OVERLAY, "Saved overlay #{0}: {1}", "Saved overlay #{0}: {1}", "Saved overlay #{0}: {1}", "Saved overlay #{0}: {1}", "Saved overlay #{0}: {1}") \ + X(TOAST_SAVE_OVERLAY_FAILED, "Unable to save overlay #{0}: {1}", "Unable to save overlay #{0}: {1}", "Unable to save overlay #{0}: {1}", "Unable to save overlay #{0}: {1}", "Unable to save overlay #{0}: {1}") \ X(TOAST_SAVE_SPRITESHEET, "Saved spritesheet #{0}: {1}", "Spritesheet Guardada #{0}: {1}", "Спрайт-лист #{0} сохранен: {1}", "已保存图集 #{0}: {1}", "{1}에 {0}번 스프라이트 시트를 저장했습니다.") \ X(TOAST_SAVE_SPRITESHEET_FAILED, "Unable to save spritesheet #{0}: {1}", "No se pudo guardar spritesheet #{0}: {1}", "Не удалось сохранить спрайт-лист #{0}: {1}", "无法保存图集 #{0}: {1}", "{0}번 스프라이트 시트를 저장할 수 없습니다. {1}") \ X(TOAST_SOUNDS_DESERIALIZE_ERROR, "Failed to deserialize sound(s): {0}", "Error al deserializar sonido(s): {0}", "Не удалось десериализировать звуки: {0}", "反序列化声音失败: {0}", "사운드 역직렬화 실패: {0}") \ @@ -535,6 +573,7 @@ namespace anm2ed X(TOOLTIP_ADD_LAYER, "Add a layer.", "Añadir una capa.", "Добавить слой.", "添加一个动画层.", "레이어를 추가합니다.") \ X(TOOLTIP_ADD_NULL, "Add a null.", "Añadir Null.", "Добавить нуль.", "添加一个Null.", "Null을 추가합니다.") \ X(TOOLTIP_ADD_SPRITESHEET, "Add a new spritesheet.", "Añadir nueva spritesheet.", "Добавить новый спрайт-лист.", "添加一个新图集.", "새 스프라이트 시트를 추가합니다.") \ + X(TOOLTIP_ADD_OVERLAY, "Add a new overlay to the selected spritesheet.", "Add a new overlay to the selected spritesheet.", "Add a new overlay to the selected spritesheet.", "Add a new overlay to the selected spritesheet.", "Add a new overlay to the selected spritesheet.") \ X(TOOLTIP_ADD_VALUES, "Add the specified values onto each frame.\n(Boolean/mapped values will simply be set.)", "Añadir los valores especifiados a cada Frame.\n(Los valores booleanos/mapeados simplemente se estableceran.)", "Добавить указанные значения к каждому кадру.\n(Булевы/сопоставленные значения будут просто установлены.)", "将指定的数值添加到每一帧上. (布尔/映射值将直接被设置.)", "각 프레임의 속성에 지정한 값을 더합니다.\n(불리언/매핑 값은 그대로 설정됩니다.)") \ X(TOOLTIP_ADJUST, "Set the value of each specified value onto the frame's equivalent.", "Ajustar el valor de cada valor especificado a el equivalente del Frame.", "Установить значение каждого указанного значения к эквиваленту кадра.", "将每个指定的数值设置到对应帧的相等的属性上.", "지정된 각 값을 프레임의 대응 값으로 설정합니다.") \ X(TOOLTIP_ALL_ITEMS_VISIBLE, "All items are visible. Press to only show layers.", "Todos los items son visibles. Presiona solo para mostrar capas.", "Все предметы видимы. Нажмите, чтобы только показать слои.", "所有物品均可见. 点击即可仅显示动画层.", "모든 항목이 표시됩니다. 레이어만 표시하려면 누르세요.") \ @@ -562,14 +601,15 @@ namespace anm2ed X(TOOLTIP_CHANGE_ALL_NULLS, "The frame property changes will apply to null frames.", "Los cambios de propiedades de frame se aplicaran a los frames null.", "Изменения свойств кадра будут применены к нулевым кадрам.", "帧属性更改将应用于 Null 帧。", "프레임 속성 변경 사항을 Null 프레임에 적용합니다.") \ X(TOOLTIP_CENTER_VIEW, "Centers the view.", "Centra la vista.", "Центрирует вид.", "居中视角.", "미리보기 화면을 가운데에 맞춥니다.") \ X(TOOLTIP_CLOSE_SETTINGS, "Close without updating settings.", "Cerrar sin actualizar las configuraciones.", "Закрыть без обновления настройки.", "关闭但不保存设置.", "설정을 갱신하지 않고 닫습니다.") \ - X(TOOLTIP_SERIALIZE_GROUPS, "Serialize animation groups.\nThe Binding of Isaac: Rebirth does not support groups.", "Serializa grupos de animación.\nThe Binding of Isaac: Rebirth no admite grupos.", "Сериализует группы анимации.\nThe Binding of Isaac: Rebirth не поддерживает группы.", "序列化动画组。\nThe Binding of Isaac: Rebirth 不支持组。", "애니메이션 그룹을 직렬화합니다.\nThe Binding of Isaac: Rebirth는 그룹을 지원하지 않습니다.") \ - X(TOOLTIP_SERIALIZE_REGIONS, "Serialize spritesheet regions.\nThe Binding of Isaac: Rebirth does not support regions.", "Serializa regiones de spritesheet.\nThe Binding of Isaac: Rebirth no admite regiones.", "Сериализует регионы спрайт-листа.\nThe Binding of Isaac: Rebirth не поддерживает регионы.", "序列化图集区域。\nThe Binding of Isaac: Rebirth 不支持区域。", "스프라이트 시트 영역을 직렬화합니다.\nThe Binding of Isaac: Rebirth는 영역을 지원하지 않습니다.") \ - X(TOOLTIP_SERIALIZE_SOUNDS, "Serialize sounds.\nThe Binding of Isaac: Rebirth does not support sounds in Anm2 files.", "Serializa sonidos.\nThe Binding of Isaac: Rebirth no admite sonidos en archivos Anm2.", "Сериализует звуки.\nThe Binding of Isaac: Rebirth не поддерживает звуки в Anm2-файлах.", "序列化声音。\nThe Binding of Isaac: Rebirth 不支持 Anm2 文件中的声音。", "사운드를 직렬화합니다.\nThe Binding of Isaac: Rebirth는 Anm2 파일의 사운드를 지원하지 않습니다.") \ - X(TOOLTIP_KEEP_REDUNDANT_FRAME_REGION_VALUES, "Keep crop, size, and pivot values on frames with regions.\nThis saves information; The Binding of Isaac: Rebirth still needs these values.", "Mantiene los valores de recorte, tamaño y pivote en frames con regiones.\nEsto guarda información; The Binding of Isaac: Rebirth todavía necesita estos valores.", "Сохраняет значения обрезки, размера и точки вращения в кадрах с регионами.\nЭто сохраняет информацию; The Binding of Isaac: Rebirth всё равно нужны эти значения.", "保留带区域帧的裁剪、大小和枢轴值。\n这会保存信息;The Binding of Isaac: Rebirth 仍然需要这些值。", "영역이 있는 프레임의 자르기, 크기, 중심점 값을 유지합니다.\n이 정보는 저장됩니다; The Binding of Isaac: Rebirth에도 이 값들이 필요합니다.") \ - X(TOOLTIP_BAKE_SPECIAL_INTERPOLATED_FRAMES_ON_SAVE, "Bake frames with special interpolation modes only in the saved file.\nAnm2Ed restores them when loading, and the file works in The Binding of Isaac: Rebirth as-is.", "Hornea frames con modos de interpolación especial solo en el archivo guardado.\nAnm2Ed los restaura al cargar, y el archivo funciona en The Binding of Isaac: Rebirth tal cual.", "Запекает кадры со специальными режимами интерполяции только в сохраняемом файле.\nAnm2Ed восстанавливает их при загрузке, а файл сразу работает в The Binding of Isaac: Rebirth.", "仅在保存的文件中烘焙带特殊插值模式的帧。\nAnm2Ed 加载时会还原它们,文件可直接用于 The Binding of Isaac: Rebirth。", "저장되는 파일에서만 특수 보간 모드 프레임을 베이크합니다.\nAnm2Ed는 로드할 때 이를 복원하며, 파일은 The Binding of Isaac: Rebirth에서 그대로 작동합니다.") \ + X(TOOLTIP_KEEP_REDUNDANT_FRAME_REGION_VALUES, "Keep crop, size, and pivot values on frames with regions.\nIf disabled, The Binding of Isaac: Rebirth may have parsing or playback issues.", "Mantiene los valores de recorte, tamaño y pivote en frames con regiones.\nSi se desactiva, The Binding of Isaac: Rebirth puede tener problemas de análisis o reproducción.", "Сохраняет значения обрезки, размера и точки вращения в кадрах с регионами.\nЕсли отключить, в The Binding of Isaac: Rebirth возможны проблемы разбора или воспроизведения.", "保留带区域帧的裁剪、大小和枢轴值。\n如果禁用,The Binding of Isaac: Rebirth 可能出现解析或播放问题。", "영역이 있는 프레임의 자르기, 크기, 중심점 값을 유지합니다.\n끄면 The Binding of Isaac: Rebirth에서 파싱 또는 재생 문제가 생길 수 있습니다.") \ + X(TOOLTIP_BAKE_SPECIAL_INTERPOLATED_FRAMES_ON_SAVE, "Bake frames with special interpolation modes only in the saved file.\nIf disabled, The Binding of Isaac: Rebirth may have parsing or playback issues.", "Hornea frames con modos de interpolación especial solo en el archivo guardado.\nSi se desactiva, The Binding of Isaac: Rebirth puede tener problemas de análisis o reproducción.", "Запекает кадры со специальными режимами интерполяции только в сохраняемом файле.\nЕсли отключить, в The Binding of Isaac: Rebirth возможны проблемы разбора или воспроизведения.", "仅在保存的文件中烘焙带特殊插值模式的帧。\n如果禁用,The Binding of Isaac: Rebirth 可能出现解析或播放问题。", "저장되는 파일에서만 특수 보간 모드 프레임을 베이크합니다.\n끄면 The Binding of Isaac: Rebirth에서 파싱 또는 재생 문제가 생길 수 있습니다.") \ + X(TOOLTIP_BAKE_GROUP_FRAMES_ON_SAVE, "Bake child layer/null frames when their group root has non-default transform or color values.\nIf disabled, The Binding of Isaac: Rebirth may have parsing or playback issues.", "Hornea frames de capas/null hijos cuando la raíz del grupo tenga transformaciones o valores de color no predeterminados.\nSi se desactiva, The Binding of Isaac: Rebirth puede tener problemas de análisis o reproducción.", "Запекает дочерние кадры слоев/null, когда корень группы имеет нестандартные преобразования или цветовые значения.\nЕсли отключить, в The Binding of Isaac: Rebirth возможны проблемы разбора или воспроизведения.", "当组根具有非默认变换或颜色值时,烘焙子图层/null 帧。\n如果禁用,The Binding of Isaac: Rebirth 可能出现解析或播放问题。", "그룹 루트에 기본값이 아닌 변형 또는 색상 값이 있을 때 하위 레이어/null 프레임을 베이크합니다.\n끄면 The Binding of Isaac: Rebirth에서 파싱 또는 재생 문제가 생길 수 있습니다.") \ X(TOOLTIP_COLOR_OFFSET, "Change the color added onto the frame.", "Cambia el color añadido al Frame.", "Изменить цвет, который добавлен на кадр.", "更改覆盖在帧上的颜色.", "프레임에 더해지는 색을 변경합니다.") \ X(TOOLTIP_REGION, "Set the spritesheet region the frame will use.", "Establece la región del spritesheet que usará el frame.", "Установить регион спрайт-листа, который будет использовать кадр.", "设置帧将使用的图集区域.", "프레임이 사용할 스프라이트 시트 영역을 설정합니다.") \ X(TOOLTIP_REGION_PROPERTIES_ORIGIN, "Use a preset origin for the region.", "Usa un origen predefinido para la región.", "Использовать предустановленную точку отсчета для региона.", "为区域使用预设原点。", "영역에 사전 설정된 원점을 사용합니다.") \ + X(TOOLTIP_MERGE_PRESET_APPEND_AS_NEW, "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.") \ + X(TOOLTIP_MERGE_PRESET_MERGE_BY_NAME, "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.") \ + X(TOOLTIP_MERGE_PRESET_REPLACE_MATCHING, "Replace same-named animations and definitions with incoming content, and add anything missing.", "Replace same-named animations and definitions with incoming content, and add anything missing.", "Replace same-named animations and definitions with incoming content, and add anything missing.", "Replace same-named animations and definitions with incoming content, and add anything missing.", "Replace same-named animations and definitions with incoming content, and add anything missing.") \ X(TOOLTIP_COLUMNS, "Set how many columns the spritesheet will have.", "Ajusta cuantas columnas va a tener el spritesheet.", "Установить сколько колонн будет иметь спрайт-лист.", "设置图集有多少列.", "스프라이트 시트의 열 수를 설정합니다.") \ X(TOOLTIP_CROP, "Change the crop position the frame uses.", "Cambiar la poscicion de recortado que usa el Frame.", "Изменить позицию обрезки, которую использует кадр.", "更改当前帧的裁剪位置.", "프레임에 대응되는 스프라이트 시트를 어느 지점부터 사용할지 변경합니다.") \ X(TOOLTIP_CUSTOM_RANGE, "Toggle using a custom range for the animation.", "Alterna usando un rango personalizado para la animacion.", "Переключить использование пользовательского диапазона для анимации.", "切换是否让动画使用自定义区间.", "애니메이션에 사용자 지정 길이를 사용할지 정합니다.") \ @@ -642,7 +682,9 @@ namespace anm2ed X(TOOLTIP_POSITION, "Change the position of the frame.", "Cambia la posicion del Frame.", "Изменить позицию кадра.", "更改此帧的位置.", "프레임의 위치를 변경합니다.") \ X(TOOLTIP_PREVIEW_ZOOM, "Change the zoom of the preview.", "Cambia el zoom de la vista previa.", "Изменить масштаб предпросмотра.", "更改预览视图的缩放.", "미리보기의 줌을 변경합니다.") \ X(TOOLTIP_PREVIEW_TRANSPARENT, "Toggle the animation preview background being transparent.", "Alterna la transparencia del fondo de la vista previa de animacion.", "Переключить прозрачность фона предпросмотра анимации.", "切换动画预览背景是否透明.", "애니메이션 미리보기 배경을 투명하게 전환합니다.") \ - X(TOOLTIP_RAW, "Record only the raw animation; i.e., only its layers, to its bounds.", "Graba solo la animacion cruda; i. e., Solo sus capas.", "Записывать только «сырую» анимацию, т. е. только ее слои.", "仅保存原生动画; 比如只保存动画层.", "Raw 애니메이션만 녹화합니다. 즉, 레이어만 녹화합니다.") \ + X(TOOLTIP_USE_ANIMATION_BOUNDS, "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.", "Render using the animation's bounds instead of the preview viewport.") \ + X(TOOLTIP_USE_ISOLATED_ANIMATION, "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.", "Render only animation layers with a transparent background and preview helpers hidden.") \ + X(TOOLTIP_RELOAD_OVERLAYS, "Reloads the selected overlays.", "Reloads the selected overlays.", "Reloads the selected overlays.", "Reloads the selected overlays.", "Reloads the selected overlays.") \ X(TOOLTIP_RELOAD_SPRITESHEETS, "Reloads the selected spritesheets.", "Recarga la spritesheet seleccionada.", "Перезагружает выбранные спрайт-листы.", "重新加载所选图集.", "선택한 스프라이트 시트를 다시 불러옵니다.") \ X(TOOLTIP_RELOAD_SOUNDS, "Reloads the selected sounds.", "Recarga los sonidos seleccionados.", "Перезагружает выбранные звуки.", "重新加载所选声音.", "선택한 사운드를 다시 불러옵니다.") \ X(TOOLTIP_REMOVE_ANIMATION, "Remove the selected animation(s).", "Remueve la(s) animacion(es) seleccionada(s).", "Удалить выбранные анимации.", "去除所选动画.", "선택한 애니메이션을 제거합니다.") \ @@ -654,10 +696,12 @@ namespace anm2ed X(TOOLTIP_REMOVE_UNUSED_NULLS, "Remove unused nulls (i.e., ones not used in any animation.)", "Remueve nulls no utilizados (i. e., aquellos no usados en ninguna animacion.)", "Удалить неиспользуемые нули (т. е. нули, которые не используются ни одной анимацией.)", "去除未使用的Null (未被任何动画使用的那些.)", "사용되지 않는 Null(어떤 애니메이션에서도 사용되지 않는 것)을 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_SOUNDS, "Remove unused sounds (i.e., ones not used in any trigger.)", "Remueve sonidos no utilizados (i. e., aquellos no usados en ningun trigger.)", "Удалить неиспользуемые звуки (т. е. звуки, которые не используются ни одным триггером.)", "去除未使用的声音 (未被任何触发器使用的那些.)", "사용되지 않는 사운드(어떤 트리거에서도 사용되지 않는 것)를 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_SPRITESHEETS, "Remove all unused spritesheets (i.e., not used in any layer.).", "Remueve todos los spritesheets no utilizados (i. e., aquellos no usados en ninguna capa.)", "Удалить неиспользуемые спрайт-листы (т. е. те, которые не используются ни одним слоем.)", "去除未使用的图集 (未被任何动画层使用的那些.)", "사용되지 않는 모든 스프라이트 시트(어떤 레이어에서도 사용되지 않는 것)를 제거합니다.") \ + X(TOOLTIP_REMOVE_OVERLAYS, "Remove the selected overlays.", "Remove the selected overlays.", "Remove the selected overlays.", "Remove the selected overlays.", "Remove the selected overlays.") \ X(TOOLTIP_RENDER_BUTTON, "Render the animation using the current settings.", "Renderiza la animacion usando la configuracion actual", "Рендерировать анимацию, используя текущие настройки.", "应用当前设置去渲染动画.", "현재 설정으로 애니메이션을 렌더링합니다.") \ X(TOOLTIP_RENDER_TYPE, "Set the type of the output.", "Ajusta el tipo de la salida", "Установить тип вывода.", "设置输出的类型.", "출력 유형을 설정합니다.") \ X(TOOLTIP_REPEAT_DELAY, "Set how often, after repeating begins, key inputs will be fired.", "Ajusta que tanto, despues de que empieza la repeticion, seran disparadas las entradas clave.", "Установить, как часто после начала повторения будут срабатывать нажатия клавиш.", "更改键盘按键开启重复时, 重复的速率.", "반복 입력이 시작된 후 입력이 얼마나 자주 들어갈지 설정합니다.") \ X(TOOLTIP_REPLACE_SPRITESHEET, "Replace the selected spritesheet with a new one.", "Reemplaza la spritesheet seleccionada con una nueva.", "Заменить выбранный спрайт-лист на новый.", "替换所选旧图集为新图集.", "선택된 스프라이트 시트를 새 시트로 교체합니다.") \ + X(TOOLTIP_REPLACE_OVERLAY, "Replace the selected overlay with a new one.", "Replace the selected overlay with a new one.", "Replace the selected overlay with a new one.", "Replace the selected overlay with a new one.", "Replace the selected overlay with a new one.") \ X(TOOLTIP_REPLACE_SOUND, "Replace the selected sound with a new one.", "Reemplaza el sonido seleccionado con uno nuevo.", "Заменяет выбранный звук новым.", "用新的声音替换所选声音.", "선택한 사운드를 새 사운드로 교체합니다.") \ X(TOOLTIP_ROOT_TRANSFORM, "Root frames will transform the rest of the animation.", "Los Frames root transformaran el resto de la animacion.", "Корневые кадры трансформируют остаток анимации.", "与“根”有关的帧会跟随整个动画而变换.", "Root 프레임이 나머지 애니메이션을 변형합니다.") \ X(TOOLTIP_ROTATION, "Change the rotation of the frame.", "Cambia la rotacion del Frame.", "Изменить поворот кадра.", "更改此帧的旋转.", "프레임의 회전값을 변경합니다.") \ @@ -665,6 +709,7 @@ namespace anm2ed X(TOOLTIP_ROUND_SCALE, "Scale will be rounded to the nearest whole number.", "La escala sera aproximada al numero entero mas cercano.", "Масштаб будет округлен к самому близкому целому числу.", "缩放数值会被取整.", "비율을 가장 가까운 정수로 반올림합니다.") \ X(TOOLTIP_ROWS, "Set how many rows the spritesheet will have.", "Ajusta cuantas filas tendra el spritsheet.", "Установить сколько рядов будет иметь спрайт-лист.", "设置图集的行数量.", "스프라이트 시트의 행 수를 설정합니다.") \ X(TOOLTIP_SAVE_SPRITESHEETS, "Save the selected spritesheets.", "Guarda los spritesheets seleccionados.", "Сохранить выбранные спрайт-листы.", "保存所选图集.", "선택한 스프라이트 시트를 저장합니다.") \ + X(TOOLTIP_SAVE_OVERLAYS, "Save the selected overlays.", "Save the selected overlays.", "Save the selected overlays.", "Save the selected overlays.", "Save the selected overlays.") \ X(TOOLTIP_SCALE, "Change the scale of the frame, in percent.", "Cambia la escala del Frame, en porcentaje.", "Изменить масштаб кадра.", "修改此帧的缩放.", "프레임의 비율을 변경합니다.") \ X(TOOLTIP_SCALE_OUTPUT, "Set the output scale of the animation.", "Ajusta la escala de salida de la animacion.", "Установить масштаб анимации при выводе.", "设置输出动画的缩放.", "애니메이션의 출력 비율을 설정합니다.") \ X(TOOLTIP_SETTINGS_SAVE, "Use the configured settings.", "Usa las opciones configuradas.", "Использовать настроенные настройки.", "应用更改的设置.", "구성된 설정을 사용합니다.") \ diff --git a/src/settings.cpp b/src/settings.cpp index f14303e..1289f15 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -14,119 +14,150 @@ namespace anm2ed constexpr auto IMGUI_DEFAULT = R"( [Window][##DockSpace] Pos=0,54 -Size=1512,876 +Size=1918,1007 Collapsed=0 [Window][##Documents] Pos=0,22 -Size=1512,32 +Size=1918,32 Collapsed=0 +[Window][###Onionskin] +Pos=8,724 +Size=1902,329 +Collapsed=0 +DockId=0x00000016,1 + [Window][###Animation Preview] Pos=60,62 -Size=949,583 +Size=898,660 Collapsed=0 DockId=0x00000013,0 -[Window][###Onionskin] -Pos=8,647 -Size=1496,275 -Collapsed=0 -DockId=0x00000006,1 - [Window][###Sounds] -Pos=1364,62 -Size=140,128 +Pos=1166,62 +Size=744,305 Collapsed=0 DockId=0x0000000F,1 [Window][###Animations] -Pos=1364,192 -Size=64,453 +Pos=1166,369 +Size=179,353 Collapsed=0 DockId=0x00000011,0 [Window][###Events] -Pos=1011,402 -Size=351,243 +Pos=960,413 +Size=204,309 Collapsed=0 -DockId=0x0000000E,1 +DockId=0x00000006,1 [Window][###Frame Properties] -Pos=1011,62 -Size=351,338 +Pos=960,62 +Size=204,349 Collapsed=0 -DockId=0x0000000D,0 +DockId=0x00000005,0 [Window][###Layers] -Pos=1011,402 -Size=351,243 +Pos=960,413 +Size=204,309 Collapsed=0 -DockId=0x0000000E,0 +DockId=0x00000006,0 [Window][###Nulls] -Pos=1011,402 -Size=351,243 +Pos=960,413 +Size=204,309 Collapsed=0 -DockId=0x0000000E,2 +DockId=0x00000006,2 [Window][###Spritesheet Editor] Pos=60,62 -Size=949,583 +Size=898,660 Collapsed=0 DockId=0x00000013,1 [Window][###Spritesheets] -Pos=1364,62 -Size=140,128 +Pos=1166,62 +Size=744,305 Collapsed=0 DockId=0x0000000F,0 [Window][###Tools] Pos=8,62 -Size=50,583 +Size=50,660 Collapsed=0 -DockId=0x00000012,0 +DockId=0x00000004,0 [Window][###Welcome] Pos=0,54 -Size=1512,876 +Size=1918,1007 Collapsed=0 [Window][###Timeline] -Pos=8,647 -Size=1496,275 +Pos=8,724 +Size=1902,329 Collapsed=0 -DockId=0x00000006,0 +DockId=0x00000016,0 [Window][###Regions] -Pos=1430,192 -Size=74,453 +Pos=1347,369 +Size=563,353 Collapsed=0 DockId=0x00000014,0 +[Window][###Shaders] +Pos=1347,369 +Size=563,353 +Collapsed=0 +DockId=0x00000014,1 + +[Window][###Overlays] +Pos=1347,369 +Size=563,353 +Collapsed=0 +DockId=0x00000014,2 + +[Table][0xE5891919,5] +Column 0 Weight=1.3608 +Column 1 Weight=0.8522 +Column 2 Weight=0.7973 +Column 3 Weight=0.9897 +Column 4 Weight=0.5671 + +[Table][0xB03AD869,4] +Column 0 Weight=0.9635 +Column 1 Weight=0.6034 +Column 2 Weight=0.5742 +Column 3 Weight=1.8589 + +[Table][0x6BD17CEE,4] +Column 0 Weight=0.9451 +Column 1 Weight=0.5919 +Column 2 Weight=0.5823 +Column 3 Weight=1.8807 + [Docking][Data] -DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1496,860 Split=Y Selected=0x4EFD0020 - DockNode ID=0x00000005 Parent=0x123F8F08 SizeRef=1910,714 Split=X - DockNode ID=0x00000001 Parent=0x00000005 SizeRef=50,994 Selected=0x18A5FDB9 - DockNode ID=0x00000002 Parent=0x00000005 SizeRef=1850,994 Split=X Selected=0x4EFD0020 - DockNode ID=0x00000003 Parent=0x00000002 SizeRef=1001,994 Split=X Selected=0xDDB7ACD5 - DockNode ID=0x00000012 Parent=0x00000003 SizeRef=50,555 Selected=0xA82FD886 - DockNode ID=0x00000013 Parent=0x00000003 SizeRef=949,555 Selected=0xDDB7ACD5 - DockNode ID=0x00000004 Parent=0x00000002 SizeRef=899,994 Split=X Selected=0x4EFD0020 - DockNode ID=0x00000009 Parent=0x00000004 SizeRef=351,497 Split=Y Selected=0xCD8384B1 - DockNode ID=0x00000007 Parent=0x00000009 SizeRef=181,275 Selected=0x754E368F - DockNode ID=0x00000008 Parent=0x00000009 SizeRef=181,278 Split=Y Selected=0xA4818A79 - DockNode ID=0x0000000D Parent=0x00000008 SizeRef=342,414 Selected=0x6DE1CB13 - DockNode ID=0x0000000E Parent=0x00000008 SizeRef=342,298 Selected=0x64F6E1D7 - DockNode ID=0x0000000A Parent=0x00000004 SizeRef=546,497 Split=Y Selected=0x4EFD0020 - DockNode ID=0x0000000B Parent=0x0000000A SizeRef=459,303 Split=Y Selected=0xD302131E - DockNode ID=0x0000000F Parent=0x0000000B SizeRef=586,259 CentralNode=1 Selected=0xD302131E - DockNode ID=0x00000010 Parent=0x0000000B SizeRef=586,453 Split=X Selected=0x9B32B74A - DockNode ID=0x00000011 Parent=0x00000010 SizeRef=252,316 Selected=0x0ED5C382 - DockNode ID=0x00000014 Parent=0x00000010 SizeRef=292,316 Selected=0x9B32B74A - DockNode ID=0x0000000C Parent=0x0000000A SizeRef=459,250 Selected=0xC1986EE2 - DockNode ID=0x00000006 Parent=0x123F8F08 SizeRef=1910,275 Selected=0x597925B7 +DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 Split=Y Selected=0x4EFD0020 + DockNode ID=0x00000015 Parent=0x123F8F08 SizeRef=1902,660 Split=X + DockNode ID=0x00000004 Parent=0x00000015 SizeRef=50,991 Selected=0xA82FD886 + DockNode ID=0x00000012 Parent=0x00000015 SizeRef=1850,991 Split=X + DockNode ID=0x00000013 Parent=0x00000012 SizeRef=898,991 Selected=0xDDB7ACD5 + DockNode ID=0x00000003 Parent=0x00000012 SizeRef=950,991 Split=X + DockNode ID=0x00000001 Parent=0x00000003 SizeRef=50,994 Selected=0x18A5FDB9 + DockNode ID=0x00000002 Parent=0x00000003 SizeRef=1850,994 Split=X Selected=0x4EFD0020 + DockNode ID=0x00000009 Parent=0x00000002 SizeRef=204,497 Split=Y Selected=0xCD8384B1 + DockNode ID=0x00000007 Parent=0x00000009 SizeRef=181,275 Selected=0x754E368F + DockNode ID=0x00000008 Parent=0x00000009 SizeRef=181,278 Split=Y Selected=0xE42526D3 + DockNode ID=0x00000005 Parent=0x00000008 SizeRef=204,349 Selected=0x6DE1CB13 + DockNode ID=0x00000006 Parent=0x00000008 SizeRef=204,309 Selected=0xE42526D3 + DockNode ID=0x0000000A Parent=0x00000002 SizeRef=744,497 Split=Y Selected=0x4EFD0020 + DockNode ID=0x0000000B Parent=0x0000000A SizeRef=459,303 Split=Y Selected=0xD302131E + DockNode ID=0x0000000F Parent=0x0000000B SizeRef=586,305 CentralNode=1 Selected=0xD302131E + DockNode ID=0x00000010 Parent=0x0000000B SizeRef=586,353 Split=X Selected=0x9B32B74A + DockNode ID=0x00000011 Parent=0x00000010 SizeRef=179,293 Selected=0x0ED5C382 + DockNode ID=0x00000014 Parent=0x00000010 SizeRef=563,293 Selected=0x3732FDF0 + DockNode ID=0x0000000C Parent=0x0000000A SizeRef=459,250 Selected=0xC1986EE2 + DockNode ID=0x00000016 Parent=0x123F8F08 SizeRef=1902,329 Selected=0x597925B7 diff --git a/src/settings.hpp b/src/settings.hpp index e50a5f4..1fc1f4d 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -65,11 +65,9 @@ namespace anm2ed X(FILE_IS_AUTOSAVE, fileIsAutosave, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_WARN_OVERWRITE, fileIsWarnOverwrite, STRING_UNDEFINED, BOOL, true) \ X(FILE_SNAPSHOT_STACK_SIZE, fileSnapshotStackSize, STRING_UNDEFINED, INT, 50) \ - X(FILE_IS_SERIALIZE_GROUPS, fileIsSerializeGroups, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_SERIALIZE_REGIONS, fileIsSerializeRegions, STRING_UNDEFINED, BOOL, true) \ - X(FILE_IS_SERIALIZE_SOUNDS, fileIsSerializeSounds, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_KEEP_REDUNDANT_FRAME_REGION_VALUES, fileIsKeepRedundantFrameRegionValues, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_BAKE_SPECIAL_INTERPOLATED_FRAMES, fileIsBakeSpecialInterpolatedFrames, STRING_UNDEFINED, BOOL, true) \ + X(IS_FILE_BAKE_GROUP_FRAMES, isFileBakeGroupFrames, STRING_UNDEFINED, BOOL, true) \ \ X(KEYBOARD_REPEAT_DELAY, keyboardRepeatDelay, STRING_UNDEFINED, FLOAT, 0.300f) \ X(KEYBOARD_REPEAT_RATE, keyboardRepeatRate, STRING_UNDEFINED, FLOAT, 0.050f) \ @@ -201,7 +199,8 @@ namespace anm2ed X(RENDER_ROWS, renderRows, STRING_UNDEFINED, INT, 0) \ X(RENDER_COLUMNS, renderColumns, STRING_UNDEFINED, INT, 0) \ X(RENDER_FORMAT, renderFormat, STRING_UNDEFINED, PATH, "{}.png") \ - X(RENDER_IS_RAW_ANIMATION, renderIsRawAnimation, STRING_UNDEFINED, BOOL, true) \ + X(RENDER_IS_USE_ANIMATION_BOUNDS, renderIsUseAnimationBounds, STRING_UNDEFINED, BOOL, true) \ + X(RENDER_IS_USE_ISOLATED_ANIMATION, renderIsUseIsolatedAnimation, STRING_UNDEFINED, BOOL, false) \ X(RENDER_SCALE, renderScale, STRING_UNDEFINED, FLOAT, 1.0f) \ X(RENDER_FFMPEG_PATH, renderFFmpegPath, STRING_UNDEFINED, PATH, FFMPEG_PATH_DEFAULT) @@ -274,7 +273,9 @@ namespace anm2ed X(WINDOW_LAYERS, windowIsLayers, LABEL_LAYERS_WINDOW, BOOL, true) \ X(WINDOW_NULLS, windowIsNulls, LABEL_NULLS_WINDOW, BOOL, true) \ X(WINDOW_ONIONSKIN, windowIsOnionskin, LABEL_ONIONSKIN_WINDOW, BOOL, true) \ + X(WINDOW_OVERLAYS, windowIsOverlays, LABEL_OVERLAYS_WINDOW, BOOL, true) \ X(WINDOW_PREVIEW, windowIsSpritesheets, LABEL_SPRITESHEETS_WINDOW, BOOL, true) \ + X(WINDOW_SHADERS, windowIsShaders, LABEL_SHADERS_WINDOW, BOOL, true) \ X(WINDOW_SOUNDS, windowIsSounds, LABEL_SOUNDS_WINDOW, BOOL, true) \ X(WINDOW_SPRITESHEET_EDITOR, windowIsSpritesheetEditor, LABEL_SPRITESHEET_EDITOR_WINDOW, BOOL, true) \ X(WINDOW_TIMELINE, windowIsTimeline, LABEL_TIMELINE_WINDOW, BOOL, true) \ diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 3c4e483..976eba0 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -1,40 +1,297 @@ #include "snapshots.hpp" #include +#include -using namespace anm2ed::snapshots; +#include + +namespace anm2ed::snapshots +{ + bool is_vec2_equal(const glm::vec2& left, const glm::vec2& right) { return glm::all(glm::equal(left, right)); } + + bool is_vec3_equal(const glm::vec3& left, const glm::vec3& right) { return glm::all(glm::equal(left, right)); } + + bool is_vec4_equal(const glm::vec4& left, const glm::vec4& right) { return glm::all(glm::equal(left, right)); } + + bool is_playback_equal(const Playback& left, const Playback& right) + { + return left.time == right.time && left.isPlaying == right.isPlaying && left.isFinished == right.isFinished; + } + + bool is_storage_equal(const Storage& left, const Storage& right) + { + return left.reference == right.reference && left.hovered == right.hovered && left.labelsString == right.labelsString && + left.ids == right.ids && static_cast&>(left.selection) == + static_cast&>(right.selection) && + left.references == right.references; + } + + bool is_texture_equal(const resource::Texture& left, const resource::Texture& right) + { + return left.size == right.size && left.filter == right.filter && left.channels == right.channels && + left.pixels == right.pixels; + } + + bool is_audio_equal(const resource::Audio& left, const resource::Audio& right) + { + return const_cast(left).is_valid() == const_cast(right).is_valid(); + } + + template + bool is_map_equal(const std::map& left, const std::map& right, Compare compare) + { + if (left.size() != right.size()) return false; + + auto leftIt = left.begin(); + auto rightIt = right.begin(); + while (leftIt != left.end() && rightIt != right.end()) + { + if (leftIt->first != rightIt->first) return false; + if (!compare(leftIt->second, rightIt->second)) return false; + ++leftIt; + ++rightIt; + } + + return leftIt == left.end() && rightIt == right.end(); + } + + template bool is_value_equal(const T& left, const T& right) { return left == right; } + + bool is_value_equal(const Playback& left, const Playback& right) { return is_playback_equal(left, right); } + + bool is_value_equal(const Storage& left, const Storage& right) { return is_storage_equal(left, right); } + + bool is_value_equal(const std::map& left, const std::map& right) + { + return is_map_equal(left, right, is_texture_equal); + } + + bool is_value_equal(const std::map& left, const std::map& right) + { + return is_map_equal(left, right, is_audio_equal); + } + + bool is_element_shallow_equal(const Element& left, const Element& right) + { + return left.type == right.type && left.tag == right.tag && left.name == right.name && + left.createdBy == right.createdBy && left.createdOn == right.createdOn && left.path == right.path && + left.vertex == right.vertex && left.fragment == right.fragment && left.binding == right.binding && + left.value == right.value && left.defaultAnimation == right.defaultAnimation && left.id == right.id && + left.layerId == right.layerId && left.nullId == right.nullId && + left.spritesheetId == right.spritesheetId && left.fps == right.fps && left.version == right.version && + left.frameNum == right.frameNum && left.duration == right.duration && left.atFrame == right.atFrame && + left.eventId == right.eventId && left.regionId == right.regionId && left.soundId == right.soundId && + left.groupId == right.groupId && left.index == right.index && left.isLoop == right.isLoop && + left.isVisible == right.isVisible && left.isShowRect == right.isShowRect && left.isExpanded == right.isExpanded && + left.isEnabled == right.isEnabled && left.interpolation == right.interpolation && left.origin == right.origin && + left.rotation == right.rotation && left.soundIds == right.soundIds && is_vec2_equal(left.pivot, right.pivot) && + is_vec2_equal(left.crop, right.crop) && is_vec2_equal(left.position, right.position) && + is_vec2_equal(left.size, right.size) && is_vec2_equal(left.scale, right.scale) && + is_vec3_equal(left.colorOffset, right.colorOffset) && is_vec4_equal(left.tint, right.tint); + } + + bool is_element_recurseable(const Element& left, const Element& right) + { + if (left.type != right.type) return false; + if (left.children.size() != right.children.size()) return false; + + for (size_t i = 0; i < left.children.size(); ++i) + if (left.children[i].type != right.children[i].type) return false; + + return true; + } + + bool is_element_equal(const Element& left, const Element& right) + { + if (!is_element_shallow_equal(left, right)) return false; + if (left.children.size() != right.children.size()) return false; + + for (size_t i = 0; i < left.children.size(); ++i) + if (!is_element_equal(left.children[i], right.children[i])) return false; + + return true; + } + + void element_steps_build(std::vector& out, const Element& before, const Element& after, + std::vector& path) + { + if (!is_element_recurseable(before, after) || !is_element_shallow_equal(before, after)) + { + out.push_back({path, before, after}); + return; + } + + for (size_t i = 0; i < before.children.size(); ++i) + { + path.push_back((int)i); + element_steps_build(out, before.children[i], after.children[i], path); + path.pop_back(); + } + } + + Element* element_get(Element& root, const std::vector& path) + { + auto* element = &root; + for (auto index : path) + { + if (index < 0 || index >= (int)element->children.size()) return nullptr; + element = &element->children[index]; + } + return element; + } + + const Element* element_get(const Element& root, const std::vector& path) + { + auto* element = &root; + for (auto index : path) + { + if (index < 0 || index >= (int)element->children.size()) return nullptr; + element = &element->children[index]; + } + return element; + } + + bool element_path_get(const Element& element, const Element* target, std::vector& path) + { + for (size_t i = 0; i < element.children.size(); ++i) + { + path.push_back((int)i); + if (&element.children[i] == target) return true; + if (element_path_get(element.children[i], target, path)) return true; + path.pop_back(); + } + return false; + } + + std::optional> frame_path_get(const Anm2& anm2, Reference frameReference) + { + auto frame = anm2.element_get(frameReference); + if (!frame) return std::nullopt; + + std::vector path{}; + if (!element_path_get(anm2.root, frame, path)) return std::nullopt; + return path; + } + + std::optional> region_path_get(const Anm2& anm2, int spritesheetId, int regionId) + { + auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return std::nullopt; + auto region = element_child_id_get(*spritesheet, ElementType::REGION, regionId); + if (!region) return std::nullopt; + + std::vector path{}; + if (!element_path_get(anm2.root, region, path)) return std::nullopt; + return path; + } + + void step_state_seed(SnapshotStep& step, const Snapshot& snapshot) + { +#define X(type, name) step.name = SnapshotStepValue{snapshot.name, {}}; + SNAPSHOT_STEP_STATE_FIELDS +#undef X + } + + void step_textures_seed(SnapshotStep& step, const Snapshot& snapshot) + { + step.textures = SnapshotStepValue{snapshot.textures, {}}; + step.overlayTextures = SnapshotStepValue{snapshot.overlayTextures, {}}; + } + + SnapshotStep step_anm2_seed(const Snapshot& snapshot, const std::string& message) + { + SnapshotStep step{}; + step.message = message; + step.anm2.isValid = SnapshotStepValue{snapshot.anm2.isValid, {}}; + step.anm2.elements.push_back({{}, snapshot.anm2.root, {}}); + step_state_seed(step, snapshot); + return step; + } + + void frames_step_add(SnapshotStep& step, const Snapshot& snapshot, Reference frameReference) + { + auto path = frame_path_get(snapshot.anm2, frameReference); + if (!path) return; + for (auto& elementStep : step.anm2.elements) + if (elementStep.path == *path) return; + + auto frame = snapshot.anm2.element_get(frameReference); + if (!frame) return; + + step.anm2.elements.push_back({std::move(*path), *frame, {}}); + } + + void regions_step_add(SnapshotStep& step, const Snapshot& snapshot, int spritesheetId, int regionId) + { + auto path = region_path_get(snapshot.anm2, spritesheetId, regionId); + if (!path) return; + for (auto& elementStep : step.anm2.elements) + if (elementStep.path == *path) return; + + auto spritesheet = snapshot.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); + if (!spritesheet) return; + auto region = element_child_id_get(*spritesheet, ElementType::REGION, regionId); + if (!region) return; + + step.anm2.elements.push_back({std::move(*path), *region, {}}); + } + + SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) + { + SnapshotAnm2Step step{}; + if (before.isValid != after.isValid) step.isValid = SnapshotStepValue{before.isValid, after.isValid}; + + std::vector path{}; + element_steps_build(step.elements, before.root, after.root, path); + return step; + } + +} namespace anm2ed { int SnapshotStack::maxSize = snapshots::MAX; - Snapshot Snapshot::stack_copy_get() const + bool SnapshotAnm2Step::is_empty() const { return !isValid && elements.empty(); } + + void SnapshotAnm2Step::apply(Anm2& anm2, SnapshotStepDirection direction) const { - Snapshot out{}; - out.playback = playback; - out.animation = animation; - out.event = event; - out.frames = frames; - out.items = items; - out.layer = layer; - out.merge = merge; - out.null = null; - out.region = region; - out.sound = sound; - out.spritesheet = spritesheet; - out.textures = textures; - out.sounds = sounds; - out.anm2 = anm2; - out.reference = reference; - out.groupReferences = groupReferences; - out.frameTime = frameTime; - out.message = message; - return out; + if (isValid) anm2.isValid = direction == SnapshotStepDirection::UNDO ? isValid->undo : isValid->redo; + + for (auto& elementStep : elements) + if (auto* element = snapshots::element_get(anm2.root, elementStep.path); element) + *element = direction == SnapshotStepDirection::UNDO ? elementStep.undo : elementStep.redo; + } + + bool SnapshotStep::is_empty() const + { + if (!anm2.is_empty()) return false; + +#define X(type, name) \ + if (this->name) return false; + SNAPSHOT_STEP_STATE_FIELDS + SNAPSHOT_STEP_RESOURCE_FIELDS +#undef X + + return true; + } + + void SnapshotStep::apply(Snapshot& snapshot, SnapshotStepDirection direction) const + { + snapshot.message = message; + anm2.apply(snapshot.anm2, direction); + +#define X(type, name) \ + if (this->name) snapshot.name = direction == SnapshotStepDirection::UNDO ? this->name->undo : this->name->redo; + SNAPSHOT_STEP_STATE_FIELDS + SNAPSHOT_STEP_RESOURCE_FIELDS +#undef X + } bool SnapshotStack::is_empty() { return stack.empty(); } - void SnapshotStack::push(const Snapshot& snapshot) + void SnapshotStack::push(SnapshotStep step) { if (maxSize <= 0) { @@ -42,13 +299,13 @@ namespace anm2ed return; } if ((int)stack.size() >= maxSize) stack.pop_front(); - stack.push_back(snapshot.stack_copy_get()); + stack.push_back(std::move(step)); } - std::optional SnapshotStack::pop() + std::optional SnapshotStack::pop() { if (is_empty()) return std::nullopt; - auto snapshot = stack.back(); + auto snapshot = std::move(stack.back()); stack.pop_back(); return snapshot; } @@ -71,18 +328,105 @@ namespace anm2ed int SnapshotStack::max_size_get() { return maxSize; } - void Snapshots::push(const Snapshot& snapshot) + Snapshot* Snapshots::get() { return ¤t; } + + void Snapshots::anm2_push(const Snapshot& snapshot, const std::string& message) { - undoStack.push(snapshot); + pendingStep = snapshots::step_anm2_seed(snapshot, message); + } + + void Snapshots::frames_push(const Snapshot& snapshot, const std::string& message, + const std::set& frameReferences) + { + SnapshotStep step{}; + step.message = message; + for (auto frameReference : frameReferences) + snapshots::frames_step_add(step, snapshot, frameReference); + + pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + } + + void Snapshots::regions_push(const Snapshot& snapshot, const std::string& message, int spritesheetId, + const std::set& regionIds) + { + SnapshotStep step{}; + step.message = message; + for (auto regionId : regionIds) + snapshots::regions_step_add(step, snapshot, spritesheetId, regionId); + + pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + } + + void Snapshots::textures_push(const Snapshot& snapshot, const std::string& message) + { + SnapshotStep step{}; + step.message = message; + snapshots::step_textures_seed(step, snapshot); + pendingStep = std::move(step); + } + + void Snapshots::anm2_textures_push(const Snapshot& snapshot, const std::string& message) + { + auto step = snapshots::step_anm2_seed(snapshot, message); + snapshots::step_textures_seed(step, snapshot); + pendingStep = std::move(step); + } + + void Snapshots::commit(const Snapshot& snapshot) + { + if (!pendingStep) return; + + auto step = std::move(*pendingStep); + pendingStep.reset(); + + if (step.anm2.isValid) + { + step.anm2.isValid->redo = snapshot.anm2.isValid; + if (step.anm2.isValid->undo == step.anm2.isValid->redo) step.anm2.isValid.reset(); + } + + for (auto it = step.anm2.elements.begin(); it != step.anm2.elements.end();) + { + auto* element = snapshots::element_get(snapshot.anm2.root, it->path); + if (!element) + { + it = step.anm2.elements.erase(it); + continue; + } + + it->redo = *element; + if (snapshots::is_element_equal(it->undo, it->redo)) + { + it = step.anm2.elements.erase(it); + continue; + } + + ++it; + } + +#define X(type, name) \ + if (step.name) \ + { \ + step.name->redo = snapshot.name; \ + if (snapshots::is_value_equal(step.name->undo, step.name->redo)) step.name.reset(); \ + } + SNAPSHOT_STEP_STATE_FIELDS + SNAPSHOT_STEP_RESOURCE_FIELDS +#undef X + + if (step.is_empty()) return; + + undoStack.push(std::move(step)); redoStack.clear(); } bool Snapshots::undo() { - if (auto snapshot = undoStack.pop()) + pendingStep.reset(); + if (auto step = undoStack.pop()) { - redoStack.push(current); - current = *snapshot; + step->apply(current, SnapshotStepDirection::UNDO); + redoStack.push(std::move(*step)); return true; } return false; @@ -90,10 +434,11 @@ namespace anm2ed bool Snapshots::redo() { - if (auto snapshot = redoStack.pop()) + pendingStep.reset(); + if (auto step = redoStack.pop()) { - undoStack.push(current); - current = *snapshot; + step->apply(current, SnapshotStepDirection::REDO); + undoStack.push(std::move(*step)); return true; } return false; @@ -103,6 +448,7 @@ namespace anm2ed { undoStack.clear(); redoStack.clear(); + pendingStep.reset(); } void Snapshots::apply_limit() @@ -110,4 +456,4 @@ namespace anm2ed undoStack.trim_to_limit(); redoStack.trim_to_limit(); } -}; +} diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 5b9202c..1c5917c 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "anm2/anm2.hpp" #include "audio.hpp" @@ -19,6 +20,34 @@ namespace anm2ed::snapshots namespace anm2ed { + enum class SnapshotStepDirection + { + UNDO, + REDO + }; + + template struct SnapshotStepValue + { + T undo{}; + T redo{}; + }; + + struct SnapshotElementStep + { + std::vector path{}; + Element undo{}; + Element redo{}; + }; + + struct SnapshotAnm2Step + { + std::optional> isValid{}; + std::vector elements{}; + + bool is_empty() const; + void apply(Anm2&, SnapshotStepDirection) const; + }; + class Snapshot { public: @@ -30,18 +59,58 @@ namespace anm2ed Storage layer{}; Storage merge{}; Storage null{}; + Storage overlay{}; Storage region{}; Storage sound{}; Storage spritesheet{}; std::map textures{}; + std::map overlayTextures{}; std::map sounds{}; Anm2 anm2{}; Reference reference{}; std::set groupReferences{}; float frameTime{}; std::string message = snapshots::ACTION; + }; - Snapshot stack_copy_get() const; + using SnapshotTextureMap = std::map; + using SnapshotOverlayTextureMap = std::map; + using SnapshotSoundMap = std::map; + +#define SNAPSHOT_STEP_STATE_FIELDS \ + X(Playback, playback) \ + X(Storage, animation) \ + X(Storage, event) \ + X(Storage, frames) \ + X(Storage, items) \ + X(Storage, layer) \ + X(Storage, merge) \ + X(Storage, null) \ + X(Storage, overlay) \ + X(Storage, region) \ + X(Storage, sound) \ + X(Storage, spritesheet) \ + X(Reference, reference) \ + X(std::set, groupReferences) \ + X(float, frameTime) + +#define SNAPSHOT_STEP_RESOURCE_FIELDS \ + X(SnapshotTextureMap, textures) \ + X(SnapshotOverlayTextureMap, overlayTextures) \ + X(SnapshotSoundMap, sounds) + + struct SnapshotStep + { + std::string message = snapshots::ACTION; + SnapshotAnm2Step anm2{}; + +#define X(type, name) std::optional> name{}; + SNAPSHOT_STEP_STATE_FIELDS + SNAPSHOT_STEP_RESOURCE_FIELDS +#undef X + + bool is_empty() const; + void apply(Snapshot&, SnapshotStepDirection) const; }; class SnapshotStack @@ -50,8 +119,8 @@ namespace anm2ed SnapshotStack() = default; bool is_empty(); - void push(const Snapshot&); - std::optional pop(); + void push(SnapshotStep); + std::optional pop(); void clear(); void trim_to_limit(); @@ -60,7 +129,7 @@ namespace anm2ed private: static int maxSize; - std::deque stack; + std::deque stack; }; class Snapshots @@ -69,9 +138,15 @@ namespace anm2ed SnapshotStack undoStack{}; SnapshotStack redoStack{}; Snapshot current{}; + std::optional pendingStep{}; Snapshot* get(); - void push(const Snapshot&); + void anm2_push(const Snapshot&, const std::string&); + void frames_push(const Snapshot&, const std::string&, const std::set&); + void regions_push(const Snapshot&, const std::string&, int, const std::set&); + void textures_push(const Snapshot&, const std::string&); + void anm2_textures_push(const Snapshot&, const std::string&); + void commit(const Snapshot&); bool undo(); bool redo(); void reset(); diff --git a/src/util/imgui/selectable.cpp b/src/util/imgui/selectable.cpp index 114e5ec..6367d19 100644 --- a/src/util/imgui/selectable.cpp +++ b/src/util/imgui/selectable.cpp @@ -14,6 +14,32 @@ namespace anm2ed::imgui return editID; } + bool input_text_rename_update(std::string& text, RenameState& state, float width) + { + bool isActivated{}; + + auto finish = [&]() + { + selectable_input_text_id().clear(); + isActivated = true; + state = RENAME_FINISHED; + isSelectableInputTextRenaming = false; + }; + + if (state == RENAME_BEGIN) + { + ImGui::SetKeyboardFocusHere(); + state = RENAME_EDITING; + } + + ImGui::SetNextItemWidth(width); + if (input_text_string("##Edit", &text, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) + finish(); + if (ImGui::IsItemDeactivatedAfterEdit() || ImGui::IsKeyPressed(ImGuiKey_Escape)) finish(); + + return isActivated; + } + bool selectable_input_text(const std::string& label, const std::string& id, std::string& text, bool isSelected, ImGuiSelectableFlags flags, RenameState& state) { @@ -22,26 +48,7 @@ namespace anm2ed::imgui bool isActivated{}; if (isRename) - { - auto finish = [&]() - { - editID.clear(); - isActivated = true; - state = RENAME_FINISHED; - isSelectableInputTextRenaming = false; - }; - - if (state == RENAME_BEGIN) - { - ImGui::SetKeyboardFocusHere(); - state = RENAME_EDITING; - } - - ImGui::SetNextItemWidth(-FLT_MIN); - if (input_text_string("##Edit", &text, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_AutoSelectAll)) - finish(); - if (ImGui::IsItemDeactivatedAfterEdit() || ImGui::IsKeyPressed(ImGuiKey_Escape)) finish(); - } + isActivated = input_text_rename_update(text, state); else { if (ImGui::Selectable(label.c_str(), isSelected, flags)) isActivated = true; diff --git a/src/util/imgui/selectable.hpp b/src/util/imgui/selectable.hpp index 82d4dcc..5f33544 100644 --- a/src/util/imgui/selectable.hpp +++ b/src/util/imgui/selectable.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -16,6 +17,7 @@ namespace anm2ed::imgui }; std::string& selectable_input_text_id(); + bool input_text_rename_update(std::string&, RenameState&, float = -FLT_MIN); bool selectable_input_text(const std::string&, const std::string&, std::string&, bool, ImGuiSelectableFlags, RenameState&); } diff --git a/src/util/imgui/tree.cpp b/src/util/imgui/tree.cpp new file mode 100644 index 0000000..d4be6dd --- /dev/null +++ b/src/util/imgui/tree.cpp @@ -0,0 +1,41 @@ +#include "tree.hpp" + +namespace anm2ed::imgui +{ + TreeNodeInputTextResult tree_node_input_text(const std::string& label, const std::string& id, std::string& text, + bool isSelected, ImGuiTreeNodeFlags flags, RenameState& state) + { + TreeNodeInputTextResult result{}; + auto& editID = selectable_input_text_id(); + auto isRename = editID == id; + auto treeFlags = flags | ImGuiTreeNodeFlags_FramePadding | (isSelected ? ImGuiTreeNodeFlags_Selected : 0); + + if (!isRename) + { + result.isOpen = ImGui::TreeNodeEx(id.c_str(), treeFlags, "%s", label.c_str()); + result.isClicked = + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + result.isActivated = result.isClicked; + + if (state == RENAME_FORCE_EDIT || (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))) + { + state = RENAME_BEGIN; + editID = id; + result.isActivated = true; + result.isRenameStarted = true; + } + + return result; + } + + result.isOpen = ImGui::TreeNodeEx(id.c_str(), treeFlags, "%s", ""); + auto itemMin = ImGui::GetItemRectMin(); + auto itemMax = ImGui::GetItemRectMax(); + auto labelX = itemMin.x + ImGui::GetTreeNodeToLabelSpacing(); + ImGui::SetCursorScreenPos(ImVec2(labelX, itemMin.y)); + auto width = itemMax.x > labelX ? itemMax.x - labelX : 1.0f; + result.isActivated = input_text_rename_update(text, state, width); + result.isRenameFinished = state == RENAME_FINISHED; + return result; + } +} diff --git a/src/util/imgui/tree.hpp b/src/util/imgui/tree.hpp new file mode 100644 index 0000000..ecf9932 --- /dev/null +++ b/src/util/imgui/tree.hpp @@ -0,0 +1,22 @@ +#pragma once + +#include + +#include + +#include "selectable.hpp" + +namespace anm2ed::imgui +{ + struct TreeNodeInputTextResult + { + bool isOpen{}; + bool isActivated{}; + bool isClicked{}; + bool isRenameStarted{}; + bool isRenameFinished{}; + }; + + TreeNodeInputTextResult tree_node_input_text(const std::string&, const std::string&, std::string&, bool, + ImGuiTreeNodeFlags, RenameState&); +}