diff --git a/src/imgui/window/timeline/commands.cpp b/src/imgui/window/timeline/commands.cpp deleted file mode 100644 index 3491e73..0000000 --- a/src/imgui/window/timeline/commands.cpp +++ /dev/null @@ -1,2012 +0,0 @@ -#include "context.hpp" - -namespace anm2ed::imgui -{ - void TimelineContext::commands_bind() - { - type_index = [](int type) { return std::clamp(type, 0, (int)TRIGGER); }; - item_type_get = [](int type) { return static_cast(type); }; - item_get = [&](int type, int id = -1, int groupType = NONE, int groupId = -1) - { return animation ? animation_item_get(*animation, item_type_get(type), id, groupType, groupId) : nullptr; }; - frame_get = [&]() - { - if (reference.frameIndex < 0) return (Element*)nullptr; - return anm2.element_get(reference); - }; - selected_item_get = [&]() - { - auto itemReference = reference; - itemReference.frameIndex = -1; - return anm2.element_get(itemReference); - }; - item_frame_type_get = [](const Element& item) - { return item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; }; - item_frames_count = [](const Element* item) - { - if (!item) return 0; - auto frameType = item->type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int count{}; - for (const auto& child : item->children) - if (child.type == frameType) ++count; - return count; - }; - item_frame_child_index_get = [](const Element& item, int frameIndex) - { - if (frameIndex < 0) return -1; - auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int currentFrameIndex{}; - for (int i = 0; i < (int)item.children.size(); ++i) - { - if (item.children[i].type != frameType) continue; - if (currentFrameIndex == frameIndex) return i; - ++currentFrameIndex; - } - return -1; - }; - item_frame_insert_index_get = [](const Element& item, int frameIndex) - { - auto targetFrameIndex = glm::max(0, frameIndex); - auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int currentFrameIndex{}; - for (int i = 0; i < (int)item.children.size(); ++i) - { - if (item.children[i].type != frameType) continue; - if (currentFrameIndex == targetFrameIndex) return i; - ++currentFrameIndex; - } - return (int)item.children.size(); - }; - layer_get = [&](int id) { return anm2.element_get(ElementType::LAYER_ELEMENT, id); }; - null_get = [&](int id) - { - auto nulls = anm2.element_get(ElementType::NULLS); - return nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, id) : nullptr; - }; - spritesheet_get = [&](int id) { return anm2.element_get(ElementType::SPRITESHEET, id); }; - info_get = [&]() { return element_first_get(anm2.root, ElementType::INFO); }; - container_type_get = [](int type) - { - if (type == LAYER) return ElementType::LAYER_ANIMATIONS; - if (type == NULL_) return ElementType::NULL_ANIMATIONS; - return ElementType::UNKNOWN; - }; - track_type_get = [](int type) - { - if (type == LAYER) return ElementType::LAYER_ANIMATION; - if (type == NULL_) return ElementType::NULL_ANIMATION; - return ElementType::UNKNOWN; - }; - track_id_get = [](const Element& track, int type) - { - if (type == LAYER) return track.layerId; - if (type == NULL_) return track.nullId; - return -1; - }; - track_container_get = [&](int type) - { return animation ? child_first_get(*animation, container_type_get(type)) : nullptr; }; - track_group_get = [&](int type, int groupId) - { - auto container = track_container_get(type); - return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; - }; - is_track_group_visible = [&](int type, int groupId) - { - if (groupId == -1) return true; - auto group = track_group_get(type, groupId); - return !group || group->isVisible; - }; - row_group_get = [&](const TimelineItemRow& row) -> Element* - { return row.isGroup ? track_group_get(row.type, row.id) : nullptr; }; - group_items_count_get = [&](int type, int groupId) - { - auto container = track_container_get(type); - auto trackType = track_type_get(type); - int count{}; - if (!container) return count; - for (auto& item : container->children) - if (item.type == trackType && item.groupId == groupId) ++count; - return count; - }; - - command_animation_get = [](Document& document, int animationIndex) - { return document.anm2.element_get(ElementType::ANIMATION, animationIndex); }; - command_item_get = - [](Document& document, int animationIndex, int type, int id, int groupType = NONE, int groupId = -1) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); - return animation ? animation_item_get(*animation, static_cast(type), id, groupType, groupId) : nullptr; - }; - command_item_reference_get = [](Document& document, Reference itemReference) - { - itemReference.frameIndex = -1; - return document.anm2.element_get(itemReference); - }; - command_frame_get = [](Document& document, const Reference& targetReference) - { - if (targetReference.frameIndex < 0) return (Element*)nullptr; - return document.anm2.element_get(targetReference); - }; - command_layer_get = [](Document& document, int id) - { return document.anm2.element_get(ElementType::LAYER_ELEMENT, id); }; - command_spritesheet_get = [](Document& document, int id) - { return document.anm2.element_get(ElementType::SPRITESHEET, id); }; - command_info_get = [](Document& document) { return element_first_get(document.anm2.root, ElementType::INFO); }; - item_reference_get = [&](int type, int id, int groupType = NONE, int groupId = -1) - { return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; }; - item_reference_from_frame_get = [](Reference frameReference) - { - frameReference.frameIndex = -1; - return frameReference; - }; - is_same_item = [](const Reference& left, const Reference& right) - { - return left.animationIndex == right.animationIndex && left.itemType == right.itemType && - left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; - }; - is_frame_reference_valid_for = [&](Document& targetDocument, const Reference& frameReference) - { return targetDocument.is_frame_reference_valid(frameReference); }; - group_selection_reset_for = [this](Document& targetDocument) - { - targetDocument.groupReferences.clear(); - isRowSelectionAnchorSet = false; - }; - frame_references_for_current_get = [&]() - { return document.frame_references_get(Document::FrameReferenceFallback::NONE); }; - item_references_for_current_get = [&]() - { - std::set result = document.items.references; - if (result.empty() && reference.itemType != NONE) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - result.insert(itemReference); - } - return result; - }; - frames_selection_sync_for = [&](Document& targetDocument) - { - auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - targetDocument.frame_references_set(std::move(selectedFrames)); - frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); - frameSelectionSnapshotReference = targetDocument.reference; - }; - item_selection_set_for = [&](Document& targetDocument, Reference itemReference) - { - itemReference.frameIndex = -1; - targetDocument.items.references = {itemReference}; - }; - frame_selection_set_for = [&](Document& targetDocument, Reference frameReference) - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - targetDocument.frame_references_set({frameReference}); - frames_selection_sync_for(targetDocument); - }; - frame_selection_toggle_for = [&](Document& targetDocument, Reference frameReference) - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - auto selection = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - auto itemReference = item_reference_from_frame_get(frameReference); - if (selection.contains(frameReference)) - { - if (selection.size() > 1) selection.erase(frameReference); - bool isItemStillSelected{}; - for (const auto& selectedFrame : selection) - if (is_same_item(selectedFrame, itemReference)) isItemStillSelected = true; - if (!isItemStillSelected && targetDocument.items.references.size() > 1) - targetDocument.items.references.erase(itemReference); - } - else - { - selection.insert(frameReference); - targetDocument.items.references.insert(itemReference); - } - targetDocument.reference = frameReference; - targetDocument.frame_references_set(std::move(selection)); - frames_selection_sync_for(targetDocument); - }; - frame_selection_range_set_for = [&](Document& targetDocument, Reference firstReference, Reference lastReference, - bool isAdditive) -> bool - { - group_selection_reset_for(targetDocument); - targetDocument.editTarget = Document::EditTarget::FRAME; - if (!is_same_item(firstReference, lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) - return false; - - auto item = command_item_reference_get(targetDocument, lastReference); - if (!item) return false; - if (firstReference.frameIndex >= (int)item->children.size() || - lastReference.frameIndex >= (int)item->children.size()) - return false; - - auto firstIndex = firstReference.frameIndex; - auto lastIndex = lastReference.frameIndex; - if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); - auto selectedFrames = isAdditive ? targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE) - : std::set{}; - - for (int i = firstIndex; i <= lastIndex; ++i) - { - auto frameReference = lastReference; - frameReference.frameIndex = i; - selectedFrames.insert(frameReference); - } - - targetDocument.reference = lastReference; - targetDocument.frame_references_set(std::move(selectedFrames)); - frames_selection_sync_for(targetDocument); - return true; - }; - all_frame_references_for_items_get = [&]() { return document.selected_item_frame_references_get(); }; - is_frame_copy_item = [](const Reference& itemReference) - { return itemReference.itemType == ROOT || itemReference.itemType == LAYER || itemReference.itemType == NULL_; }; - copy_frame_references_get = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (!selectedFrames.empty()) return selectedFrames; - - auto selectedItems = document.items.references; - if (selectedItems.empty() && reference.itemType != NONE && reference.frameIndex < 0) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - selectedItems.insert(itemReference); - } - - std::set result{}; - for (auto itemReference : selectedItems) - { - itemReference.frameIndex = -1; - if (!is_frame_copy_item(itemReference)) continue; - auto itemFrames = document.item_frame_references_get(itemReference); - result.insert(itemFrames.begin(), itemFrames.end()); - } - return result; - }; - frames_selection_reset_for = [this](Document& targetDocument) - { - targetDocument.frame_references_clear(); - frameSelectionSnapshot.clear(); - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusRequested = false; - frameFocusIndex = -1; - frameSelectionSnapshotReference = targetDocument.reference; - }; - frames_selection_set_reference_for = [this](Document& targetDocument) - { - auto& targetReference = targetDocument.reference; - if (targetReference.frameIndex >= 0) - { - targetDocument.editTarget = Document::EditTarget::FRAME; - targetDocument.frame_references_set({targetReference}); - } - else - targetDocument.frame_references_clear(); - frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); - frameSelectionSnapshotReference = targetReference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = targetReference.frameIndex; - frameFocusRequested = targetReference.frameIndex >= 0; - }; - frames_reference_normalize_for = [&](Document& targetDocument) - { - auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); - if (!selectedFrames.empty()) - { - targetDocument.frame_references_set(std::move(selectedFrames)); - frames_selection_sync_for(targetDocument); - return; - } - - if (targetDocument.reference.frameIndex >= 0 && - !is_frame_reference_valid_for(targetDocument, targetDocument.reference)) - targetDocument.reference.frameIndex = -1; - }; - frames_reference_normalize_for(document); - reference_clear_for = [=, this](Document& targetDocument) - { - targetDocument.reference = {targetDocument.reference.animationIndex}; - frames_selection_reset_for(targetDocument); - targetDocument.items.references.clear(); - }; - reference_set_item_reference_for = [=, this](Document& targetDocument, Reference itemReference) - { - itemReference.frameIndex = -1; - targetDocument.reference = itemReference; - frames_selection_reset_for(targetDocument); - item_selection_set_for(targetDocument, itemReference); - }; - reference_set_timeline_item_reference_for = [=, this](Document& targetDocument, Reference itemReference) - { - if (itemReference.itemType == LAYER) - if (auto layer = command_layer_get(targetDocument, itemReference.itemID)) - targetDocument.spritesheet.reference = layer->spritesheetId; - reference_set_item_reference_for(targetDocument, itemReference); - }; - command_push = [&](auto run) - { - manager.command_push( - {manager.selected, [run](Manager& manager, Document& document) mutable { run(manager, document); }}); - }; - track_references_from_frame_references_get = [](std::set frameReferences) - { - std::set result{}; - for (auto frameReference : frameReferences) - { - frameReference.frameIndex = -1; - result.insert(frameReference); - } - return result; - }; - tracks_snapshot_command_push = [&](StringType messageType, const std::set& trackReferences) - { - auto message = std::string(localize.get(messageType)); - auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, [message, queuedTrackReferences](Manager&, Document& document) - { document.snapshots.tracks_push(message, queuedTrackReferences); }}); - }; - frames_snapshot_command_push = [&](StringType messageType, const std::set& frameReferences) - { - auto message = std::string(localize.get(messageType)); - auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) - { document.snapshots.frames_push(message, queuedFrameReferences); }}); - }; - frames_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& frameReferences, auto run) - { - auto message = std::string(localize.get(messageType)); - auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable - { - (void)changeType; - document.snapshots.frames_push(message, queuedFrameReferences); - run(manager, document); - document.change(changeType); - }}); - }; - tracks_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& trackReferences, auto run) - { - auto message = std::string(localize.get(messageType)); - auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable - { - (void)changeType; - document.snapshots.tracks_push(message, queuedTrackReferences); - run(manager, document); - document.change(changeType); - }}); - }; - edit_command_push = [&](StringType messageType, Document::ChangeType changeType, auto run) - { - auto message = std::string(localize.get(messageType)); - manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable - { - (void)changeType; - document.snapshots.anm2_push(message); - run(manager, document); - document.change(changeType); - }}); - }; - type_color_base_vec = [&](int type) - { return isLightTheme ? FRAME_COLOR_LIGHT_BASE[type_index(type)] : TYPE_COLOR[type]; }; - - type_color_active_vec = [&](int type) - { - if (isLightTheme) return FRAME_COLOR_LIGHT_ACTIVE[type_index(type)]; - return TYPE_COLOR_ACTIVE[type]; - }; - - type_color_hovered_vec = [&](int type) - { - if (isLightTheme) return FRAME_COLOR_LIGHT_HOVERED[type_index(type)]; - return TYPE_COLOR_HOVERED[type]; - }; - - item_color_vec = [&](int type) - { - if (!isLightTheme) return TYPE_COLOR[type]; - return ITEM_COLOR_LIGHT_BASE[type_index(type)]; - }; - - item_color_active_vec = [&](int type) - { - if (!isLightTheme) return TYPE_COLOR_ACTIVE[type]; - return ITEM_COLOR_LIGHT_ACTIVE[type_index(type)]; - }; - - iconTintDefault = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : ICON_TINT_DEFAULT_DARK; - itemIconTint = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : iconTintDefault; - frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; - frameBorderColorReferenced = - isLightTheme ? FRAME_BORDER_COLOR_REFERENCED_LIGHT : FRAME_BORDER_COLOR_REFERENCED_DARK; - frameMultipleOverlayColor = isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; - textMultipleColor = isLightTheme ? TEXT_MULTIPLE_COLOR_LIGHT : TEXT_MULTIPLE_COLOR_DARK; - playheadLineColor = isLightTheme ? PLAYHEAD_LINE_COLOR_LIGHT : PLAYHEAD_LINE_COLOR_DARK; - playheadIconTint = isLightTheme ? PLAYHEAD_ICON_TINT_LIGHT : iconTintDefault; - timelineBackgroundColor = - isLightTheme ? TIMELINE_BACKGROUND_COLOR_LIGHT : ImGui::GetStyleColorVec4(ImGuiCol_Header); - timelinePlayheadRectColor = isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; - timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; - itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; - - overlay_icon = [&](GLuint textureId, ImVec4 tint, bool isForced = false) - { - if (!isForced && !isLightTheme) return; - auto min = ImGui::GetItemRectMin(); - auto max = ImGui::GetItemRectMax(); - ImGui::GetWindowDrawList()->AddImage((ImTextureID)(intptr_t)textureId, min, max, ImVec2(0, 0), ImVec2(1, 1), - ImGui::GetColorU32(tint)); - }; - - frames_selection_set_reference = [&]() { frames_selection_set_reference_for(document); }; - - playback_stop = [&]() - { - playback.isPlaying = false; - playback.isFinished = false; - playback.timing_reset(); - }; - - frame_insert = [&]() - { - auto targetReference = reference; - auto targetFrameTime = document.frameTime; - if (!animation || !command_item_reference_get(document, targetReference)) return; - - tracks_edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetReference.animationIndex); - auto item = command_item_reference_get(document, targetReference); - if (!animation || !item) return; - - auto newReference = targetReference; - - if (targetReference.itemType == TRIGGER) - { - for (auto& trigger : item->children) - if (targetFrameTime == trigger.atFrame) return; - - auto addFrame = element_make(ElementType::TRIGGER); - addFrame.atFrame = targetFrameTime; - item->children.push_back(addFrame); - frames_sort_by_at_frame(*item); - newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); - } - else - { - auto frame = command_frame_get(document, targetReference); - auto framesCount = item_frames_count(item); - if (frame) - { - auto addFrame = *frame; - auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, addFrame); - newReference.frameIndex = insertIndex; - } - else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) - { - item->children.emplace_back(*lastFrame); - newReference.frameIndex = framesCount; - } - else - { - item->children.emplace_back(element_make(ElementType::FRAME)); - newReference.frameIndex = 0; - } - } - - document.reference = newReference; - frames_selection_set_reference_for(document); - if (newReference.itemType != TRIGGER) - document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); - }); - }; - - frames_delete_for = [=, this](Document& document, std::set selectedFrames) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - } - - auto item = command_item_reference_get(document, document.reference); - if (!item || item->children.empty()) - { - document.reference.frameIndex = -1; - frames_selection_reset_for(document); - return; - } - - document.reference.frameIndex = glm::clamp(document.reference.frameIndex, 0, (int)item->children.size() - 1); - frames_selection_set_reference_for(document); - }; - - frames_delete_action = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.empty()) return; - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_DELETE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }); - }; - - frames_duplicate = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set duplicatedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - std::vector validIndices{}; - std::vector duplicatedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - duplicatedFrames.push_back(*frame); - } - if (validIndices.empty()) continue; - - auto insertIndex = validIndices.back() + 1; - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(duplicatedFrames.begin()), - std::make_move_iterator(duplicatedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - duplicatedSelection.insert(targetReference); - auto sourceReference = itemReference; - sourceReference.frameIndex = validIndices[offset]; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (duplicatedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); - document.frame_references_set(std::move(duplicatedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - is_frames_reverse_available = [&](std::set selectedFrames) - { - std::map counts{}; - std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - ++counts[itemReference]; - } - return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); - }; - - frames_reverse = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (!is_frames_reverse_available(selectedFrames)) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_REVERSE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set reversedSelection{}; - auto newReference = document.reference; - bool isReferenceSet{}; - - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item || indices.size() < 2) continue; - - std::vector validIndices{}; - std::vector reversedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - reversedFrames.push_back(std::move(*frame)); - } - if (validIndices.size() < 2) continue; - - auto insertIndex = validIndices.front(); - for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } - - std::ranges::reverse(reversedFrames); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(reversedFrames.begin()), - std::make_move_iterator(reversedFrames.end())); - - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - reversedSelection.insert(targetReference); - auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; - auto sourceReference = itemReference; - sourceReference.frameIndex = sourceIndex; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } - - if (reversedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); - document.frame_references_set(std::move(reversedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - frames_bake = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - auto bakeInterval = settings.bakeInterval; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; - std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (selectedFrames.empty()) return; - - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_BAKE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } - - std::set bakedSelection{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - int insertedBefore = 0; - for (auto originalIndex : indices) - { - auto i = originalIndex + insertedBefore; - auto frame = track_frame_get(*item, i); - if (!frame) continue; - - auto originalDuration = frame->duration; - frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); - - auto bakedCount = originalDuration <= FRAME_DURATION_MIN - ? 1 - : (int)std::ceil((float)originalDuration / bakeInterval); - for (int offset = 0; offset < bakedCount; ++offset) - { - auto frameReference = itemReference; - frameReference.frameIndex = i + offset; - bakedSelection.insert(frameReference); - } - - insertedBefore += bakedCount - 1; - } - } - - document.frame_references_set(std::move(bakedSelection)); - if (!document.frames.references.empty()) - { - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - } - else - frames_selection_reset_for(document); - }); - }; - - selected_root_frame_references_get = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); - return selectedFrames; - }; - - item_references_for_bake_into_other_frames_get = [](const Document& targetDocument, const Element& targetAnimation, - BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls) - { - std::set result{}; - auto animationIndex = targetDocument.reference.animationIndex; - if (target == BakeIntoOtherFramesTarget::CURRENT_SELECTION) - { - for (auto itemReference : targetDocument.items.references) - { - itemReference.frameIndex = -1; - if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) result.insert(itemReference); - } - return result; - } - - auto add_items = [&](const Element& container, int itemType) - { - auto trackType = TYPE_TRACKS[itemType]; - auto add_item = [&](auto&& self, const Element& item) -> void - { - if (item.type == ElementType::GROUP) - { - for (const auto& child : item.children) - self(self, child); - return; - } - if (item.type != trackType) return; - auto itemID = itemType == LAYER ? item.layerId : item.nullId; - auto groupType = item.groupId == -1 ? NONE : itemType; - result.insert({animationIndex, itemType, itemID, -1, groupType, item.groupId}); - }; - for (const auto& item : container.children) - add_item(add_item, item); - }; - - if (isLayers) - if (auto layerAnimations = child_first_get(targetAnimation, ElementType::LAYER_ANIMATIONS)) - add_items(*layerAnimations, LAYER); - if (isNulls) - if (auto nullAnimations = child_first_get(targetAnimation, ElementType::NULL_ANIMATIONS)) - add_items(*nullAnimations, NULL_); - return result; - }; - - is_bake_into_other_frames_ready = [&]() - { - auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty() || !animation) return false; - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - return !targetItems.empty(); - }; - - frame_root_transform_apply = - [](Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, bool isUseRootPivot) - { - auto rootScale = math::percent_to_unit(rootFrame.scale); - auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); - auto offset = (frame.position - pivot) * rootScale; - auto radians = glm::radians(rootFrame.rotation); - auto cos = std::cos(radians); - auto sin = std::sin(radians); - - frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); - frame.scale *= rootScale; - frame.rotation += rootFrame.rotation; - frame.tint *= rootFrame.tint; - frame.colorOffset += rootFrame.colorOffset; - - if (isRoundScale) frame.scale = glm::round(frame.scale); - if (isRoundRotation) frame.rotation = std::round(frame.rotation); - }; - - bake_into_other_frames = [&]() - { - auto selectedRootFrames = selected_root_frame_references_get(); - if (selectedRootFrames.empty()) return; - if (!animation) return; - auto target = bakeIntoOtherFramesTarget; - auto isLayers = isBakeIntoOtherFramesLayers; - auto isNulls = isBakeIntoOtherFramesNulls; - auto isRoundScale = settings.bakeIsRoundScale; - auto isRoundRotation = settings.bakeIsRoundRotation; - auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto isUseRootPivot = settings.bakeIsUseRootPivot; - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); - trackReferences.insert(targetItems.begin(), targetItems.end()); - tracks_edit_command_push( - EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, document.reference.animationIndex); - if (!animation) return; - auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); - for (auto rootReference : selectedRootFrames) - if (!is_same_item(rootReference, rootItemReference)) return; - auto root = command_item_reference_get(document, rootItemReference); - if (!root) return; - - std::vector spans{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); - spans.push_back({start, start + rootFrame->duration}); - } - if (spans.empty()) return; - - auto targetItems = - item_references_for_bake_into_other_frames_get(document, *animation, target, isLayers, isNulls); - if (targetItems.empty()) return; - - for (auto itemReference : targetItems) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; - - if (isMatchRootInterpolation) - { - std::vector bakeIndices{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - bakeIndices.push_back(frameIndex); - break; - } - ++frameIndex; - } - for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) - frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); - } - - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - bool isInsideSpan{}; - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - isInsideSpan = true; - break; - } - if (!isInsideSpan) - { - ++frameIndex; - continue; - } - auto rootFrame = frame_generate(*root, (float)frameStart); - frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, isUseRootPivot); - ++frameIndex; - } - } - - std::set selectedRootFrameIndices{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - selectedRootFrameIndices.insert(rootReference.frameIndex); - } - if (selectedRootFrameIndices.empty()) return; - - std::vector rootFrames{}; - std::set defaultRootSelection{}; - int frameIndex{}; - int rewrittenFrameIndex{}; - int defaultDuration{}; - auto default_root_frame_push = [&]() - { - if (defaultDuration <= 0) return; - auto frame = element_make(ElementType::FRAME); - frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); - auto defaultRootReference = rootItemReference; - defaultRootReference.frameIndex = rewrittenFrameIndex; - defaultRootSelection.insert(defaultRootReference); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - defaultDuration = 0; - }; - - for (const auto& frame : root->children) - { - if (frame.type != ElementType::FRAME) - { - default_root_frame_push(); - rootFrames.push_back(frame); - continue; - } - - if (selectedRootFrameIndices.contains(frameIndex)) - defaultDuration += frame.duration; - else - { - default_root_frame_push(); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - } - ++frameIndex; - } - default_root_frame_push(); - - root->children = std::move(rootFrames); - document.frame_references_set(std::move(defaultRootSelection)); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - }); - }; - - frame_split = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.size() != 1) return; - auto targetReference = *selectedFrames.begin(); - auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); - if (targetReference.itemType == TRIGGER) return; - - tracks_edit_command_push( - EDIT_SPLIT_FRAME, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) mutable - { - if (targetReference.itemType == TRIGGER) return; - - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - - if (!item || !frame) return; - - auto originalDuration = frame->duration; - if (originalDuration <= 1) return; - - auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); - int frameStart = (int)std::round(frameStartTime); - int firstDuration = splitTime - frameStart + 1; - - if (firstDuration <= 0 || firstDuration >= originalDuration) return; - - int secondDuration = originalDuration - firstDuration; - auto splitFrame = *frame; - splitFrame.duration = secondDuration; - - auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); - if (frame->interpolation != Interpolation::NONE && nextFrame) - frame_mix(splitFrame, *nextFrame, - interpolation_factor(frame->interpolation, (float)firstDuration / (float)originalDuration)); - - frame->duration = firstDuration; - auto insertIndex = item_frame_insert_index_get(*item, targetReference.frameIndex + 1); - item->children.insert(item->children.begin() + insertIndex, splitFrame); - document.reference = targetReference; - frames_selection_set_reference_for(document); - }); - }; - - reference_clear = [&]() - { - group_selection_reset_for(document); - reference_clear_for(document); - }; - - reference_set_timeline_item_reference = [&](Reference itemReference) - { - group_selection_reset_for(document); - reference_set_timeline_item_reference_for(document, itemReference); - }; - - timeline_item_rows_get = [&]() - { - std::vector rows{}; - if (!animation) return rows; - - auto track_row_push = [&](const Element& item, int type, int index, int depth = 0) - { - auto rootGroupType = item.groupId == -1 ? NONE : type; - rows.push_back({.type = type, - .id = track_id_get(item, type), - .index = index, - .groupId = item.groupId, - .rootGroupType = rootGroupType, - .rootGroupId = item.groupId, - .depth = depth}); - }; - auto group_row_push = [&](const Element& group, int type, int index) - { rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); }; - auto group_root_row_push = [&](const Element& group, int type) - { rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); }; - auto group_ids_get = [](const Element& container) - { - std::set result{}; - for (const auto& item : container.children) - if (item.type == ElementType::GROUP) result.insert(item.id); - return result; - }; - - rows.push_back({.type = ROOT}); - - if (auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) - { - auto groupIds = group_ids_get(*layerAnimations); - auto layer_track_push = [&](int groupId, int depth) - { - for (int j = (int)layerAnimations->children.size() - 1; j >= 0; --j) - { - auto& item = layerAnimations->children[j]; - if (item.type != ElementType::LAYER_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, LAYER, j, depth); - } - }; - - for (int i = (int)layerAnimations->children.size() - 1; i >= 0; --i) - { - auto& item = layerAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, LAYER, i); - if (item.isExpanded) - { - group_root_row_push(item, LAYER); - layer_track_push(item.id, 1); - } - } - else if (item.type == ElementType::LAYER_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, LAYER, i); - } - } - - if (auto nullAnimations = child_first_get(*animation, ElementType::NULL_ANIMATIONS)) - { - auto groupIds = group_ids_get(*nullAnimations); - auto null_track_push = [&](int groupId, int depth) - { - for (int j = 0; j < (int)nullAnimations->children.size(); ++j) - { - auto& item = nullAnimations->children[j]; - if (item.type != ElementType::NULL_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, NULL_, j, depth); - } - }; - - for (int i = 0; i < (int)nullAnimations->children.size(); ++i) - { - auto& item = nullAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, NULL_, i); - if (item.isExpanded) - { - group_root_row_push(item, NULL_); - null_track_push(item.id, 1); - } - } - else if (item.type == ElementType::NULL_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, NULL_, i); - } - } - - rows.push_back({.type = TRIGGER}); - return rows; - }; - - timeline_item_references_get = [&]() - { - std::vector itemReferences; - for (const auto& row : timeline_item_rows_get()) - { - if (row.isGroup) continue; - itemReferences.push_back({reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); - } - return itemReferences; - }; - - group_reference_get = [&](const TimelineItemRow& row) - { return Reference{reference.animationIndex, row.type, row.id}; }; - - row_reference_get = [&](const TimelineItemRow& row) - { - return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, - row.index, row.rootGroupType, row.rootGroupId, row.isGroup}; - }; - - row_item_reference_get = [](const TimelineRowReference& row) - { return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; }; - - timeline_row_references_get = [&]() - { - std::vector rowReferences; - for (const auto& row : timeline_item_rows_get()) - { - if (row.type == NONE) continue; - rowReferences.push_back(row_reference_get(row)); - } - return rowReferences; - }; - - is_group_selected = [&](const TimelineItemRow& row) - { return document.groupReferences.contains(group_reference_get(row)); }; - - is_row_selected = [&](const TimelineItemRow& row) - { - if (row.isGroup) return is_group_selected(row); - auto itemReference = item_reference_get(row.type, row.id, row.rootGroupType, row.rootGroupId); - auto isReferenced = is_same_item(reference, itemReference); - return document.items.references.contains(itemReference) || - (document.items.references.empty() && document.groupReferences.empty() && isReferenced); - }; - - row_selection_clear = [&]() - { - document.items.references.clear(); - document.groupReferences.clear(); - }; - - row_selection_insert = [&](const TimelineRowReference& row) - { - if (row.isGroup) - document.groupReferences.insert({row.animationIndex, row.type, row.id}); - else - document.items.references.insert(row_item_reference_get(row)); - }; - - row_selection_erase = [&](const TimelineRowReference& row) - { - if (row.isGroup) - document.groupReferences.erase({row.animationIndex, row.type, row.id}); - else - document.items.references.erase(row_item_reference_get(row)); - }; - - is_row_reference_selected = [&](const TimelineRowReference& row) - { - if (row.isGroup) return document.groupReferences.contains({row.animationIndex, row.type, row.id}); - return document.items.references.contains(row_item_reference_get(row)); - }; - - row_selection_count_get = [&]() { return document.items.references.size() + document.groupReferences.size(); }; - - row_selection_set = [&](const TimelineItemRow& row) - { - auto rowReference = row_reference_get(row); - auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); - auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); - - if (row.isGroup) - reference = {reference.animationIndex}; - else - { - if (row.type == LAYER) - if (auto layer = layer_get(row.id)) document.spritesheet.reference = layer->spritesheetId; - reference = row_item_reference_get(rowReference); - } - frames_selection_reset_for(document); - - if (isShiftDown) - { - auto rowSelection = timeline_row_references_get(); - auto anchor = isRowSelectionAnchorSet ? rowSelectionAnchor : rowReference; - auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); - auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); - if (first == rowSelection.end() || last == rowSelection.end()) - { - if (!isCtrlDown) row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - else - { - auto firstIndex = (int)std::distance(rowSelection.begin(), first); - auto lastIndex = (int)std::distance(rowSelection.begin(), last); - if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); - if (!isCtrlDown) row_selection_clear(); - for (int i = firstIndex; i <= lastIndex; ++i) - row_selection_insert(rowSelection[i]); - if (!isRowSelectionAnchorSet) rowSelectionAnchor = rowReference; - } - } - else if (isCtrlDown) - { - if (is_row_reference_selected(rowReference) && row_selection_count_get() > 1) - row_selection_erase(rowReference); - else - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - else - { - row_selection_clear(); - row_selection_insert(rowReference); - rowSelectionAnchor = rowReference; - } - - isRowSelectionAnchorSet = true; - }; - - reference_set_adjacent_item = [&](int direction) - { - auto itemReferences = timeline_item_references_get(); - if (itemReferences.empty()) return; - - auto it = std::find_if(itemReferences.begin(), itemReferences.end(), - [&](const Reference& itemReference) { return is_same_item(itemReference, reference); }); - - int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; - if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; - index = std::clamp(index, 0, (int)itemReferences.size() - 1); - - auto& itemReference = itemReferences[index]; - reference_set_timeline_item_reference(itemReference); - }; - - selected_row_references_get = [&]() - { - std::vector result{}; - for (const auto& row : timeline_item_rows_get()) - if (is_row_selected(row)) result.push_back(row_reference_get(row)); - return result; - }; - - row_drag_references_get = [&](const TimelineItemRow& row) - { - auto clicked = row_reference_get(row); - if (clicked.type != LAYER && clicked.type != NULL_) return std::vector{clicked}; - - auto rows = selected_row_references_get(); - if (!is_row_reference_selected(clicked)) rows = {clicked}; - if (rows.empty()) rows = {clicked}; - - std::erase_if(rows, [&](const TimelineRowReference& rowReference) { return rowReference.type != clicked.type; }); - if (rows.empty()) rows = {clicked}; - return rows; - }; - - item_remove = [&]() - { - auto targetRows = selected_row_references_get(); - std::map> targetIds{}; - std::map> targetGroupIds{}; - for (auto row : targetRows) - { - if (row.type != LAYER && row.type != NULL_) continue; - if (row.isGroup) - targetGroupIds[row.type].insert(row.id); - else - targetIds[row.type].insert(row.id); - } - auto animationIndex = reference.animationIndex; - if (!animation) return; - if (targetIds.empty() && targetGroupIds.empty()) return; - edit_command_push(EDIT_REMOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - for (auto targetType : {LAYER, NULL_}) - { - auto containerType = container_type_get(targetType); - auto targetTrackType = track_type_get(targetType); - auto container = child_first_get(*animation, containerType); - if (!container) continue; - auto ids = targetIds.contains(targetType) ? targetIds.at(targetType) : std::set{}; - auto groupIds = - targetGroupIds.contains(targetType) ? targetGroupIds.at(targetType) : std::set{}; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && groupIds.contains(item.id)) - { - container->children.erase(container->children.begin() + i); - continue; - } - if (item.type == targetTrackType && - (ids.contains(track_id_get(item, targetType)) || groupIds.contains(item.groupId))) - container->children.erase(container->children.begin() + i); - } - } - reference_clear_for(document); - group_selection_reset_for(document); - }); - }; - - item_references_groupable_get = [&]() - { - if (!document.groupReferences.empty()) return std::vector{}; - auto selectedItems = item_references_for_current_get(); - std::erase_if(selectedItems, [](const Reference& itemReference) - { return itemReference.itemType != LAYER && itemReference.itemType != NULL_; }); - if (selectedItems.empty()) return std::vector{}; - auto itemType = selectedItems.begin()->itemType; - for (const auto& itemReference : selectedItems) - if (itemReference.itemType != itemType) return std::vector{}; - - std::vector result{}; - for (const auto& row : timeline_item_rows_get()) - { - if (row.isGroup || row.type != itemType) continue; - auto itemReference = item_reference_get(row.type, row.id, NONE, -1); - if (!selectedItems.contains(itemReference)) continue; - if (row.groupId != -1) return std::vector{}; - result.push_back(itemReference); - } - return result; - }; - - item_group = [&]() - { - auto targetReferences = item_references_groupable_get(); - if (targetReferences.empty()) return; - auto targetType = targetReferences.front().itemType; - auto animationIndex = reference.animationIndex; - auto groupName = std::string(localize.get(TEXT_NEW_GROUP)); - - edit_command_push(EDIT_GROUP_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - - auto containerType = container_type_get(targetType); - auto targetTrackType = track_type_get(targetType); - auto container = child_first_get(*animation, containerType); - if (!container) return; - - std::set targetIds{}; - for (auto itemReference : targetReferences) - targetIds.insert(itemReference.itemID); - - auto group = element_make(ElementType::GROUP); - group.id = element_child_next_id_get(*container, ElementType::GROUP); - group.name = groupName; - group.isExpanded = true; - auto root = element_make(ElementType::ROOT_ANIMATION); - root.children.push_back(element_make(ElementType::FRAME)); - group.children.push_back(root); - int insertIndex = (int)container->children.size(); - - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == targetTrackType && targetIds.contains(track_id_get(item, targetType))) - { - insertIndex = std::min(insertIndex, i); - item.groupId = group.id; - } - } - - if (insertIndex == (int)container->children.size()) return; - insertIndex = std::clamp(insertIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + insertIndex, group); - - document.items.references.clear(); - for (auto itemReference : targetReferences) - document.items.references.insert(itemReference); - document.reference = targetReferences.front(); - frames_selection_reset_for(document); - }); - }; - - rows_move_to_row = [&](std::vector draggedRows, TimelineItemRow targetRow, bool isDropAfter, - bool isDropIntoGroup = false) - { - if (draggedRows.empty()) return; - auto targetType = draggedRows.front().type; - if (targetType != LAYER && targetType != NULL_) return; - for (const auto& draggedRow : draggedRows) - if (draggedRow.type != targetType) return; - - if (targetRow.isGroup && targetRow.type != targetType) return; - if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && - targetRow.type != TRIGGER) - return; - - auto animationIndex = reference.animationIndex; - edit_command_push( - EDIT_MOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - auto container = child_first_get(*animation, container_type_get(targetType)); - if (!container) return; - auto targetTrackType = track_type_get(targetType); - - std::set draggedIds{}; - std::set draggedGroupIds{}; - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - draggedGroupIds.insert(draggedRow.id); - else - draggedIds.insert(draggedRow.id); - } - - if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; - - std::vector movedItems{}; - for (const auto& item : container->children) - { - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = - item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) movedItems.push_back(item); - } - if (movedItems.empty()) return; - - if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; - - auto row_index_get = [&](const TimelineItemRow& row) - { - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; - if (!row.isGroup && row.type == targetType && item.type == targetTrackType && - track_id_get(item, targetType) == row.id) - return i; - } - return -1; - }; - auto group_end_index_get = [&](int groupId) - { - int result = -1; - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); - if (item.type == targetTrackType && item.groupId == groupId) result = std::max(result, i); - } - return result; - }; - - int targetIndex = (int)container->children.size(); - if (targetRow.isGroup || targetRow.type == targetType) - { - auto rowIndex = row_index_get(targetRow); - if (rowIndex == -1) return; - if (targetRow.isGroup) - { - auto groupEndIndex = group_end_index_get(targetRow.id); - if (targetType == LAYER) - targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; - else - targetIndex = rowIndex + isDropAfter; - } - else - targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); - } - - int removedBeforeTarget = 0; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = - item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) - { - if (i < targetIndex) ++removedBeforeTarget; - container->children.erase(container->children.begin() + i); - } - } - - auto targetGroupId = -1; - if (targetRow.isGroup && isDropIntoGroup) - targetGroupId = targetRow.id; - else if (targetRow.type == targetType) - targetGroupId = targetRow.groupId; - - for (auto& item : movedItems) - if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) item.groupId = targetGroupId; - - targetIndex -= removedBeforeTarget; - targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), movedItems.end()); - - document.items.references.clear(); - document.groupReferences.clear(); - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - document.groupReferences.insert({draggedRow.animationIndex, draggedRow.type, draggedRow.id}); - else - document.items.references.insert(row_item_reference_get(draggedRow)); - } - if (!document.items.references.empty()) - document.reference = *document.items.references.begin(); - else - document.reference = {animationIndex}; - frames_selection_reset_for(document); - }); - }; - - fit_animation_length = [&]() - { - if (!animation) return; - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->frameNum = animation_length_get(*animation); - }); - }; - - frame_references_copy = [&](const std::set& selectedFrames) - { - if (!animation || selectedFrames.empty()) return; - - std::string clipboardString{}; - for (auto frameReference : selectedFrames) - { - auto item = - item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; - if (!frame) continue; - auto parentType = TYPE_TRACKS[frameReference.itemType]; - clipboardString += element_to_string(*frame, parentType); - } - if (!clipboardString.empty()) clipboard.set(clipboardString); - }; - - copy = [&]() - { - auto selectedFrames = copy_frame_references_get(); - if (selectedFrames.empty()) return; - - frame_references_copy(selectedFrames); - }; - - cut = [&]() - { - auto selectedFrames = frame_references_for_current_get(); - if (selectedFrames.empty()) return; - frame_references_copy(selectedFrames); - auto trackReferences = track_references_from_frame_references_get(selectedFrames); - tracks_edit_command_push(EDIT_CUT_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { frames_delete_for(document, selectedFrames); }); - }; - - paste = [&]() - { - auto targetReference = reference; - auto selectedFrames = frame_references_for_current_get(); - auto clipboardString = clipboard.get(); - if (clipboardString.empty()) return; - auto targetHoveredTime = hoveredTime; - auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); - command_push( - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetReference.animationIndex); - if (!animation) return; - if (auto item = command_item_reference_get(document, targetReference)) - { - document.snapshots.tracks_push(message, {targetReference}); - std::set indices{}; - std::string errorString{}; - int insertIndex = (int)item->children.size(); - std::set selectedIndices{}; - for (auto frameReference : selectedFrames) - if (is_same_item(frameReference, targetReference)) selectedIndices.insert(frameReference.frameIndex); - - if (!selectedIndices.empty()) - insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); - else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) - insertIndex = targetReference.frameIndex + 1; - - auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; - if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) - { - if (targetReference.itemType != LAYER) - { - for (auto i : indices) - if (auto frame = track_frame_get(*item, i); frame) - { - frame->regionId = -1; - frame->crop = {}; - frame->size = {}; - frame->pivot = {}; - } - } - else if (targetReference.itemID != -1) - { - auto layer = command_layer_get(document, targetReference.itemID); - auto spritesheet = layer ? command_spritesheet_get(document, layer->spritesheetId) : nullptr; - - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame || frame->regionId == -1) continue; - auto region = - spritesheet ? child_id_get(*spritesheet, ElementType::REGION, frame->regionId) : nullptr; - if (!region) frame->regionId = -1; - } - } - - std::set pastedSelection{}; - for (auto i : indices) - { - auto pastedReference = targetReference; - pastedReference.frameIndex = i; - pastedSelection.insert(pastedReference); - } - document.reference = targetReference; - document.reference.frameIndex = *indices.begin(); - document.frame_references_set(std::move(pastedSelection)); - document.change(Document::FRAMES); - } - else - { - document.snapshots.pendingStep.reset(); - toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); - logger.error( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), errorString)); - } - } - else - { - toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); - } - }); - }; - - context_menu = [&]() - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED)) cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED)) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED)) paste(); - if (shortcut(manager.chords[SHORTCUT_SPLIT], shortcut::FOCUSED)) frame_split(); - if (shortcut(manager.chords[SHORTCUT_BAKE], shortcut::FOCUSED)) frames_bake(); - if (shortcut(manager.chords[SHORTCUT_FIT], shortcut::FOCUSED)) fit_animation_length(); - - auto make_region = [&]() - { - auto targetReference = reference; - auto frame = frame_get(); - if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; - if (frame->regionId != -1) return; - auto layer = layer_get(targetReference.itemID); - if (!layer) return; - - auto spritesheetID = layer->spritesheetId; - if (!spritesheet_get(spritesheetID)) return; - - auto settingsPtr = &settings; - command_push( - [=, this](Manager& manager, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame || frame->regionId != -1) return; - auto layer = command_layer_get(document, targetReference.itemID); - if (!layer) return; - - auto spritesheetID = layer->spritesheetId; - if (!command_spritesheet_get(document, spritesheetID)) return; - - auto region = element_make(ElementType::REGION); - region.crop = frame->crop; - region.size = frame->size; - region.pivot = frame->pivot; - region.origin = Origin::CUSTOM; - - document.spritesheet.reference = spritesheetID; - settingsPtr->windowIsRegions = true; - manager.makeRegionSpritesheetId = spritesheetID; - manager.makeRegion = region; - manager.isMakeRegionRequested = true; - }); - }; - - auto make_many_regions = [&]() - { - auto targetFrames = frame_references_for_current_get(); - std::erase_if(targetFrames, - [&](const Reference& frameReference) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, - frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; - auto layer = layer_get(frameReference.itemID); - return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); - }); - if (targetFrames.size() < 2) return; - - makeManyRegionReferences = targetFrames; - makeManyRegionsPopup.open(); - }; - - auto item = selected_item_get(); - auto frame = frame_get(); - auto selectedFrames = frame_references_for_current_get(); - auto copyFrames = copy_frame_references_get(); - auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - auto isReverseFrames = is_frames_reverse_available(selectedFrames); - auto selectedRegionFrames = selectedFrames; - std::erase_if(selectedRegionFrames, - [&](const Reference& frameReference) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return true; - auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, - frameReference.groupId); - auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; - auto layer = layer_get(frameReference.itemID); - return !frame || frame->regionId != -1 || !layer || !spritesheet_get(layer->spritesheetId); - }); - bool isMakeManyRegions = selectedRegionFrames.size() > 1; - auto selectedRootFrames = selected_root_frame_references_get(); - bool isMakeRegion = frame && reference.itemType == LAYER && reference.itemID != -1 && frame->regionId == -1 && - layer_get(reference.itemID) && spritesheet_get(layer_get(reference.itemID)->spritesheetId); - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add({.label = playback.isPlaying ? LABEL_PAUSE : LABEL_PLAY, - .shortcut = SHORTCUT_PLAY_PAUSE, - .isEnabled = []() { return true; }, - .run = [&]() { playback.toggle(); }}); - actions.add({.label = LABEL_INSERT, - .shortcut = SHORTCUT_INSERT_FRAME, - .isEnabled = [&]() { return item; }, - .run = [&]() { frame_insert(); }}); - actions.add(ACTION_DUPLICATE, [=, this]() { return !selectedBakeFrames.empty(); }, [&]() { frames_duplicate(); }); - actions.add({.label = LABEL_SPLIT, - .shortcut = SHORTCUT_SPLIT, - .isEnabled = [=, this]() { return selectedBakeFrames.size() == 1; }, - .run = [&]() { frame_split(); }}); - actions.add(ACTION_REVERSE, [=, this]() { return isReverseFrames; }, [&]() { frames_reverse(); }); - actions.separator(); - actions.add({.label = LABEL_BAKE, - .shortcut = SHORTCUT_BAKE, - .isEnabled = [=, this]() { return !selectedBakeFrames.empty(); }, - .run = [&]() { frames_bake(); }}); - actions.add({.label = LABEL_BAKE_INTO_OTHER_FRAMES, - .shortcut = -1, - .isEnabled = [=, this]() { return !selectedRootFrames.empty(); }, - .run = [&]() { bakeIntoOtherFramesPopup.open(); }}); - actions.add({.label = LABEL_FIT_ANIMATION_LENGTH, - .shortcut = SHORTCUT_FIT, - .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, - .run = [&]() { fit_animation_length(); }}); - actions.separator(); - actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, - .shortcut = -1, - .isEnabled = [=, this]() { return isMakeManyRegions || isMakeRegion; }, - .run = - [&]() - { - if (isMakeManyRegions) - make_many_regions(); - else - make_region(); - }}); - actions.separator(); - actions.add({.label = LABEL_DELETE, - .shortcut = SHORTCUT_REMOVE, - .isEnabled = [=, this]() { return !selectedFrames.empty(); }, - .run = [&]() { frames_delete_action(); }}); - actions.separator(); - actions.add(ACTION_CUT, [=, this]() { return !selectedFrames.empty(); }, cut); - actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, copy); - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, paste); - actions_context_window_draw("##Context Menu", actions, settings); - - ImGui::PopStyleVar(2); - }; - - item_base_properties_open = [&](int type, int id) - { - if (auto row = anm2ed::track_container_get((ItemType)type)) manager.item_properties_open(row->element, id); - }; - - group_properties_close = [&]() - { - groupName.clear(); - groupAnimationIndex = -1; - groupType = NONE; - groupId = -1; - groupPropertiesPopup.close(); - }; - - group_properties_open = [&](const TimelineItemRow& row, const Element& group) - { - groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; - groupAnimationIndex = reference.animationIndex; - groupType = row.type; - groupId = row.id; - groupPropertiesPopup.open(); - }; - - group_properties_update = [&]() - { - groupPropertiesPopup.trigger(); - - if (ImGui::BeginPopupModal(groupPropertiesPopup.label(), &groupPropertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto childSize = child_size_get(1); - if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) - { - if (groupPropertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); - input_text_string(localize.get(BASIC_NAME), &groupName); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); - } - ImGui::EndChild(); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(BASIC_CONFIRM), widgetSize)) - { - auto targetName = groupName; - auto targetAnimationIndex = groupAnimationIndex; - auto targetType = groupType; - auto targetId = groupId; - edit_command_push(EDIT_RENAME_GROUP, Document::ITEMS, - [=, this](Manager&, Document& document) - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, container_type_get(targetType)) : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; - if (!group) return; - group->name = targetName; - }); - group_properties_close(); - } - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) group_properties_close(); - - ImGui::EndPopup(); - } - - groupPropertiesPopup.end(); - }; - - item_context_menu = [&]() - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - - auto& type = reference.itemType; - auto& id = reference.itemID; - auto item = selected_item_get(); - auto selectedRows = selected_row_references_get(); - auto selectedGroupableItems = item_references_groupable_get(); - auto copyFrames = copy_frame_references_get(); - TimelineItemRow selectedGroupRow{}; - Element* selectedGroup{}; - if (selectedRows.size() == 1 && selectedRows.front().isGroup) - { - auto row = selectedRows.front(); - selectedGroupRow = {.type = row.type, .id = row.id, .index = row.index, .isGroup = true}; - selectedGroup = row_group_get(selectedGroupRow); - } - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) - { return row.type == LAYER || row.type == NULL_; }); - auto item_cut = [&]() - { - if (copyFrames.empty() || !isRemoveAvailable) return; - frame_references_copy(copyFrames); - item_remove(); - }; - - if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && - ImGui::IsMouseClicked(ImGuiMouseButton_Right)) - ImGui::OpenPopup("##Items Context Menu"); - - Actions actions{}; - actions_undo_redo_add(actions, manager, document); - actions.separator(); - actions.add( - ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, - [&]() - { - if (selectedGroup) - group_properties_open(selectedGroupRow, *selectedGroup); - else - item_base_properties_open(type, id); - }); - actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); - actions.add(ACTION_REMOVE, [=, this]() { return isRemoveAvailable; }, [&]() { item_remove(); }); - actions.add(ACTION_GROUP, [=, this]() { return !selectedGroupableItems.empty(); }, [&]() { item_group(); }); - actions.separator(); - actions.add(ACTION_CUT, [=, this]() { return !copyFrames.empty() && isRemoveAvailable; }, item_cut); - actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, copy); - actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, paste); - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED) && !copyFrames.empty() && isRemoveAvailable) - item_cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && !copyFrames.empty()) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && item && !clipboard.is_empty()) paste(); - actions_popup_draw("##Items Context Menu", actions, settings); - - ImGui::PopStyleVar(2); - }; - } -} diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index 9038f38..519108e 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -24,6 +24,7 @@ #include "util/imgui/tooltip.hpp" #include "vector.hpp" +#include "window/window.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; @@ -102,11 +103,53 @@ namespace anm2ed::imgui constexpr auto FRAME_MULTIPLE = 5; constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; - constexpr auto DRAG_DROP_SOURCE_FLAGS = - ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; #define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5 + enum TimelineColor + { + COLOR_FRAME_BASE, + COLOR_FRAME_ACTIVE, + COLOR_FRAME_HOVERED, + COLOR_ITEM_BASE, + COLOR_ITEM_ACTIVE, + COLOR_ITEM_SELECTED + }; + + struct TimelineColorSet + { + const glm::vec4* light; + const glm::vec4* dark; + }; + + inline const TimelineColorSet TIMELINE_COLORS[] = {{FRAME_COLOR_LIGHT_BASE, TYPE_COLOR}, + {FRAME_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, + {FRAME_COLOR_LIGHT_HOVERED, TYPE_COLOR_HOVERED}, + {ITEM_COLOR_LIGHT_BASE, TYPE_COLOR}, + {ITEM_COLOR_LIGHT_ACTIVE, TYPE_COLOR_ACTIVE}, + {ITEM_COLOR_LIGHT_SELECTED, TYPE_COLOR_ACTIVE}}; + + enum class SnapshotKind + { + ANM2, + TRACKS, + FRAMES + }; + + inline void snapshot_take(Document& document, const std::string& message, SnapshotKind kind, + const std::set& references) + { + if (kind == SnapshotKind::ANM2) document.snapshots.anm2_push(message); + if (kind == SnapshotKind::TRACKS) document.snapshots.tracks_push(message, references); + if (kind == SnapshotKind::FRAMES) document.snapshots.frames_push(message, references); + } + + inline bool is_trigger_reference(const Reference& reference) { return reference.itemType == TRIGGER; } + + constexpr resource::icon::Type INTERPOLATION_ICONS[] = {resource::icon::UNINTERPOLATED, resource::icon::INTERPOLATED, + resource::icon::EASE_IN, resource::icon::EASE_OUT, + resource::icon::EASE_IN_OUT}; + struct TimelineItemRow { int type{NONE}; @@ -125,59 +168,8 @@ namespace anm2ed::imgui int end{}; }; - struct TimelineContext + struct TimelineContext : TimelineState { - Timeline& timeline; - bool& isDragging; - bool& isWindowHovered; - bool& isHorizontalScroll; - popup::ItemProperties& itemProperties; - PopupHelper& bakePopup; - PopupHelper& bakeIntoOtherFramesPopup; - PopupHelper& makeManyRegionsPopup; - BakeIntoOtherFramesTarget& bakeIntoOtherFramesTarget; - bool& isBakeIntoOtherFramesLayers; - bool& isBakeIntoOtherFramesNulls; - bool& isMakeManyRegionsMapFrames; - std::set& makeManyRegionReferences; - int& hoveredTime; - bool& isFrameBoxPending; - bool& isFrameBoxSelecting; - bool& isFrameBoxAdditive; - ImVec2& frameBoxStart; - ImVec2& frameBoxEnd; - std::set& frameBoxSelection; - TimelineRowReference& rowSelectionAnchor; - bool& isRowSelectionAnchorSet; - PopupHelper& groupPropertiesPopup; - std::string& groupName; - int& groupAnimationIndex; - int& groupType; - int& groupId; - Reference& draggedFrameReference; - bool& isDraggedFrameActive; - int& draggedFrameType; - int& draggedFrameIndex; - int& draggedFrameStart; - int& draggedFrameStartDuration; - std::vector& draggedFrameStartDurations; - float& draggedFrameStartMouseX; - float& draggedFrameWidth; - bool& isDraggedFrameSnapshot; - bool& frameFocusRequested; - int& frameFocusIndex; - FrameMoveDrag& frameMoveDrag; - std::vector& frameSelectionSnapshot; - std::vector& frameSelectionLocked; - bool& isFrameSelectionLocked; - Reference& frameSelectionSnapshotReference; - Reference& frameSelectionAnchor; - bool& isFrameSelectionAnchorSet; - int& animationLengthEditIndex; - std::vector& rowDragReferences; - glm::vec2& scroll; - ImGuiStyle& style; - Manager& manager; Settings& settings; Resources& resources; @@ -220,126 +212,110 @@ namespace anm2ed::imgui ImVec2 frameBoxClipMax{}; bool isFrameBoxClipSet{}; - std::function type_index{}; - std::function item_type_get{}; - std::function item_get{}; - std::function frame_get{}; - std::function selected_item_get{}; - std::function item_frame_type_get{}; - std::function item_frames_count{}; - std::function item_frame_child_index_get{}; - std::function item_frame_insert_index_get{}; - std::function layer_get{}; - std::function null_get{}; - std::function spritesheet_get{}; - std::function info_get{}; - std::function container_type_get{}; - std::function track_type_get{}; - std::function track_id_get{}; - std::function track_container_get{}; - std::function track_group_get{}; - std::function is_track_group_visible{}; - std::function row_group_get{}; - std::function group_items_count_get{}; - std::function command_animation_get{}; - std::function command_item_get{}; - std::function command_item_reference_get{}; - std::function command_frame_get{}; - std::function command_layer_get{}; - std::function command_spritesheet_get{}; - std::function command_info_get{}; - std::function item_reference_get{}; - std::function item_reference_from_frame_get{}; - std::function is_same_item{}; - std::function is_frame_reference_valid_for{}; - std::function group_selection_reset_for{}; - std::function()> frame_references_for_current_get{}; - std::function()> item_references_for_current_get{}; - std::function frames_selection_sync_for{}; - std::function item_selection_set_for{}; - std::function frame_selection_set_for{}; - std::function frame_selection_toggle_for{}; - std::function frame_selection_range_set_for{}; - std::function()> all_frame_references_for_items_get{}; - std::function is_frame_copy_item{}; - std::function()> copy_frame_references_get{}; - std::function frames_selection_reset_for{}; - std::function frames_selection_set_reference_for{}; - std::function frames_reference_normalize_for{}; - std::function reference_clear_for{}; - std::function reference_set_item_reference_for{}; - std::function reference_set_timeline_item_reference_for{}; - std::function)> command_push{}; - std::function(std::set)> track_references_from_frame_references_get{}; - std::function&)> tracks_snapshot_command_push{}; - std::function&)> frames_snapshot_command_push{}; - std::function&, - std::function)> - frames_edit_command_push{}; - std::function&, - std::function)> - tracks_edit_command_push{}; - std::function)> edit_command_push{}; - std::function type_color_base_vec{}; - std::function type_color_active_vec{}; - std::function type_color_hovered_vec{}; - std::function item_color_vec{}; - std::function item_color_active_vec{}; - std::function overlay_icon{}; - std::function frames_selection_set_reference{}; - std::function playback_stop{}; - std::function frame_insert{}; - std::function)> frames_delete_for{}; - std::function frames_delete_action{}; - std::function frames_duplicate{}; - std::function)> is_frames_reverse_available{}; - std::function frames_reverse{}; - std::function frames_bake{}; - std::function()> selected_root_frame_references_get{}; - std::function(const Document&, const Element&, BakeIntoOtherFramesTarget, bool, bool)> - item_references_for_bake_into_other_frames_get{}; - std::function is_bake_into_other_frames_ready{}; - std::function frame_root_transform_apply{}; - std::function bake_into_other_frames{}; - std::function frame_split{}; - std::function reference_clear{}; - std::function reference_set_timeline_item_reference{}; - std::function()> timeline_item_rows_get{}; - std::function()> timeline_item_references_get{}; - std::function group_reference_get{}; - std::function row_reference_get{}; - std::function row_item_reference_get{}; - std::function()> timeline_row_references_get{}; - std::function is_group_selected{}; - std::function is_row_selected{}; - std::function row_selection_clear{}; - std::function row_selection_insert{}; - std::function row_selection_erase{}; - std::function is_row_reference_selected{}; - std::function row_selection_count_get{}; - std::function row_selection_set{}; - std::function reference_set_adjacent_item{}; - std::function()> selected_row_references_get{}; - std::function(const TimelineItemRow&)> row_drag_references_get{}; - std::function item_remove{}; - std::function()> item_references_groupable_get{}; - std::function item_group{}; - std::function, TimelineItemRow, bool, bool)> rows_move_to_row{}; - std::function fit_animation_length{}; - std::function&)> frame_references_copy{}; - std::function copy{}; - std::function cut{}; - std::function paste{}; - std::function context_menu{}; - std::function item_base_properties_open{}; - std::function group_properties_close{}; - std::function group_properties_open{}; - std::function group_properties_update{}; - std::function item_context_menu{}; + Element* item_get(int type, int id = -1, int groupType = NONE, int groupId = -1); + Element* frame_get(); + Element* selected_item_get(); + Element* track_container_get(int type); + Element* track_group_get(int type, int groupId); + bool is_track_group_visible(int type, int groupId); + Element* row_group_get(const TimelineItemRow& row); + int group_items_count_get(int type, int groupId); + Element* command_item_get(Document& document, int animationIndex, int type, int id, int groupType = NONE, + int groupId = -1); + Element* command_item_reference_get(Document& document, Reference itemReference); + glm::vec4 color_get(TimelineColor, int); + template std::map> frames_by_item_get(const Range& frameReferences) + { + std::map> result{}; + for (auto frameReference : frameReferences) + result[item_reference_from_frame_get(frameReference)].insert(frameReference.frameIndex); + return result; + } + void frames_focus_sync_for(Document&); + std::set drag_frame_references_get(const Reference&); + void snapshot_command_push(StringType, SnapshotKind, const std::set&); + void edit_command_push(StringType, Document::ChangeType, std::function, + SnapshotKind = SnapshotKind::ANM2, const std::set& = {}); + Element* command_frame_get(Document& document, const Reference& targetReference); + Reference item_reference_get(int type, int id, int groupType = NONE, int groupId = -1); + Reference item_reference_from_frame_get(Reference frameReference); + bool is_same_item(const Reference& left, const Reference& right); + void group_selection_reset_for(Document& targetDocument); + std::set item_references_for_current_get(); + void frames_selection_sync_for(Document& targetDocument); + void item_selection_set_for(Document& targetDocument, Reference itemReference); + void frame_selection_set_for(Document& targetDocument, Reference frameReference); + void frame_selection_toggle_for(Document& targetDocument, Reference frameReference); + bool frame_selection_range_set_for(Document& targetDocument, Reference firstReference, Reference lastReference, + bool isAdditive); + bool is_frame_copy_item(const Reference& itemReference); + std::set copy_frame_references_get(); + void frames_selection_reset_for(Document& targetDocument); + void frames_selection_set_reference_for(Document& targetDocument); + void frames_reference_normalize_for(Document& targetDocument); + void reference_clear_for(Document& targetDocument); + void reference_set_item_reference_for(Document& targetDocument, Reference itemReference); + void reference_set_timeline_item_reference_for(Document& targetDocument, Reference itemReference); + void command_push(std::function run); + std::set track_references_from_frame_references_get(std::set frameReferences); + void overlay_icon(GLuint textureId, ImVec4 tint, bool isForced = false); + void playback_stop(); + void frame_insert(); + void frames_delete_for(Document& document, std::set selectedFrames); + void frames_delete_action(); + void frames_duplicate(); + bool is_frames_reverse_available(std::set selectedFrames); + void frames_reverse(); + void frames_bake(); + std::set selected_root_frame_references_get(); + std::set item_references_for_bake_into_other_frames_get(const Document& targetDocument, + const Element& targetAnimation, + BakeIntoOtherFramesTarget target, bool isLayers, + bool isNulls); + bool is_bake_into_other_frames_ready(); + void frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, + bool isUseRootPivot); + void bake_into_other_frames(); + void frame_split(); + void reference_clear(); + void reference_set_timeline_item_reference(Reference itemReference); + std::vector timeline_item_rows_get(); + std::vector timeline_item_references_get(); + Reference group_reference_get(const TimelineItemRow& row); + TimelineRowReference row_reference_get(const TimelineItemRow& row); + Reference row_item_reference_get(const TimelineRowReference& row); + std::vector timeline_row_references_get(); + bool is_group_selected(const TimelineItemRow& row); + bool is_row_selected(const TimelineItemRow& row); + void row_selection_clear(); + void row_selection_insert(const TimelineRowReference& row); + void row_selection_erase(const TimelineRowReference& row); + bool is_row_reference_selected(const TimelineRowReference& row); + std::size_t row_selection_count_get(); + void row_selection_set(const TimelineItemRow& row); + void reference_set_adjacent_item(int direction); + std::vector selected_row_references_get(); + std::vector row_drag_references_get(const TimelineItemRow& row); + void item_remove(); + std::vector item_references_groupable_get(); + void item_group(); + void rows_move_to_row(std::vector draggedRows, TimelineItemRow targetRow, bool isDropAfter, + bool isDropIntoGroup = false); + void fit_animation_length(); + void frame_references_copy(const std::set& selectedFrames); + void copy(); + void cut(); + void paste(); + void context_menu(); + void item_base_properties_open(int type, int id); + void group_properties_close(); + void group_properties_open(const TimelineItemRow& row, const Element& group); + void group_properties_update(); + void item_context_menu(); - TimelineContext(Timeline&, Manager&, Settings&, Resources&, Clipboard&); + TimelineContext(TimelineState&&, Manager&, Settings&, Resources&, Clipboard&); void update(); - void commands_bind(); + void frame_begin(); void item_child(const TimelineItemRow&, int); void items_child(); void frame_move_drag_clear(); diff --git a/src/imgui/window/timeline/edit.cpp b/src/imgui/window/timeline/edit.cpp new file mode 100644 index 0000000..a62ab4b --- /dev/null +++ b/src/imgui/window/timeline/edit.cpp @@ -0,0 +1,938 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::frame_insert() + { + auto targetReference = reference; + auto targetFrameTime = document.frameTime; + if (!animation || !command_item_reference_get(document, targetReference)) return; + + edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + auto animation = + document.anm2.element_get(ElementType::ANIMATION, targetReference.animationIndex); + auto item = command_item_reference_get(document, targetReference); + if (!animation || !item) return; + + auto newReference = targetReference; + + if (targetReference.itemType == TRIGGER) + { + for (auto& trigger : item->children) + if (targetFrameTime == trigger.atFrame) return; + + auto addFrame = element_make(ElementType::TRIGGER); + addFrame.atFrame = targetFrameTime; + item->children.push_back(addFrame); + frames_sort_by_at_frame(*item); + newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); + } + else + { + auto frame = command_frame_get(document, targetReference); + auto framesCount = track_frames_count_get(*item); + if (frame) + { + auto addFrame = *frame; + auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); + auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, addFrame); + newReference.frameIndex = insertIndex; + } + else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) + { + item->children.emplace_back(*lastFrame); + newReference.frameIndex = framesCount; + } + else + { + item->children.emplace_back(element_make(ElementType::FRAME)); + newReference.frameIndex = 0; + } + } + + document.reference = newReference; + frames_selection_set_reference_for(document); + if (newReference.itemType != TRIGGER) + document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); + }, + SnapshotKind::TRACKS, {targetReference}); + } + + void TimelineContext::frames_delete_for(Document& document, std::set selectedFrames) + { + auto groupedFrames = frames_by_item_get(selectedFrames); + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + auto childIndex = track_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } + } + + auto item = command_item_reference_get(document, document.reference); + if (!item || item->children.empty()) + { + document.reference.frameIndex = -1; + frames_selection_reset_for(document); + return; + } + + document.reference.frameIndex = glm::clamp(document.reference.frameIndex, 0, (int)item->children.size() - 1); + frames_selection_set_reference_for(document); + } + + void TimelineContext::frames_delete_action() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (selectedFrames.empty()) return; + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + edit_command_push( + EDIT_DELETE_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable + { frames_delete_for(document, selectedFrames); }, SnapshotKind::TRACKS, trackReferences); + } + + void TimelineContext::frames_duplicate() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + std::erase_if(selectedFrames, is_trigger_reference); + if (selectedFrames.empty()) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + edit_command_push( + EDIT_DUPLICATE_FRAMES, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + auto groupedFrames = frames_by_item_get(selectedFrames); + + std::set duplicatedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + std::vector validIndices{}; + std::vector duplicatedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + duplicatedFrames.push_back(*frame); + } + if (validIndices.empty()) continue; + + auto insertIndex = validIndices.back() + 1; + auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, + std::make_move_iterator(duplicatedFrames.begin()), + std::make_move_iterator(duplicatedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + duplicatedSelection.insert(targetReference); + auto sourceReference = itemReference; + sourceReference.frameIndex = validIndices[offset]; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } + + if (duplicatedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); + document.frame_references_set(std::move(duplicatedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_focus_sync_for(document); + }, + SnapshotKind::TRACKS, trackReferences); + } + + bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) + { + std::map counts{}; + std::erase_if(selectedFrames, is_trigger_reference); + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + ++counts[itemReference]; + } + return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); + } + + void TimelineContext::frames_reverse() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + std::erase_if(selectedFrames, is_trigger_reference); + if (!is_frames_reverse_available(selectedFrames)) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + edit_command_push( + EDIT_REVERSE_FRAMES, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + auto groupedFrames = frames_by_item_get(selectedFrames); + + std::set reversedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; + + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item || indices.size() < 2) continue; + + std::vector validIndices{}; + std::vector reversedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + reversedFrames.push_back(std::move(*frame)); + } + if (validIndices.size() < 2) continue; + + auto insertIndex = validIndices.front(); + for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) + { + auto childIndex = track_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } + + std::ranges::reverse(reversedFrames); + auto childIndex = track_frame_insert_child_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, std::make_move_iterator(reversedFrames.begin()), + std::make_move_iterator(reversedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + reversedSelection.insert(targetReference); + auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; + auto sourceReference = itemReference; + sourceReference.frameIndex = sourceIndex; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } + + if (reversedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); + document.frame_references_set(std::move(reversedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_focus_sync_for(document); + }, + SnapshotKind::TRACKS, trackReferences); + } + + void TimelineContext::frames_bake() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + auto bakeInterval = settings.bakeInterval; + auto isRoundScale = settings.bakeIsRoundScale; + auto isRoundRotation = settings.bakeIsRoundRotation; + std::erase_if(selectedFrames, is_trigger_reference); + if (selectedFrames.empty()) return; + + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + edit_command_push( + EDIT_BAKE_FRAMES, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + auto groupedFrames = frames_by_item_get(selectedFrames); + + std::set bakedSelection{}; + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + int insertedBefore = 0; + for (auto originalIndex : indices) + { + auto i = originalIndex + insertedBefore; + auto frame = track_frame_get(*item, i); + if (!frame) continue; + + auto originalDuration = frame->duration; + frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); + + auto bakedCount = + originalDuration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)originalDuration / bakeInterval); + for (int offset = 0; offset < bakedCount; ++offset) + { + auto frameReference = itemReference; + frameReference.frameIndex = i + offset; + bakedSelection.insert(frameReference); + } + + insertedBefore += bakedCount - 1; + } + } + + document.frame_references_set(std::move(bakedSelection)); + if (!document.frames.references.empty()) + { + frames_focus_sync_for(document); + } + else + frames_selection_reset_for(document); + }, + SnapshotKind::TRACKS, trackReferences); + } + + std::set TimelineContext::selected_root_frame_references_get() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); + return selectedFrames; + } + + std::set TimelineContext::item_references_for_bake_into_other_frames_get(const Document& targetDocument, + const Element& targetAnimation, + BakeIntoOtherFramesTarget target, + bool isLayers, bool isNulls) + { + std::set result{}; + auto animationIndex = targetDocument.reference.animationIndex; + if (target == BakeIntoOtherFramesTarget::CURRENT_SELECTION) + { + for (auto itemReference : targetDocument.items.references) + { + itemReference.frameIndex = -1; + if (itemReference.itemType == LAYER || itemReference.itemType == NULL_) result.insert(itemReference); + } + return result; + } + + for (const auto& row : TRACK_CONTAINERS) + { + auto container = child_first_get(targetAnimation, row.container); + if (!container || !(row.itemType == ItemType::LAYER ? isLayers : isNulls)) continue; + tracks_each(*container, row.track, + [&](const Element& track) + { + auto itemType = (int)row.itemType; + result.insert({animationIndex, itemType, anm2ed::track_id_get(track), -1, + track.groupId == -1 ? NONE : itemType, track.groupId}); + }); + } + return result; + } + + bool TimelineContext::is_bake_into_other_frames_ready() + { + auto selectedRootFrames = selected_root_frame_references_get(); + if (selectedRootFrames.empty() || !animation) return false; + auto targetItems = item_references_for_bake_into_other_frames_get( + document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); + return !targetItems.empty(); + } + + void TimelineContext::frame_root_transform_apply(Element& frame, const Element& rootFrame, bool isRoundScale, + bool isRoundRotation, bool isUseRootPivot) + { + auto rootScale = math::percent_to_unit(rootFrame.scale); + auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); + auto offset = (frame.position - pivot) * rootScale; + auto radians = glm::radians(rootFrame.rotation); + auto cos = std::cos(radians); + auto sin = std::sin(radians); + + frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); + frame.scale *= rootScale; + frame.rotation += rootFrame.rotation; + frame.tint *= rootFrame.tint; + frame.colorOffset += rootFrame.colorOffset; + + if (isRoundScale) frame.scale = glm::round(frame.scale); + if (isRoundRotation) frame.rotation = std::round(frame.rotation); + } + + void TimelineContext::bake_into_other_frames() + { + auto selectedRootFrames = selected_root_frame_references_get(); + if (selectedRootFrames.empty()) return; + if (!animation) return; + auto target = bakeIntoOtherFramesTarget; + auto isLayers = isBakeIntoOtherFramesLayers; + auto isNulls = isBakeIntoOtherFramesNulls; + auto isRoundScale = settings.bakeIsRoundScale; + auto isRoundRotation = settings.bakeIsRoundRotation; + auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; + auto isUseRootPivot = settings.bakeIsUseRootPivot; + auto targetItems = item_references_for_bake_into_other_frames_get( + document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); + auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); + trackReferences.insert(targetItems.begin(), targetItems.end()); + edit_command_push( + EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, document.reference.animationIndex); + if (!animation) return; + auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); + for (auto rootReference : selectedRootFrames) + if (!is_same_item(rootReference, rootItemReference)) return; + auto root = command_item_reference_get(document, rootItemReference); + if (!root) return; + + std::vector spans{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); + spans.push_back({start, start + rootFrame->duration}); + } + if (spans.empty()) return; + auto is_spanned = [&](int time) + { + return std::ranges::any_of(spans, + [&](RootFrameSpan span) { return time >= span.start && time < span.end; }); + }; + + auto targetItems = + item_references_for_bake_into_other_frames_get(document, *animation, target, isLayers, isNulls); + if (targetItems.empty()) return; + + for (auto itemReference : targetItems) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; + + if (isMatchRootInterpolation) + { + std::vector bakeIndices{}; + auto frameType = track_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) + { + if (frame.type != frameType) continue; + if (is_spanned((int)frame_time_from_index_get(*item, frameIndex))) bakeIndices.push_back(frameIndex); + ++frameIndex; + } + for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) + frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); + } + + auto frameType = track_frame_type_get(*item); + int frameIndex{}; + for (auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = (int)frame_time_from_index_get(*item, frameIndex++); + if (is_spanned(frameStart)) + frame_root_transform_apply(frame, frame_generate(*root, (float)frameStart), isRoundScale, + isRoundRotation, isUseRootPivot); + } + } + + std::set selectedRootFrameIndices{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + selectedRootFrameIndices.insert(rootReference.frameIndex); + } + if (selectedRootFrameIndices.empty()) return; + + std::vector rootFrames{}; + std::set defaultRootSelection{}; + int frameIndex{}; + int rewrittenFrameIndex{}; + int defaultDuration{}; + auto default_root_frame_push = [&]() + { + if (defaultDuration <= 0) return; + auto frame = element_make(ElementType::FRAME); + frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); + auto defaultRootReference = rootItemReference; + defaultRootReference.frameIndex = rewrittenFrameIndex; + defaultRootSelection.insert(defaultRootReference); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + defaultDuration = 0; + }; + + for (const auto& frame : root->children) + { + if (frame.type != ElementType::FRAME) + { + default_root_frame_push(); + rootFrames.push_back(frame); + continue; + } + + if (selectedRootFrameIndices.contains(frameIndex)) + defaultDuration += frame.duration; + else + { + default_root_frame_push(); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + } + ++frameIndex; + } + default_root_frame_push(); + + root->children = std::move(rootFrames); + document.frame_references_set(std::move(defaultRootSelection)); + frames_focus_sync_for(document); + }, + SnapshotKind::TRACKS, trackReferences); + } + + void TimelineContext::frame_split() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (selectedFrames.size() != 1) return; + auto targetReference = *selectedFrames.begin(); + auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); + if (targetReference.itemType == TRIGGER) return; + + edit_command_push( + EDIT_SPLIT_FRAME, Document::FRAMES, + [=, this](Manager&, Document& document) mutable + { + if (targetReference.itemType == TRIGGER) return; + + auto item = command_item_reference_get(document, targetReference); + auto frame = command_frame_get(document, targetReference); + + if (!item || !frame) return; + + auto originalDuration = frame->duration; + if (originalDuration <= 1) return; + + auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); + int frameStart = (int)std::round(frameStartTime); + int firstDuration = splitTime - frameStart + 1; + + if (firstDuration <= 0 || firstDuration >= originalDuration) return; + + int secondDuration = originalDuration - firstDuration; + auto splitFrame = *frame; + splitFrame.duration = secondDuration; + + auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); + if (frame->interpolation != Interpolation::NONE && nextFrame) + frame_mix(splitFrame, *nextFrame, + interpolation_factor(frame->interpolation, (float)firstDuration / (float)originalDuration)); + + frame->duration = firstDuration; + auto insertIndex = track_frame_insert_child_index_get(*item, targetReference.frameIndex + 1); + item->children.insert(item->children.begin() + insertIndex, splitFrame); + document.reference = targetReference; + frames_selection_set_reference_for(document); + }, + SnapshotKind::TRACKS, {targetReference}); + } + + void TimelineContext::item_remove() + { + auto targetRows = selected_row_references_get(); + std::map> targetIds{}; + std::map> targetGroupIds{}; + for (auto row : targetRows) + { + if (row.type != LAYER && row.type != NULL_) continue; + if (row.isGroup) + targetGroupIds[row.type].insert(row.id); + else + targetIds[row.type].insert(row.id); + } + auto animationIndex = reference.animationIndex; + if (!animation) return; + if (targetIds.empty() && targetGroupIds.empty()) return; + edit_command_push(EDIT_REMOVE_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + for (auto targetType : {LAYER, NULL_}) + { + auto containerType = TYPE_CONTAINERS[targetType]; + auto targetTrackType = TYPE_TRACKS[targetType]; + auto container = child_first_get(*animation, containerType); + if (!container) continue; + auto ids = targetIds.contains(targetType) ? targetIds.at(targetType) : std::set{}; + auto groupIds = + targetGroupIds.contains(targetType) ? targetGroupIds.at(targetType) : std::set{}; + for (int i = (int)container->children.size() - 1; i >= 0; --i) + { + auto& item = container->children[i]; + if (item.type == ElementType::GROUP && groupIds.contains(item.id)) + { + container->children.erase(container->children.begin() + i); + continue; + } + if (item.type == targetTrackType && + (ids.contains(anm2ed::track_id_get(item)) || groupIds.contains(item.groupId))) + container->children.erase(container->children.begin() + i); + } + } + reference_clear_for(document); + group_selection_reset_for(document); + }); + } + + std::vector TimelineContext::item_references_groupable_get() + { + if (!document.groupReferences.empty()) return std::vector{}; + auto selectedItems = item_references_for_current_get(); + std::erase_if(selectedItems, [](const Reference& itemReference) + { return itemReference.itemType != LAYER && itemReference.itemType != NULL_; }); + if (selectedItems.empty()) return std::vector{}; + auto itemType = selectedItems.begin()->itemType; + for (const auto& itemReference : selectedItems) + if (itemReference.itemType != itemType) return std::vector{}; + + std::vector result{}; + for (const auto& row : timeline_item_rows_get()) + { + if (row.isGroup || row.type != itemType) continue; + auto itemReference = item_reference_get(row.type, row.id, NONE, -1); + if (!selectedItems.contains(itemReference)) continue; + if (row.groupId != -1) return std::vector{}; + result.push_back(itemReference); + } + return result; + } + + void TimelineContext::item_group() + { + auto targetReferences = item_references_groupable_get(); + if (targetReferences.empty()) return; + auto targetType = targetReferences.front().itemType; + auto animationIndex = reference.animationIndex; + auto groupName = std::string(localize.get(TEXT_NEW_GROUP)); + + edit_command_push(EDIT_GROUP_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + + auto containerType = TYPE_CONTAINERS[targetType]; + auto targetTrackType = TYPE_TRACKS[targetType]; + auto container = child_first_get(*animation, containerType); + if (!container) return; + + std::set targetIds{}; + for (auto itemReference : targetReferences) + targetIds.insert(itemReference.itemID); + + auto group = element_make(ElementType::GROUP); + group.id = element_child_next_id_get(*container, ElementType::GROUP); + group.name = groupName; + group.children.push_back(root_animation_make()); + int insertIndex = (int)container->children.size(); + + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type == targetTrackType && targetIds.contains(anm2ed::track_id_get(item))) + { + insertIndex = std::min(insertIndex, i); + item.groupId = group.id; + } + } + + if (insertIndex == (int)container->children.size()) return; + insertIndex = std::clamp(insertIndex, 0, (int)container->children.size()); + container->children.insert(container->children.begin() + insertIndex, group); + + document.items.references.clear(); + for (auto itemReference : targetReferences) + document.items.references.insert(itemReference); + document.reference = targetReferences.front(); + frames_selection_reset_for(document); + }); + } + + void TimelineContext::rows_move_to_row(std::vector draggedRows, TimelineItemRow targetRow, + bool isDropAfter, bool isDropIntoGroup) + { + if (draggedRows.empty()) return; + auto targetType = draggedRows.front().type; + if (targetType != LAYER && targetType != NULL_) return; + for (const auto& draggedRow : draggedRows) + if (draggedRow.type != targetType) return; + + if (targetRow.isGroup && targetRow.type != targetType) return; + if (!targetRow.isGroup && targetRow.type != targetType && targetRow.type != NONE && targetRow.type != ROOT && + targetRow.type != TRIGGER) + return; + + auto animationIndex = reference.animationIndex; + edit_command_push( + EDIT_MOVE_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + auto container = child_first_get(*animation, TYPE_CONTAINERS[targetType]); + if (!container) return; + auto targetTrackType = TYPE_TRACKS[targetType]; + + std::set draggedIds{}; + std::set draggedGroupIds{}; + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + draggedGroupIds.insert(draggedRow.id); + else + draggedIds.insert(draggedRow.id); + } + + if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; + + auto is_dragged = [&](const Element& item) + { + return (item.type == ElementType::GROUP && draggedGroupIds.contains(item.id)) || + (item.type == targetTrackType && + (draggedIds.contains(anm2ed::track_id_get(item)) || draggedGroupIds.contains(item.groupId))); + }; + std::vector movedItems{}; + std::ranges::copy_if(container->children, std::back_inserter(movedItems), is_dragged); + if (movedItems.empty()) return; + + if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; + + auto row_index_get = [&](const TimelineItemRow& row) + { + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; + if (!row.isGroup && row.type == targetType && item.type == targetTrackType && + anm2ed::track_id_get(item) == row.id) + return i; + } + return -1; + }; + auto group_end_index_get = [&](int groupId) + { + int result = -1; + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); + if (item.type == targetTrackType && item.groupId == groupId) result = std::max(result, i); + } + return result; + }; + + int targetIndex = (int)container->children.size(); + if (targetRow.isGroup || targetRow.type == targetType) + { + auto rowIndex = row_index_get(targetRow); + if (rowIndex == -1) return; + if (targetRow.isGroup) + { + auto groupEndIndex = group_end_index_get(targetRow.id); + if (targetType == LAYER) + targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; + else + targetIndex = rowIndex + isDropAfter; + } + else + targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); + } + + int removedBeforeTarget = 0; + for (int i = (int)container->children.size() - 1; i >= 0; --i) + { + if (is_dragged(container->children[i])) + { + if (i < targetIndex) ++removedBeforeTarget; + container->children.erase(container->children.begin() + i); + } + } + + auto targetGroupId = -1; + if (targetRow.isGroup && isDropIntoGroup) + targetGroupId = targetRow.id; + else if (targetRow.type == targetType) + targetGroupId = targetRow.groupId; + + for (auto& item : movedItems) + if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) item.groupId = targetGroupId; + + targetIndex -= removedBeforeTarget; + targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); + container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), movedItems.end()); + + document.items.references.clear(); + document.groupReferences.clear(); + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + document.groupReferences.insert({draggedRow.animationIndex, draggedRow.type, draggedRow.id}); + else + document.items.references.insert(row_item_reference_get(draggedRow)); + } + if (!document.items.references.empty()) + document.reference = *document.items.references.begin(); + else + document.reference = {animationIndex}; + frames_selection_reset_for(document); + }); + } + + void TimelineContext::fit_animation_length() + { + if (!animation) return; + auto animationIndex = reference.animationIndex; + edit_command_push(EDIT_FIT_ANIMATION_LENGTH, Document::ANIMATIONS, + [=, this](Manager&, Document& document) + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); + if (!animation) return; + animation->frameNum = animation_length_get(*animation); + }); + } + + void TimelineContext::frame_references_copy(const std::set& selectedFrames) + { + if (!animation || selectedFrames.empty()) return; + + std::string clipboardString{}; + for (auto frameReference : selectedFrames) + { + auto item = + item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, frameReference.groupId); + auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; + if (!frame) continue; + auto parentType = TYPE_TRACKS[frameReference.itemType]; + clipboardString += element_to_string(*frame, parentType); + } + if (!clipboardString.empty()) clipboard.set(clipboardString); + } + + void TimelineContext::copy() + { + auto selectedFrames = copy_frame_references_get(); + if (selectedFrames.empty()) return; + + frame_references_copy(selectedFrames); + } + + void TimelineContext::cut() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (selectedFrames.empty()) return; + frame_references_copy(selectedFrames); + auto trackReferences = track_references_from_frame_references_get(selectedFrames); + edit_command_push( + EDIT_CUT_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable + { frames_delete_for(document, selectedFrames); }, SnapshotKind::TRACKS, trackReferences); + } + + void TimelineContext::paste() + { + auto targetReference = reference; + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + auto clipboardString = clipboard.get(); + if (clipboardString.empty()) return; + auto targetHoveredTime = hoveredTime; + auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); + command_push( + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, targetReference.animationIndex); + if (!animation) return; + if (auto item = command_item_reference_get(document, targetReference)) + { + document.snapshots.tracks_push(message, {targetReference}); + std::set indices{}; + std::string errorString{}; + int insertIndex = (int)item->children.size(); + std::set selectedIndices{}; + for (auto frameReference : selectedFrames) + if (is_same_item(frameReference, targetReference)) selectedIndices.insert(frameReference.frameIndex); + + if (!selectedIndices.empty()) + insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); + else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) + insertIndex = targetReference.frameIndex + 1; + + auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; + if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) + { + if (targetReference.itemType != LAYER) + { + for (auto i : indices) + if (auto frame = track_frame_get(*item, i); frame) + { + frame->regionId = -1; + frame->crop = {}; + frame->size = {}; + frame->pivot = {}; + } + } + else if (targetReference.itemID != -1) + { + auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); + auto spritesheet = + layer ? document.anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame || frame->regionId == -1) continue; + auto region = + spritesheet ? child_id_get(*spritesheet, ElementType::REGION, frame->regionId) : nullptr; + if (!region) frame->regionId = -1; + } + } + + std::set pastedSelection{}; + for (auto i : indices) + { + auto pastedReference = targetReference; + pastedReference.frameIndex = i; + pastedSelection.insert(pastedReference); + } + document.reference = targetReference; + document.reference.frameIndex = *indices.begin(); + document.frame_references_set(std::move(pastedSelection)); + document.change(Document::FRAMES); + } + else + { + document.snapshots.pendingStep.reset(); + toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); + logger.error( + std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), errorString)); + } + } + else + { + toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); + } + }); + } +} diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index 8425f86..e6db6d4 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -33,20 +33,15 @@ namespace anm2ed::imgui auto trackReferences = track_references_from_frame_references_get(std::set(drag.references.begin(), drag.references.end())); trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); - tracks_edit_command_push( - EDIT_MOVE_FRAMES, Document::FRAMES, trackReferences, + edit_command_push( + EDIT_MOVE_FRAMES, Document::FRAMES, [=, this](Manager&, Document& document) mutable { auto targetItem = command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, targetGroupId); if (!targetItem) return; - std::map> groupedFrames{}; - for (auto frameReference : drag.references) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + auto groupedFrames = frames_by_item_get(drag.references); int removedBeforeTarget = 0; std::vector movedFrames; @@ -57,7 +52,7 @@ namespace anm2ed::imgui for (auto i : indices) { - auto childIndex = item_frame_child_index_get(*sourceItem, i); + auto childIndex = track_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 && @@ -68,20 +63,20 @@ namespace anm2ed::imgui for (auto it = indices.rbegin(); it != indices.rend(); ++it) { - auto childIndex = item_frame_child_index_get(*sourceItem, *it); + auto childIndex = track_frame_child_index_get(*sourceItem, *it); if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); } } if (movedFrames.empty()) return; - int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); + int desired = std::clamp(insertIndex, 0, track_frames_count_get(*targetItem)); desired -= removedBeforeTarget; - desired = std::clamp(desired, 0, item_frames_count(targetItem)); + desired = std::clamp(desired, 0, track_frames_count_get(*targetItem)); auto insertPosResult = desired; auto insertedCount = (int)movedFrames.size(); - auto childIndex = item_frame_insert_index_get(*targetItem, insertPosResult); + auto childIndex = track_frame_insert_child_index_get(*targetItem, insertPosResult); targetItem->children.insert(targetItem->children.begin() + childIndex, std::make_move_iterator(movedFrames.begin()), std::make_move_iterator(movedFrames.end())); @@ -97,16 +92,12 @@ namespace anm2ed::imgui insertPosResult, targetGroupType, targetGroupId}; document.frame_references_set(std::move(movedSelection)); document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); - frameSelectionSnapshot.assign(document.frames.selection.begin(), document.frames.selection.end()); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; + frames_focus_sync_for(document); if (targetType == LAYER) - if (auto layer = command_layer_get(document, targetID)) + if (auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetID)) document.spritesheet.reference = layer->spritesheetId; - }); + }, + SnapshotKind::TRACKS, trackReferences); } ImVec2 TimelineContext::frame_box_content_point_get() @@ -186,9 +177,9 @@ namespace anm2ed::imgui auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; if (isOnlyShowLayers && type != LAYER) isVisible = false; - auto colorVec = type_color_base_vec(type); - auto colorActiveVec = type_color_active_vec(type); - auto colorHoveredVec = type_color_hovered_vec(type); + auto colorVec = color_get(COLOR_FRAME_BASE, type); + auto colorActiveVec = color_get(COLOR_FRAME_ACTIVE, type); + auto colorHoveredVec = color_get(COLOR_FRAME_HOVERED, type); auto color = to_imvec4(colorVec); auto colorActive = to_imvec4(colorActiveVec); auto colorHovered = to_imvec4(colorHoveredVec); @@ -232,7 +223,7 @@ namespace anm2ed::imgui auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; auto rowMaxY = rowMinY + childSize.y; float selectionFrameTime{}; - auto frameType = item_frame_type_get(*item); + auto frameType = track_frame_type_get(*item); int frameIndex{}; for (const auto& frame : item->children) { @@ -387,10 +378,10 @@ namespace anm2ed::imgui { auto mouseX = mousePos.x - cursorScreenPos.x; auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = item_frames_count(item); + int dropIndex = track_frames_count_get(*item); float dropFrameTime{}; float frameTime{}; - auto frameType = item_frame_type_get(*item); + auto frameType = track_frame_type_get(*item); int frameIndex{}; for (const auto& frame : item->children) @@ -434,7 +425,7 @@ namespace anm2ed::imgui } } - auto frameType = item_frame_type_get(*item); + auto frameType = track_frame_type_get(*item); int frameIndex{}; for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) { @@ -488,22 +479,24 @@ namespace anm2ed::imgui if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) { if (type == LAYER) - if (auto layer = layer_get(id)) document.spritesheet.reference = layer->spritesheetId; + if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id)) + document.spritesheet.reference = layer->spritesheetId; if (type != TRIGGER) { if (ImGui::IsKeyDown(ImGuiMod_Alt)) { auto targetReference = frameReference; - frames_edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame) return; - frame->interpolation = frame->interpolation == Interpolation::NONE - ? Interpolation::LINEAR - : Interpolation::NONE; - }); + edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame) return; + frame->interpolation = frame->interpolation == Interpolation::NONE + ? Interpolation::LINEAR + : Interpolation::NONE; + }, + SnapshotKind::FRAMES, {targetReference}); } document.frameTime = frameTime; @@ -557,22 +550,9 @@ namespace anm2ed::imgui if (type != TRIGGER) draggedFrameStartDuration = frame.duration; draggedFrameStartDurations.clear(); if (type != TRIGGER) - { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, [](const Reference& selectedReference) - { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; - for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) + for (auto selectedReference : drag_frame_references_get(frameReference)) + if (auto selectedFrame = command_frame_get(document, selectedReference)) draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); - } - } draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; draggedFrameWidth = frameSize.x; } @@ -584,20 +564,11 @@ namespace anm2ed::imgui if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left)) { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, - [](const Reference& selectedReference) { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; + auto selectedReferences = drag_frame_references_get(frameReference); int dragDuration = 0; for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) dragDuration += selectedFrame->duration; - } + if (auto selectedFrame = command_frame_get(document, selectedReference)) + dragDuration += selectedFrame->duration; dragDuration = glm::max(1, dragDuration); frameMoveDrag = { @@ -621,33 +592,7 @@ namespace anm2ed::imgui auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); - auto icon = icon::UNINTERPOLATED; - if (type == TRIGGER) - icon = icon::TRIGGER; - else - { - switch (frame.interpolation) - { - case Interpolation::NONE: - icon = icon::UNINTERPOLATED; - break; - case Interpolation::LINEAR: - icon = icon::INTERPOLATED; - break; - case Interpolation::EASE_IN: - icon = icon::EASE_IN; - break; - case Interpolation::EASE_OUT: - icon = icon::EASE_OUT; - break; - case Interpolation::EASE_IN_OUT: - icon = icon::EASE_IN_OUT; - break; - default: - icon = icon::UNINTERPOLATED; - break; - } - } + auto icon = type == TRIGGER ? icon::TRIGGER : INTERPOLATION_ICONS[(int)frame.interpolation]; auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); ImGui::SetCursorPos(iconPos); @@ -709,7 +654,8 @@ namespace anm2ed::imgui { isDraggedFrameSnapshot = true; if (draggedFrameType == TRIGGER) - tracks_snapshot_command_push(EDIT_TRIGGER_AT_FRAME, {item_reference_from_frame_get(draggedFrameReference)}); + snapshot_command_push(EDIT_TRIGGER_AT_FRAME, SnapshotKind::TRACKS, + {item_reference_from_frame_get(draggedFrameReference)}); else { std::set draggedFrameReferences{}; @@ -718,7 +664,7 @@ namespace anm2ed::imgui else for (auto& frameDuration : draggedFrameStartDurations) draggedFrameReferences.insert(frameDuration.reference); - frames_snapshot_command_push(EDIT_FRAME_DURATION, draggedFrameReferences); + snapshot_command_push(EDIT_FRAME_DURATION, SnapshotKind::FRAMES, draggedFrameReferences); } } @@ -844,7 +790,7 @@ namespace anm2ed::imgui if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { group_selection_reset_for(document); - document.frame_references_set(all_frame_references_for_items_get()); + document.frame_references_set(document.selected_item_frame_references_get()); if (!document.frames.references.empty()) frames_selection_sync_for(document); } @@ -995,10 +941,9 @@ namespace anm2ed::imgui ImGui::SameLine(); auto item = selected_item_get(); - auto selectedFrames = frame_references_for_current_get(); + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + std::erase_if(selectedBakeFrames, is_trigger_reference); ImGui::BeginDisabled(!item); { @@ -1048,7 +993,7 @@ namespace anm2ed::imgui edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, [=, this](Manager&, Document& document) { - auto animation = command_animation_get(document, animationIndex); + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); if (!animation) return; animation->frameNum = frameNum; }); @@ -1066,7 +1011,7 @@ namespace anm2ed::imgui edit_command_push(EDIT_LOOP, Document::ANIMATIONS, [=, this](Manager&, Document& document) { - auto animation = command_animation_get(document, animationIndex); + auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); if (!animation) return; animation->isLoop = isLoop; }); @@ -1077,7 +1022,7 @@ namespace anm2ed::imgui ImGui::SameLine(); - auto info = info_get(); + auto info = element_first_get(anm2.root, ElementType::INFO); auto fps = info ? info->fps : 30; ImGui::SetNextItemWidth(widgetSize.x); if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) @@ -1085,7 +1030,7 @@ namespace anm2ed::imgui edit_command_push(EDIT_FPS, Document::INFO, [=, this](Manager&, Document& document) { - auto info = command_info_get(document); + auto info = element_first_get(document.anm2.root, ElementType::INFO); if (!info) { document.anm2.root.children.push_back(element_make(ElementType::INFO)); @@ -1098,7 +1043,7 @@ namespace anm2ed::imgui ImGui::SameLine(); - info = info_get(); + info = element_first_get(anm2.root, ElementType::INFO); auto createdBy = info ? info->createdBy : std::string{}; ImGui::SetNextItemWidth(widgetSize.x); if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) @@ -1106,7 +1051,7 @@ namespace anm2ed::imgui edit_command_push(EDIT_AUTHOR, Document::INFO, [=, this](Manager&, Document& document) { - auto info = command_info_get(document); + auto info = element_first_get(document.anm2.root, ElementType::INFO); if (!info) { document.anm2.root.children.push_back(element_make(ElementType::INFO)); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp new file mode 100644 index 0000000..b29eb44 --- /dev/null +++ b/src/imgui/window/timeline/menus.cpp @@ -0,0 +1,289 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + void TimelineContext::frame_begin() + { + frames_reference_normalize_for(document); + iconTintDefault = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : ICON_TINT_DEFAULT_DARK; + itemIconTint = isLightTheme ? ICON_TINT_DEFAULT_LIGHT : iconTintDefault; + frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; + frameBorderColorReferenced = + isLightTheme ? FRAME_BORDER_COLOR_REFERENCED_LIGHT : FRAME_BORDER_COLOR_REFERENCED_DARK; + frameMultipleOverlayColor = isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; + textMultipleColor = isLightTheme ? TEXT_MULTIPLE_COLOR_LIGHT : TEXT_MULTIPLE_COLOR_DARK; + playheadLineColor = isLightTheme ? PLAYHEAD_LINE_COLOR_LIGHT : PLAYHEAD_LINE_COLOR_DARK; + playheadIconTint = isLightTheme ? PLAYHEAD_ICON_TINT_LIGHT : iconTintDefault; + timelineBackgroundColor = + isLightTheme ? TIMELINE_BACKGROUND_COLOR_LIGHT : ImGui::GetStyleColorVec4(ImGuiCol_Header); + timelinePlayheadRectColor = isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; + timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; + itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; + } + + void TimelineContext::overlay_icon(GLuint textureId, ImVec4 tint, bool isForced) + { + if (!isForced && !isLightTheme) return; + auto min = ImGui::GetItemRectMin(); + auto max = ImGui::GetItemRectMax(); + ImGui::GetWindowDrawList()->AddImage((ImTextureID)(intptr_t)textureId, min, max, ImVec2(0, 0), ImVec2(1, 1), + ImGui::GetColorU32(tint)); + } + + void TimelineContext::playback_stop() + { + playback.isPlaying = false; + playback.isFinished = false; + playback.timing_reset(); + } + + void TimelineContext::context_menu() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + + if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED)) cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED)) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED)) paste(); + if (shortcut(manager.chords[SHORTCUT_SPLIT], shortcut::FOCUSED)) frame_split(); + if (shortcut(manager.chords[SHORTCUT_BAKE], shortcut::FOCUSED)) frames_bake(); + if (shortcut(manager.chords[SHORTCUT_FIT], shortcut::FOCUSED)) fit_animation_length(); + + auto make_region = [&]() + { + auto targetReference = reference; + auto frame = frame_get(); + if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; + if (frame->regionId != -1) return; + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); + if (!layer) return; + + auto spritesheetID = layer->spritesheetId; + if (!anm2.element_get(ElementType::SPRITESHEET, spritesheetID)) return; + + auto settingsPtr = &settings; + command_push( + [=, this](Manager& manager, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame || frame->regionId != -1) return; + auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, targetReference.itemID); + if (!layer) return; + + auto spritesheetID = layer->spritesheetId; + if (!document.anm2.element_get(ElementType::SPRITESHEET, spritesheetID)) return; + + auto region = element_make(ElementType::REGION); + region.crop = frame->crop; + region.size = frame->size; + region.pivot = frame->pivot; + region.origin = Origin::CUSTOM; + + document.spritesheet.reference = spritesheetID; + settingsPtr->windowIsRegions = true; + manager.makeRegionSpritesheetId = spritesheetID; + manager.makeRegion = region; + manager.isMakeRegionRequested = true; + }); + }; + + auto item = selected_item_get(); + auto frame = frame_get(); + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + auto copyFrames = copy_frame_references_get(); + auto selectedBakeFrames = selectedFrames; + std::erase_if(selectedBakeFrames, is_trigger_reference); + auto isReverseFrames = is_frames_reverse_available(selectedFrames); + auto is_region_makeable = [&](const Reference& frameReference) + { + if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return false; + auto frame = command_frame_get(document, frameReference); + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); + return frame && frame->regionId == -1 && layer && + anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId); + }; + auto selectedRegionFrames = selectedFrames; + std::erase_if(selectedRegionFrames, + [&](const Reference& frameReference) { return !is_region_makeable(frameReference); }); + bool isMakeManyRegions = selectedRegionFrames.size() > 1; + auto selectedRootFrames = selected_root_frame_references_get(); + bool isMakeRegion = is_region_makeable(reference); + Actions actions{}; + actions_undo_redo_add(actions, manager, document); + actions.separator(); + actions.add({.label = playback.isPlaying ? LABEL_PAUSE : LABEL_PLAY, + .shortcut = SHORTCUT_PLAY_PAUSE, + .isEnabled = []() { return true; }, + .run = [&]() { playback.toggle(); }}); + actions.add({.label = LABEL_INSERT, + .shortcut = SHORTCUT_INSERT_FRAME, + .isEnabled = [&]() { return item; }, + .run = [&]() { frame_insert(); }}); + actions.add(ACTION_DUPLICATE, [=, this]() { return !selectedBakeFrames.empty(); }, [&]() { frames_duplicate(); }); + actions.add({.label = LABEL_SPLIT, + .shortcut = SHORTCUT_SPLIT, + .isEnabled = [=, this]() { return selectedBakeFrames.size() == 1; }, + .run = [&]() { frame_split(); }}); + actions.add(ACTION_REVERSE, [=, this]() { return isReverseFrames; }, [&]() { frames_reverse(); }); + actions.separator(); + actions.add({.label = LABEL_BAKE, + .shortcut = SHORTCUT_BAKE, + .isEnabled = [=, this]() { return !selectedBakeFrames.empty(); }, + .run = [&]() { frames_bake(); }}); + actions.add({.label = LABEL_BAKE_INTO_OTHER_FRAMES, + .shortcut = -1, + .isEnabled = [=, this]() { return !selectedRootFrames.empty(); }, + .run = [&]() { bakeIntoOtherFramesPopup.open(); }}); + actions.add({.label = LABEL_FIT_ANIMATION_LENGTH, + .shortcut = SHORTCUT_FIT, + .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, + .run = [&]() { fit_animation_length(); }}); + actions.separator(); + actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, + .shortcut = -1, + .isEnabled = [=, this]() { return isMakeManyRegions || isMakeRegion; }, + .run = + [&]() + { + if (!isMakeManyRegions) return make_region(); + makeManyRegionReferences = selectedRegionFrames; + makeManyRegionsPopup.open(); + }}); + actions.separator(); + actions.add({.label = LABEL_DELETE, + .shortcut = SHORTCUT_REMOVE, + .isEnabled = [=, this]() { return !selectedFrames.empty(); }, + .run = [&]() { frames_delete_action(); }}); + actions.separator(); + actions.add(ACTION_CUT, [=, this]() { return !selectedFrames.empty(); }, [this]() { cut(); }); + actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, [this]() { copy(); }); + actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, [this]() { paste(); }); + actions_context_window_draw("##Context Menu", actions, settings); + + ImGui::PopStyleVar(2); + } + + void TimelineContext::item_base_properties_open(int type, int id) + { + if (auto row = anm2ed::track_container_get((ItemType)type)) manager.item_properties_open(row->element, id); + } + + void TimelineContext::group_properties_close() + { + groupName.clear(); + groupAnimationIndex = -1; + groupType = NONE; + groupId = -1; + groupPropertiesPopup.close(); + } + + void TimelineContext::group_properties_open(const TimelineItemRow& row, const Element& group) + { + groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; + groupAnimationIndex = reference.animationIndex; + groupType = row.type; + groupId = row.id; + groupPropertiesPopup.open(); + } + + void TimelineContext::group_properties_update() + { + groupPropertiesPopup.trigger(); + + if (ImGui::BeginPopupModal(groupPropertiesPopup.label(), &groupPropertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) + { + auto childSize = child_size_get(1); + if (ImGui::BeginChild("##Group Properties Child", childSize, ImGuiChildFlags_Borders)) + { + if (groupPropertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); + input_text_string(localize.get(BASIC_NAME), &groupName); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); + } + ImGui::EndChild(); + + auto result = window_popup_buttons_draw(manager, localize.get(BASIC_CONFIRM)); + if (result == PopupButton::CONFIRM) + { + auto targetName = groupName; + auto targetAnimationIndex = groupAnimationIndex; + auto targetType = groupType; + auto targetId = groupId; + edit_command_push(EDIT_RENAME_GROUP, Document::ITEMS, + [=, this](Manager&, Document& document) + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = + animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; + auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; + if (!group) return; + group->name = targetName; + }); + } + if (result != PopupButton::NONE) group_properties_close(); + + ImGui::EndPopup(); + } + + groupPropertiesPopup.end(); + } + + void TimelineContext::item_context_menu() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + + auto& type = reference.itemType; + auto& id = reference.itemID; + auto item = selected_item_get(); + auto selectedRows = selected_row_references_get(); + auto selectedGroupableItems = item_references_groupable_get(); + auto copyFrames = copy_frame_references_get(); + TimelineItemRow selectedGroupRow{}; + Element* selectedGroup{}; + if (selectedRows.size() == 1 && selectedRows.front().isGroup) + { + auto row = selectedRows.front(); + selectedGroupRow = {.type = row.type, .id = row.id, .index = row.index, .isGroup = true}; + selectedGroup = row_group_get(selectedGroupRow); + } + auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) + { return row.type == LAYER || row.type == NULL_; }); + auto item_cut = [&]() + { + if (copyFrames.empty() || !isRemoveAvailable) return; + frame_references_copy(copyFrames); + item_remove(); + }; + + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlappedByWindow) && + ImGui::IsMouseClicked(ImGuiMouseButton_Right)) + ImGui::OpenPopup("##Items Context Menu"); + + Actions actions{}; + actions_undo_redo_add(actions, manager, document); + actions.separator(); + actions.add( + ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, + [&]() + { + if (selectedGroup) + group_properties_open(selectedGroupRow, *selectedGroup); + else + item_base_properties_open(type, id); + }); + actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); + actions.add(ACTION_REMOVE, [=, this]() { return isRemoveAvailable; }, [&]() { item_remove(); }); + actions.add(ACTION_GROUP, [=, this]() { return !selectedGroupableItems.empty(); }, [&]() { item_group(); }); + actions.separator(); + actions.add(ACTION_CUT, [=, this]() { return !copyFrames.empty() && isRemoveAvailable; }, item_cut); + actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, [this]() { copy(); }); + actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, [this]() { paste(); }); + if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED) && !copyFrames.empty() && isRemoveAvailable) + item_cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && !copyFrames.empty()) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && item && !clipboard.is_empty()) paste(); + actions_popup_draw("##Items Context Menu", actions, settings); + + ImGui::PopStyleVar(2); + } +} diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp index 20afaf8..7eefb97 100644 --- a/src/imgui/window/timeline/popups.cpp +++ b/src/imgui/window/timeline/popups.cpp @@ -31,21 +31,14 @@ namespace anm2ed::imgui input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); - auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(LABEL_MAKE_MANY_REGIONS), widgetSize)) - { - auto targetFrames = makeManyRegionReferences; - auto format = settings.generateRegionNameFormat; - auto mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; - edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, - [=, this](Manager&, Document& document) mutable - { document.anm2.regions_generate({}, targetFrames, format, mapping); }); - makeManyRegionsPopup.close(); - } - - ImGui::SameLine(); - - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) makeManyRegionsPopup.close(); + auto result = window_popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); + if (result == PopupButton::CONFIRM) + edit_command_push( + EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, + [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, + mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE]( + Manager&, Document& document) { document.anm2.regions_generate({}, targetFrames, format, mapping); }); + if (result != PopupButton::NONE) makeManyRegionsPopup.close(); ImGui::EndPopup(); } @@ -165,80 +158,51 @@ namespace anm2ed::imgui document.frameTime = playback.time; } - static bool isShortenChordHeld = false; - auto isShortenFrame = shortcut(manager.chords[SHORTCUT_SHORTEN_FRAME], shortcut::GLOBAL); - - if (isShortenFrame) + struct FrameResize { - - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + int shortcut; + StringType edit; + int delta; + }; + constexpr FrameResize FRAME_RESIZES[] = {{SHORTCUT_SHORTEN_FRAME, EDIT_SHORTEN_FRAME, -1}, + {SHORTCUT_EXTEND_FRAME, EDIT_EXTEND_FRAME, 1}}; + static bool isResizeChordHeld[std::size(FRAME_RESIZES)]{}; + for (int i = 0; i < (int)std::size(FRAME_RESIZES); ++i) + { + auto resize = FRAME_RESIZES[i]; + auto isPressed = shortcut(manager.chords[resize.shortcut], shortcut::GLOBAL); + auto selectedFrames = + isPressed ? document.frame_references_get(Document::FrameReferenceFallback::NONE) : std::set{}; + std::erase_if(selectedFrames, is_trigger_reference); if (!selectedFrames.empty()) { - if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames); + if (!isResizeChordHeld[i]) snapshot_command_push(resize.edit, SnapshotKind::FRAMES, selectedFrames); command_push( [=, this](Manager&, Document& document) { for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); - } + if (auto frame = command_frame_get(document, frameReference)) + frame->duration = + std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); document.change(Document::FRAMES); }); } + isResizeChordHeld[i] = isPressed; } - isShortenChordHeld = isShortenFrame; - - static bool isExtendChordHeld = false; - auto isExtendFrame = shortcut(manager.chords[SHORTCUT_EXTEND_FRAME], shortcut::GLOBAL); - if (isExtendFrame) - { - - auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); - if (!selectedFrames.empty()) - { - if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames); - command_push( - [=, this](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); - } - document.change(Document::FRAMES); - }); - } - } - isExtendChordHeld = isExtendFrame; auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], shortcut::GLOBAL); auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], shortcut::GLOBAL); auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], shortcut::GLOBAL); auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL); - if (isPreviousFrame) - if (auto item = selected_item_get(); item && !item->children.empty()) - reference.frameIndex = glm::clamp(--reference.frameIndex, 0, (int)item->children.size() - 1); - - if (isNextFrame) - if (auto item = selected_item_get(); item && !item->children.empty()) - reference.frameIndex = glm::clamp(++reference.frameIndex, 0, (int)item->children.size() - 1); - if (isPreviousFrame || isNextFrame) - { if (auto item = selected_item_get(); item && !item->children.empty()) { - frames_selection_set_reference(); + reference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, + (int)item->children.size() - 1); + frames_selection_set_reference_for(document); document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); } - } if (isPreviousItem) reference_set_adjacent_item(-1); if (isNextItem) reference_set_adjacent_item(1); diff --git a/src/imgui/window/timeline/selection.cpp b/src/imgui/window/timeline/selection.cpp new file mode 100644 index 0000000..d4b9fe0 --- /dev/null +++ b/src/imgui/window/timeline/selection.cpp @@ -0,0 +1,589 @@ +#include "context.hpp" + +namespace anm2ed::imgui +{ + Element* TimelineContext::item_get(int type, int id, int groupType, int groupId) + { + return animation ? animation_item_get(*animation, (ItemType)(type), id, groupType, groupId) : nullptr; + } + + Element* TimelineContext::track_container_get(int type) + { + return animation ? child_first_get(*animation, TYPE_CONTAINERS[type]) : nullptr; + } + + Element* TimelineContext::track_group_get(int type, int groupId) + { + auto container = track_container_get(type); + return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr; + } + + bool TimelineContext::is_track_group_visible(int type, int groupId) + { + if (groupId == -1) return true; + auto group = track_group_get(type, groupId); + return !group || group->isVisible; + } + + Element* TimelineContext::row_group_get(const TimelineItemRow& row) + { + return row.isGroup ? track_group_get(row.type, row.id) : nullptr; + } + + int TimelineContext::group_items_count_get(int type, int groupId) + { + auto container = track_container_get(type); + auto trackType = TYPE_TRACKS[type]; + int count{}; + if (!container) return count; + for (auto& item : container->children) + if (item.type == trackType && item.groupId == groupId) ++count; + return count; + } + + Element* TimelineContext::command_item_reference_get(Document& document, Reference itemReference) + { + itemReference.frameIndex = -1; + return document.anm2.element_get(itemReference); + } + + Element* TimelineContext::command_frame_get(Document& document, const Reference& targetReference) + { + return targetReference.frameIndex < 0 ? nullptr : document.anm2.element_get(targetReference); + } + + Element* TimelineContext::command_item_get(Document& document, int animationIndex, int type, int id, int groupType, + int groupId) + { + return document.anm2.element_get(Reference{animationIndex, type, id, -1, groupType, groupId}); + } + + Element* TimelineContext::frame_get() { return command_frame_get(document, reference); } + + Element* TimelineContext::selected_item_get() { return command_item_reference_get(document, reference); } + + glm::vec4 TimelineContext::color_get(TimelineColor color, int type) + { + auto& colors = TIMELINE_COLORS[color]; + return isLightTheme ? colors.light[std::clamp(type, 0, TRIGGER)] : colors.dark[type]; + } + + std::set TimelineContext::track_references_from_frame_references_get(std::set frameReferences) + { + std::set result{}; + for (auto frameReference : frameReferences) + result.insert(item_reference_from_frame_get(frameReference)); + return result; + } + + void TimelineContext::frames_focus_sync_for(Document& targetDocument) + { + frames_selection_sync_for(targetDocument); + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = targetDocument.reference.frameIndex; + frameFocusRequested = true; + } + + std::set TimelineContext::drag_frame_references_get(const Reference& frameReference) + { + auto selectedReferences = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + std::erase_if(selectedReferences, is_trigger_reference); + return selectedReferences.empty() ? std::set{frameReference} : selectedReferences; + } + + void TimelineContext::snapshot_command_push(StringType messageType, SnapshotKind kind, + const std::set& references) + { + command_push([message = std::string(localize.get(messageType)), kind, references](Manager&, Document& document) + { snapshot_take(document, message, kind, references); }); + } + + void TimelineContext::edit_command_push(StringType messageType, Document::ChangeType changeType, + std::function run, SnapshotKind kind, + const std::set& references) + { + command_push( + [message = std::string(localize.get(messageType)), changeType, run, kind, references](Manager& manager, + Document& document) + { + snapshot_take(document, message, kind, references); + run(manager, document); + document.change(changeType); + }); + } + + Reference TimelineContext::item_reference_get(int type, int id, int groupType, int groupId) + { + return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; + } + + Reference TimelineContext::item_reference_from_frame_get(Reference frameReference) + { + frameReference.frameIndex = -1; + return frameReference; + } + + bool TimelineContext::is_same_item(const Reference& left, const Reference& right) + { + return left.animationIndex == right.animationIndex && left.itemType == right.itemType && + left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; + } + + void TimelineContext::group_selection_reset_for(Document& targetDocument) + { + targetDocument.groupReferences.clear(); + isRowSelectionAnchorSet = false; + } + + std::set TimelineContext::item_references_for_current_get() + { + std::set result = document.items.references; + if (result.empty() && reference.itemType != NONE) + { + auto itemReference = reference; + itemReference.frameIndex = -1; + result.insert(itemReference); + } + return result; + } + + void TimelineContext::frames_selection_sync_for(Document& targetDocument) + { + auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + targetDocument.frame_references_set(std::move(selectedFrames)); + frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); + frameSelectionSnapshotReference = targetDocument.reference; + } + + void TimelineContext::item_selection_set_for(Document& targetDocument, Reference itemReference) + { + itemReference.frameIndex = -1; + targetDocument.items.references = {itemReference}; + } + + void TimelineContext::frame_selection_set_for(Document& targetDocument, Reference frameReference) + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + targetDocument.frame_references_set({frameReference}); + frames_selection_sync_for(targetDocument); + } + + void TimelineContext::frame_selection_toggle_for(Document& targetDocument, Reference frameReference) + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + auto selection = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + auto itemReference = item_reference_from_frame_get(frameReference); + if (selection.contains(frameReference)) + { + if (selection.size() > 1) selection.erase(frameReference); + bool isItemStillSelected{}; + for (const auto& selectedFrame : selection) + if (is_same_item(selectedFrame, itemReference)) isItemStillSelected = true; + if (!isItemStillSelected && targetDocument.items.references.size() > 1) + targetDocument.items.references.erase(itemReference); + } + else + { + selection.insert(frameReference); + targetDocument.items.references.insert(itemReference); + } + targetDocument.reference = frameReference; + targetDocument.frame_references_set(std::move(selection)); + frames_selection_sync_for(targetDocument); + } + + bool TimelineContext::frame_selection_range_set_for(Document& targetDocument, Reference firstReference, + Reference lastReference, bool isAdditive) + { + group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; + if (!is_same_item(firstReference, lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) + return false; + + auto item = command_item_reference_get(targetDocument, lastReference); + if (!item) return false; + if (firstReference.frameIndex >= (int)item->children.size() || + lastReference.frameIndex >= (int)item->children.size()) + return false; + + auto firstIndex = firstReference.frameIndex; + auto lastIndex = lastReference.frameIndex; + if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); + auto selectedFrames = isAdditive ? targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE) + : std::set{}; + + for (int i = firstIndex; i <= lastIndex; ++i) + { + auto frameReference = lastReference; + frameReference.frameIndex = i; + selectedFrames.insert(frameReference); + } + + targetDocument.reference = lastReference; + targetDocument.frame_references_set(std::move(selectedFrames)); + frames_selection_sync_for(targetDocument); + return true; + } + + bool TimelineContext::is_frame_copy_item(const Reference& itemReference) + { + return itemReference.itemType == ROOT || itemReference.itemType == LAYER || itemReference.itemType == NULL_; + } + + std::set TimelineContext::copy_frame_references_get() + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + if (!selectedFrames.empty()) return selectedFrames; + + auto selectedItems = document.items.references; + if (selectedItems.empty() && reference.itemType != NONE && reference.frameIndex < 0) + { + auto itemReference = reference; + itemReference.frameIndex = -1; + selectedItems.insert(itemReference); + } + + std::set result{}; + for (auto itemReference : selectedItems) + { + itemReference.frameIndex = -1; + if (!is_frame_copy_item(itemReference)) continue; + auto itemFrames = document.item_frame_references_get(itemReference); + result.insert(itemFrames.begin(), itemFrames.end()); + } + return result; + } + + void TimelineContext::frames_selection_reset_for(Document& targetDocument) + { + targetDocument.frame_references_clear(); + frameSelectionSnapshot.clear(); + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusRequested = false; + frameFocusIndex = -1; + frameSelectionSnapshotReference = targetDocument.reference; + } + + void TimelineContext::frames_selection_set_reference_for(Document& targetDocument) + { + auto& targetReference = targetDocument.reference; + if (targetReference.frameIndex >= 0) + { + targetDocument.editTarget = Document::EditTarget::FRAME; + targetDocument.frame_references_set({targetReference}); + } + else + targetDocument.frame_references_clear(); + frameSelectionSnapshot.assign(targetDocument.frames.selection.begin(), targetDocument.frames.selection.end()); + frameSelectionSnapshotReference = targetReference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = targetReference.frameIndex; + frameFocusRequested = targetReference.frameIndex >= 0; + } + + void TimelineContext::frames_reference_normalize_for(Document& targetDocument) + { + auto selectedFrames = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); + if (!selectedFrames.empty()) + { + targetDocument.frame_references_set(std::move(selectedFrames)); + frames_selection_sync_for(targetDocument); + return; + } + + if (targetDocument.reference.frameIndex >= 0 && !targetDocument.is_frame_reference_valid(targetDocument.reference)) + targetDocument.reference.frameIndex = -1; + } + + void TimelineContext::reference_clear_for(Document& targetDocument) + { + targetDocument.reference = {targetDocument.reference.animationIndex}; + frames_selection_reset_for(targetDocument); + targetDocument.items.references.clear(); + } + + void TimelineContext::reference_set_item_reference_for(Document& targetDocument, Reference itemReference) + { + itemReference.frameIndex = -1; + targetDocument.reference = itemReference; + frames_selection_reset_for(targetDocument); + item_selection_set_for(targetDocument, itemReference); + } + + void TimelineContext::reference_set_timeline_item_reference_for(Document& targetDocument, Reference itemReference) + { + if (itemReference.itemType == LAYER) + if (auto layer = targetDocument.anm2.element_get(ElementType::LAYER_ELEMENT, itemReference.itemID)) + targetDocument.spritesheet.reference = layer->spritesheetId; + reference_set_item_reference_for(targetDocument, itemReference); + } + + void TimelineContext::command_push(std::function run) + { + manager.command_push( + {manager.selected, [run](Manager& manager, Document& document) mutable { run(manager, document); }}); + } + + void TimelineContext::reference_clear() + { + group_selection_reset_for(document); + reference_clear_for(document); + } + + void TimelineContext::reference_set_timeline_item_reference(Reference itemReference) + { + group_selection_reset_for(document); + reference_set_timeline_item_reference_for(document, itemReference); + } + + std::vector TimelineContext::timeline_item_rows_get() + { + std::vector rows{}; + if (!animation) return rows; + + auto track_row_push = [&](const Element& item, int type, int index, int depth = 0) + { + auto rootGroupType = item.groupId == -1 ? NONE : type; + rows.push_back({.type = type, + .id = anm2ed::track_id_get(item), + .index = index, + .groupId = item.groupId, + .rootGroupType = rootGroupType, + .rootGroupId = item.groupId, + .depth = depth}); + }; + auto group_row_push = [&](const Element& group, int type, int index) + { rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); }; + auto group_root_row_push = [&](const Element& group, int type) + { rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); }; + auto group_ids_get = [](const Element& container) + { + std::set result{}; + for (const auto& item : container.children) + if (item.type == ElementType::GROUP) result.insert(item.id); + return result; + }; + + rows.push_back({.type = ROOT}); + + for (const auto& containerRow : TRACK_CONTAINERS) + { + auto container = child_first_get(*animation, containerRow.container); + if (!container) continue; + auto type = (int)containerRow.itemType; + auto isReversed = containerRow.itemType == ItemType::LAYER; + auto count = (int)container->children.size(); + auto index_get = [&](int i) { return isReversed ? count - 1 - i : i; }; + auto groupIds = group_ids_get(*container); + auto is_track_shown = [&](const Element& item) + { return item.type == containerRow.track && (settings.timelineIsShowUnused || !item.children.empty()); }; + + for (int i = 0; i < count; ++i) + { + auto index = index_get(i); + auto& item = container->children[index]; + if (item.type == ElementType::GROUP) + { + group_row_push(item, type, index); + if (!item.isExpanded) continue; + group_root_row_push(item, type); + for (int j = 0; j < count; ++j) + if (auto& child = container->children[index_get(j)]; is_track_shown(child) && child.groupId == item.id) + track_row_push(child, type, index_get(j), 1); + } + else if (is_track_shown(item) && !groupIds.contains(item.groupId)) + track_row_push(item, type, index); + } + } + + rows.push_back({.type = TRIGGER}); + return rows; + } + + std::vector TimelineContext::timeline_item_references_get() + { + std::vector itemReferences; + for (const auto& row : timeline_item_rows_get()) + { + if (row.isGroup) continue; + itemReferences.push_back({reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); + } + return itemReferences; + } + + Reference TimelineContext::group_reference_get(const TimelineItemRow& row) + { + return Reference{reference.animationIndex, row.type, row.id}; + } + + TimelineRowReference TimelineContext::row_reference_get(const TimelineItemRow& row) + { + return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, + row.index, row.rootGroupType, row.rootGroupId, row.isGroup}; + } + + Reference TimelineContext::row_item_reference_get(const TimelineRowReference& row) + { + return Reference{row.animationIndex, row.type, row.id, -1, row.groupType, row.groupId}; + } + + std::vector TimelineContext::timeline_row_references_get() + { + std::vector rowReferences; + for (const auto& row : timeline_item_rows_get()) + { + if (row.type == NONE) continue; + rowReferences.push_back(row_reference_get(row)); + } + return rowReferences; + } + + bool TimelineContext::is_group_selected(const TimelineItemRow& row) + { + return document.groupReferences.contains(group_reference_get(row)); + } + + bool TimelineContext::is_row_selected(const TimelineItemRow& row) + { + if (row.isGroup) return is_group_selected(row); + auto itemReference = item_reference_get(row.type, row.id, row.rootGroupType, row.rootGroupId); + auto isReferenced = is_same_item(reference, itemReference); + return document.items.references.contains(itemReference) || + (document.items.references.empty() && document.groupReferences.empty() && isReferenced); + } + + void TimelineContext::row_selection_clear() + { + document.items.references.clear(); + document.groupReferences.clear(); + } + + void TimelineContext::row_selection_insert(const TimelineRowReference& row) + { + if (row.isGroup) + document.groupReferences.insert({row.animationIndex, row.type, row.id}); + else + document.items.references.insert(row_item_reference_get(row)); + } + + void TimelineContext::row_selection_erase(const TimelineRowReference& row) + { + if (row.isGroup) + document.groupReferences.erase({row.animationIndex, row.type, row.id}); + else + document.items.references.erase(row_item_reference_get(row)); + } + + bool TimelineContext::is_row_reference_selected(const TimelineRowReference& row) + { + if (row.isGroup) return document.groupReferences.contains({row.animationIndex, row.type, row.id}); + return document.items.references.contains(row_item_reference_get(row)); + } + + std::size_t TimelineContext::row_selection_count_get() + { + return document.items.references.size() + document.groupReferences.size(); + } + + void TimelineContext::row_selection_set(const TimelineItemRow& row) + { + auto rowReference = row_reference_get(row); + auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); + auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); + + if (row.isGroup) + reference = {reference.animationIndex}; + else + { + if (row.type == LAYER) + if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, row.id)) + document.spritesheet.reference = layer->spritesheetId; + reference = row_item_reference_get(rowReference); + } + frames_selection_reset_for(document); + + if (isShiftDown) + { + auto rowSelection = timeline_row_references_get(); + auto anchor = isRowSelectionAnchorSet ? rowSelectionAnchor : rowReference; + auto first = std::find(rowSelection.begin(), rowSelection.end(), anchor); + auto last = std::find(rowSelection.begin(), rowSelection.end(), rowReference); + if (first == rowSelection.end() || last == rowSelection.end()) + { + if (!isCtrlDown) row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + else + { + auto firstIndex = (int)std::distance(rowSelection.begin(), first); + auto lastIndex = (int)std::distance(rowSelection.begin(), last); + if (firstIndex > lastIndex) std::swap(firstIndex, lastIndex); + if (!isCtrlDown) row_selection_clear(); + for (int i = firstIndex; i <= lastIndex; ++i) + row_selection_insert(rowSelection[i]); + if (!isRowSelectionAnchorSet) rowSelectionAnchor = rowReference; + } + } + else if (isCtrlDown) + { + if (is_row_reference_selected(rowReference) && row_selection_count_get() > 1) + row_selection_erase(rowReference); + else + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + else + { + row_selection_clear(); + row_selection_insert(rowReference); + rowSelectionAnchor = rowReference; + } + + isRowSelectionAnchorSet = true; + } + + void TimelineContext::reference_set_adjacent_item(int direction) + { + auto itemReferences = timeline_item_references_get(); + if (itemReferences.empty()) return; + + auto it = std::find_if(itemReferences.begin(), itemReferences.end(), + [&](const Reference& itemReference) { return is_same_item(itemReference, reference); }); + + int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; + if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; + index = std::clamp(index, 0, (int)itemReferences.size() - 1); + + auto& itemReference = itemReferences[index]; + reference_set_timeline_item_reference(itemReference); + } + + std::vector TimelineContext::selected_row_references_get() + { + std::vector result{}; + for (const auto& row : timeline_item_rows_get()) + if (is_row_selected(row)) result.push_back(row_reference_get(row)); + return result; + } + + std::vector TimelineContext::row_drag_references_get(const TimelineItemRow& row) + { + auto clicked = row_reference_get(row); + if (clicked.type != LAYER && clicked.type != NULL_) return std::vector{clicked}; + + auto rows = selected_row_references_get(); + if (!is_row_reference_selected(clicked)) rows = {clicked}; + if (rows.empty()) rows = {clicked}; + + std::erase_if(rows, [&](const TimelineRowReference& rowReference) { return rowReference.type != clicked.type; }); + if (rows.empty()) rows = {clicked}; + return rows; + } +} diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp index bf48618..e15453b 100644 --- a/src/imgui/window/timeline/timeline.cpp +++ b/src/imgui/window/timeline/timeline.cpp @@ -5,36 +5,9 @@ namespace anm2ed::imgui Timeline::Timeline() = default; Timeline::~Timeline() = default; - TimelineContext::TimelineContext(Timeline& timeline, Manager& manager, Settings& settings, Resources& resources, + TimelineContext::TimelineContext(TimelineState&& state, Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) - : timeline(timeline), isDragging(timeline.isDragging), isWindowHovered(timeline.isWindowHovered), - isHorizontalScroll(timeline.isHorizontalScroll), itemProperties(timeline.itemProperties), - bakePopup(timeline.bakePopup), bakeIntoOtherFramesPopup(timeline.bakeIntoOtherFramesPopup), - makeManyRegionsPopup(timeline.makeManyRegionsPopup), - bakeIntoOtherFramesTarget(timeline.bakeIntoOtherFramesTarget), - isBakeIntoOtherFramesLayers(timeline.isBakeIntoOtherFramesLayers), - isBakeIntoOtherFramesNulls(timeline.isBakeIntoOtherFramesNulls), - isMakeManyRegionsMapFrames(timeline.isMakeManyRegionsMapFrames), - makeManyRegionReferences(timeline.makeManyRegionReferences), hoveredTime(timeline.hoveredTime), - isFrameBoxPending(timeline.isFrameBoxPending), isFrameBoxSelecting(timeline.isFrameBoxSelecting), - isFrameBoxAdditive(timeline.isFrameBoxAdditive), frameBoxStart(timeline.frameBoxStart), - frameBoxEnd(timeline.frameBoxEnd), frameBoxSelection(timeline.frameBoxSelection), - rowSelectionAnchor(timeline.rowSelectionAnchor), isRowSelectionAnchorSet(timeline.isRowSelectionAnchorSet), - groupPropertiesPopup(timeline.groupPropertiesPopup), groupName(timeline.groupName), - groupAnimationIndex(timeline.groupAnimationIndex), groupType(timeline.groupType), groupId(timeline.groupId), - draggedFrameReference(timeline.draggedFrameReference), isDraggedFrameActive(timeline.isDraggedFrameActive), - draggedFrameType(timeline.draggedFrameType), draggedFrameIndex(timeline.draggedFrameIndex), - draggedFrameStart(timeline.draggedFrameStart), draggedFrameStartDuration(timeline.draggedFrameStartDuration), - draggedFrameStartDurations(timeline.draggedFrameStartDurations), - draggedFrameStartMouseX(timeline.draggedFrameStartMouseX), draggedFrameWidth(timeline.draggedFrameWidth), - isDraggedFrameSnapshot(timeline.isDraggedFrameSnapshot), frameFocusRequested(timeline.frameFocusRequested), - frameFocusIndex(timeline.frameFocusIndex), frameMoveDrag(timeline.frameMoveDrag), - frameSelectionSnapshot(timeline.frameSelectionSnapshot), frameSelectionLocked(timeline.frameSelectionLocked), - isFrameSelectionLocked(timeline.isFrameSelectionLocked), - frameSelectionSnapshotReference(timeline.frameSelectionSnapshotReference), - frameSelectionAnchor(timeline.frameSelectionAnchor), isFrameSelectionAnchorSet(timeline.isFrameSelectionAnchorSet), - animationLengthEditIndex(timeline.animationLengthEditIndex), rowDragReferences(timeline.rowDragReferences), - scroll(timeline.scroll), style(timeline.style), manager(manager), settings(settings), resources(resources), + : TimelineState(std::move(state)), manager(manager), settings(settings), resources(resources), clipboard(clipboard), document(*manager.get()), anm2(document.anm2), playback(document.playback), reference(document.reference), frames(document.frames), region(document.region) { @@ -54,14 +27,15 @@ namespace anm2ed::imgui isTextPushed = true; } - commands_bind(); + frame_begin(); draw(); } void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard) { if (!manager.get()) return; - context = std::make_unique(*this, manager, settings, resources, clipboard); + auto state = context ? std::move(static_cast(*context)) : TimelineState{}; + context = std::make_unique(std::move(state), manager, settings, resources, clipboard); context->update(); } } diff --git a/src/imgui/window/timeline/timeline.hpp b/src/imgui/window/timeline/timeline.hpp index c3df6b0..19a394e 100644 --- a/src/imgui/window/timeline/timeline.hpp +++ b/src/imgui/window/timeline/timeline.hpp @@ -57,10 +57,8 @@ namespace anm2ed::imgui ALL }; - class Timeline + struct TimelineState { - friend struct TimelineContext; - bool isDragging{}; bool isWindowHovered{}; bool isHorizontalScroll{}; @@ -110,6 +108,10 @@ namespace anm2ed::imgui std::vector rowDragReferences{}; glm::vec2 scroll{}; ImGuiStyle style{}; + }; + + class Timeline + { std::unique_ptr context{}; public: diff --git a/src/imgui/window/timeline/tracks.cpp b/src/imgui/window/timeline/tracks.cpp index b30c3ca..e4ae9a0 100644 --- a/src/imgui/window/timeline/tracks.cpp +++ b/src/imgui/window/timeline/tracks.cpp @@ -3,86 +3,256 @@ namespace anm2ed::imgui { void TimelineContext::item_child(const TimelineItemRow& row, int index) -{ - ImGui::PushID(index); + { + ImGui::PushID(index); - auto type = row.type; - auto id = row.id; - auto row_reference_make = [&]() - { return Reference{reference.animationIndex, type, id, -1, row.rootGroupType, row.rootGroupId}; }; - if (row.isGroup) + auto type = row.type; + auto id = row.id; + auto row_reference_make = [&]() + { return Reference{reference.animationIndex, type, id, -1, row.rootGroupType, row.rootGroupId}; }; + if (row.isGroup) + { + auto group = row_group_get(row); + if (!group) { - auto group = row_group_get(row); - if (!group) + ImGui::PopID(); + return; + } + + auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; + auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); + auto isGroupVisible = group->isVisible; + auto colorVec = color_get(COLOR_ITEM_BASE, type); + if (is_group_selected(row)) colorVec = color_get(COLOR_ITEM_SELECTED, type); + auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); + ImGui::PushStyleColor(ImGuiCol_ChildBg, color); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto groupChildMin = ImGui::GetWindowPos(); + auto groupChildMax = + ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, groupChildMin.y + ImGui::GetWindowSize().y); + + auto toggle_group = [&]() { - ImGui::PopID(); - return; + auto targetRow = row; + auto targetAnimationIndex = reference.animationIndex; + edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = + animation ? child_first_get(*animation, TYPE_CONTAINERS[targetRow.type]) : nullptr; + auto group = + container ? child_id_get(*container, ElementType::GROUP, targetRow.id) : nullptr; + if (!group) return; + group->isExpanded = !group->isExpanded; + }); + }; + + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::InvisibleButton("##Group Button", itemSize); + auto groupButtonMin = ImGui::GetItemRectMin(); + auto groupButtonMax = ImGui::GetItemRectMax(); + auto mousePos = ImGui::GetIO().MousePos; + auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) + { return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; }; + auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); + bool isGroupTooltipDelayed{}; + if (isGroupHovered) + { + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + isGroupTooltipDelayed = + ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); + imguiStyle.HoverDelayNormal = previousTooltipDelay; } - auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name; - auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); - auto isGroupVisible = group->isVisible; - auto colorVec = item_color_vec(type); - if (is_group_selected(row)) + if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { - if (isLightTheme) - colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; - else - colorVec = item_color_active_vec(type); + rowDragReferences = row_drag_references_get(row); + ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), + (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); + ImGui::EndDragDropSource(); } - auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER); - ImGui::PushStyleColor(ImGuiCol_ChildBg, color); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + if (ImGui::BeginDragDropTarget()) { - auto cursorPos = ImGui::GetCursorPos(); - auto groupChildMin = ImGui::GetWindowPos(); - auto groupChildMax = ImVec2(groupChildMin.x + ImGui::GetWindowSize().x, - groupChildMin.y + ImGui::GetWindowSize().y); - - auto toggle_group = [&]() + if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { - auto targetRow = row; - auto targetAnimationIndex = reference.animationIndex; - edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, container_type_get(targetRow.type)) - : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, - targetRow.id) - : nullptr; - if (!group) return; - group->isExpanded = !group->isExpanded; - }); - }; + auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; + auto dropZone = DropZone::BEFORE; + if (mousePos.y >= groupButtonMax.y - groupDropThird) + dropZone = DropZone::AFTER; + else if (mousePos.y >= groupButtonMin.y + groupDropThird) + dropZone = DropZone::INSIDE; + auto isDropAfter = dropZone != DropZone::BEFORE; + auto payloadRows = (TimelineRowReference*)payload->Data; + auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); + std::vector draggedRows(payloadRows, payloadRows + payloadCount); + auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); + for (auto draggedRow : draggedRows) + if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false; - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::InvisibleButton("##Group Button", itemSize); - auto groupButtonMin = ImGui::GetItemRectMin(); - auto groupButtonMax = ImGui::GetItemRectMax(); - auto mousePos = ImGui::GetIO().MousePos; - auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max) - { return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; }; - auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax); - bool isGroupTooltipDelayed{}; - if (isGroupHovered) - { - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - isGroupTooltipDelayed = - ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay); - imguiStyle.HoverDelayNormal = previousTooltipDelay; + if (isDropIntoGroup) + drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); + else + drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); + + if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); } + ImGui::EndDragDropTarget(); + } + ImGui::SetCursorPos(cursorPos); + auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; + ImGui::Image(resources.icons[folderIcon].id, icon_size_get()); + auto iconMin = ImGui::GetItemRectMin(); + auto iconMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icons[folderIcon].id, itemIconTint, false); + ImGui::SameLine(); + + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + + ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; + if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + { + auto targetAnimationIndex = reference.animationIndex; + auto targetType = type; + auto targetGroupId = group->id; + auto targetVisible = !isGroupVisible; + edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto animation = document.anm2.element_get(ElementType::ANIMATION, targetAnimationIndex); + auto container = + animation ? child_first_get(*animation, TYPE_CONTAINERS[targetType]) : nullptr; + if (!container) return; + auto group = child_id_get(*container, ElementType::GROUP, targetGroupId); + if (!group) return; + group->isVisible = targetVisible; + }); + } + auto visibleButtonMin = ImGui::GetItemRectMin(); + auto visibleButtonMax = ImGui::GetItemRectMax(); + overlay_icon(resources.icons[visibleIcon].id, itemIconTint, false); + ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); + + auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); + auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); + if (isGroupTooltipDelayed && !isVisibleButtonHovered) + { + ImGui::BeginTooltip(); + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopFont(); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); + auto groupItemsCount = group_items_count_get(type, group->id); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); + ImGui::EndTooltip(); + } + if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + toggle_group(); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + group_properties_open(row, *group); + else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && + ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(); + ImGui::PopID(); + return; + } + + auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); + if (type != NONE && !item) + { + ImGui::PopID(); + return; + } + auto isItemVisible = item ? item->isVisible : false; + auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; + if (item && type == ROOT && row.rootGroupId != -1) + isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); + auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; + if (isOnlyShowLayers && type != LAYER) isVisible = false; + auto isReferenced = is_same_item(reference, row_reference_make()); + auto isItemSelected = is_row_selected(row); + + auto label = [&]() -> std::string + { + if (type == LAYER) + { + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id); + if (!layer) return localize.get(TYPE_STRINGS[type]); + return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(id, layer->name, layer->spritesheetId)); + } + if (type == NULL_) + { + auto null = anm2.element_get(ElementType::NULL_ELEMENT, id); + if (!null) return localize.get(TYPE_STRINGS[type]); + return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); + } + return localize.get(TYPE_STRINGS[type]); + }(); + auto icon = TYPE_ICONS[type]; + auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint; + auto colorVec = color_get(isItemSelected && type != NONE ? COLOR_ITEM_SELECTED : COLOR_ITEM_BASE, type); + auto color = to_imvec4(colorVec); + color = !isVisible ? to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER) : color; + ImGui::PushStyleColor(ImGuiCol_ChildBg, color); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); + + if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + { + auto cursorPos = ImGui::GetCursorPos(); + auto itemChildMin = ImGui::GetWindowPos(); + auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); + + if (type != NONE) + { + ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); + ImGui::SetNextItemAllowOverlap(); + ImGui::SetNextItemStorageID(id); + ImGui::InvisibleButton("##Item Button", itemSize); + auto itemButtonMin = ImGui::GetItemRectMin(); + auto itemButtonMax = ImGui::GetItemRectMax(); + auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + + if (type == LAYER || type == NULL_) + { if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) { rowDragReferences = row_drag_references_get(row); @@ -93,537 +263,346 @@ namespace anm2ed::imgui if (ImGui::BeginDragDropTarget()) { - if (auto payload = ImGui::AcceptDragDropPayload( - "Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + if (auto payload = ImGui::AcceptDragDropPayload("Timeline Row Drag Drop", + ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { - auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f; - auto dropZone = DropZone::BEFORE; - if (mousePos.y >= groupButtonMax.y - groupDropThird) - dropZone = DropZone::AFTER; - else if (mousePos.y >= groupButtonMin.y + groupDropThird) - dropZone = DropZone::INSIDE; - auto isDropAfter = dropZone != DropZone::BEFORE; + auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); + drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); + auto payloadRows = (TimelineRowReference*)payload->Data; auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); std::vector draggedRows(payloadRows, payloadRows + payloadCount); - auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_); - for (auto draggedRow : draggedRows) - if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false; - - if (isDropIntoGroup) - drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax); - else - drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter); - - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup); + if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, false); } ImGui::EndDragDropTarget(); } + } - ImGui::SetCursorPos(cursorPos); - auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; - ImGui::Image(resources.icons[folderIcon].id, icon_size_get()); - auto iconMin = ImGui::GetItemRectMin(); - auto iconMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[folderIcon].id, itemIconTint, false); - ImGui::SameLine(); + if (isItemButtonHovered) + { + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + item_base_properties_open(type, id); + else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && + !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) + row_selection_set(row); - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); + auto& imguiStyle = ImGui::GetStyle(); + auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; + auto previousTooltipDelay = imguiStyle.HoverDelayNormal; + imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | + ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay; + imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; + bool showItemTooltip = ImGui::BeginItemTooltip(); + imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; + imguiStyle.HoverDelayNormal = previousTooltipDelay; - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) + if (showItemTooltip) { - auto targetAnimationIndex = reference.animationIndex; - auto targetType = type; - auto targetGroupId = group->id; - auto targetVisible = !isGroupVisible; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto animation = command_animation_get(document, targetAnimationIndex); - auto container = - animation ? child_first_get(*animation, container_type_get(targetType)) - : nullptr; - if (!container) return; - auto group = child_id_get(*container, ElementType::GROUP, targetGroupId); - if (!group) return; - group->isVisible = targetVisible; - }); - } - auto visibleButtonMin = ImGui::GetItemRectMin(); - auto visibleButtonMax = ImGui::GetItemRectMax(); - overlay_icon(resources.icons[visibleIcon].id, itemIconTint, false); - ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); + auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); }; + auto visibleLabel = yesNoLabel(isVisible); + auto framesCount = item ? track_frames_count_get(*item) : 0; + + switch (type) + { + case ROOT: + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(localize.get(BASIC_ROOT)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + auto transformLabel = yesNoLabel(settings.previewIsRootTransform); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case LAYER: + { + auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, id); + if (!layer) break; + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(layer->name.c_str()); + ImGui::PopFont(); + + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)) + .c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case NULL_: + { + auto nullInfo = anm2.element_get(ElementType::NULL_ELEMENT, id); + if (!nullInfo) break; + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(nullInfo->name.c_str()); + ImGui::PopFont(); + + auto rectLabel = yesNoLabel(nullInfo->isShowRect); + ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + case TRIGGER: + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); + ImGui::PopFont(); + + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str()); + break; + } + default: + break; + } - auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax); - auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax); - if (isGroupTooltipDelayed && !isVisibleButtonHovered) - { - ImGui::BeginTooltip(); - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); - auto groupItemsCount = group_items_count_get(type, group->id); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str()); ImGui::EndTooltip(); } - if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - toggle_group(); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) - group_properties_open(row, *group); - else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered && - ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); } - ImGui::EndChild(); - ImGui::PopStyleVar(2); + + auto contentCursorPos = cursorPos; + contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); + ImGui::SetCursorPos(contentCursorPos); + + ImGui::Image(resources.icons[icon].id, icon_size_get()); + overlay_icon(resources.icons[icon].id, iconTintCurrent, false); + ImGui::SameLine(); + if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); + ImGui::TextUnformatted(label.c_str()); ImGui::PopStyleColor(); - ImGui::PopID(); - return; - } + if (isReferenced) ImGui::PopFont(); - auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); - if (type != NONE && !item) - { - ImGui::PopID(); - return; - } - auto isItemVisible = item ? item->isVisible : false; - auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; - if (item && type == ROOT && row.rootGroupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); - auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; - auto isReferenced = is_same_item(reference, row_reference_make()); - auto isItemSelected = is_row_selected(row); + 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); - auto label = [&]() -> std::string - { - if (type == LAYER) + ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; + if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) { - auto layer = layer_get(id); - if (!layer) return localize.get(TYPE_STRINGS[type]); - return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(id, layer->name, layer->spritesheetId)); + auto animationIndex = reference.animationIndex; + auto targetType = type; + auto targetID = id; + auto targetGroupType = row.rootGroupType; + auto targetGroupId = row.rootGroupId; + edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto item = command_item_get(document, animationIndex, targetType, targetID, + targetGroupType, targetGroupId); + if (!item) return; + item->isVisible = !item->isVisible; + }); } + overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) + : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); + if (type == NULL_) { - auto null = null_get(id); - if (!null) return localize.get(TYPE_STRINGS[type]); - return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); + if (auto null = anm2.element_get(ElementType::NULL_ELEMENT, id)) + { + auto& isShowRect = null->isShowRect; + auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; + ImGui::SetCursorPos( + ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get())) + { + auto nullID = id; + edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, + [=, this](Manager&, Document& document) + { + auto nulls = document.anm2.element_get(ElementType::NULLS); + auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) : nullptr; + if (!null) return; + null->isShowRect = !null->isShowRect; + }); + } + overlay_icon(resources.icons[rectIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) + : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); + } } - return localize.get(TYPE_STRINGS[type]); - }(); - auto icon = TYPE_ICONS[type]; - auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint; - auto baseColorVec = item_color_vec(type); - auto activeColorVec = item_color_active_vec(type); - auto colorVec = baseColorVec; - if (isItemSelected && type != NONE) - { - if (isLightTheme) - colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)]; - else - colorVec = activeColorVec; + + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); } - auto color = to_imvec4(colorVec); - color = !isVisible ? to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER) : color; - ImGui::PushStyleColor(ImGuiCol_ChildBg, color); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight); - - if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse)) + else { auto cursorPos = ImGui::GetCursorPos(); - auto itemChildMin = ImGui::GetWindowPos(); - auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); + ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (type != NONE) - { - ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing))); - ImGui::SetNextItemAllowOverlap(); - ImGui::SetNextItemStorageID(id); - ImGui::InvisibleButton("##Item Button", itemSize); - auto itemButtonMin = ImGui::GetItemRectMin(); - auto itemButtonMax = ImGui::GetItemRectMax(); - auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + auto& isShowUnused = settings.timelineIsShowUnused; + auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; + if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get())) + isShowUnused = !isShowUnused; + overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) + : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); - if (type == LAYER || type == NULL_) - { - if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) - { - rowDragReferences = row_drag_references_get(row); - ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(), - (int)rowDragReferences.size() * (int)sizeof(TimelineRowReference)); - ImGui::EndDragDropSource(); - } + auto& showLayersOnly = settings.timelineIsOnlyShowLayers; + auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS; + ImGui::SetCursorPos( + ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, + (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); + if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get())) + showLayersOnly = !showLayersOnly; + overlay_icon(resources.icons[layersIcon].id, iconTintCurrent, false); + ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) + : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(3); - if (ImGui::BeginDragDropTarget()) - { - if (auto payload = ImGui::AcceptDragDropPayload( - "Timeline Row Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) - { - auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax); - drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter); + ImGui::SetCursorPos(cursorPos); - auto payloadRows = (TimelineRowReference*)payload->Data; - auto payloadCount = payload->DataSize / sizeof(TimelineRowReference); - std::vector draggedRows(payloadRows, payloadRows + payloadCount); - if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, false); - } - ImGui::EndDragDropTarget(); - } - } - - if (isItemButtonHovered) - { - if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) item_base_properties_open(type, id); - else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) && - !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left)) - row_selection_set(row); - - auto& imguiStyle = ImGui::GetStyle(); - auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse; - auto previousTooltipDelay = imguiStyle.HoverDelayNormal; - imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal | - ImGuiHoveredFlags_AllowWhenDisabled | - ImGuiHoveredFlags_NoSharedDelay; - imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY; - bool showItemTooltip = ImGui::BeginItemTooltip(); - imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags; - imguiStyle.HoverDelayNormal = previousTooltipDelay; - - if (showItemTooltip) - { - auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); }; - auto visibleLabel = yesNoLabel(isVisible); - auto framesCount = item_frames_count(item); - - switch (type) - { - case ROOT: - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_ROOT)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - auto transformLabel = yesNoLabel(settings.previewIsRootTransform); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case LAYER: - { - auto layer = layer_get(id); - if (!layer) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(layer->name.c_str()); - ImGui::PopFont(); - - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId)) - .c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case NULL_: - { - auto nullInfo = null_get(id); - if (!nullInfo) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(nullInfo->name.c_str()); - ImGui::PopFont(); - - auto rectLabel = yesNoLabel(nullInfo->isShowRect); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - case TRIGGER: - { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); - ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); - ImGui::PopFont(); - - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str()); - ImGui::TextUnformatted( - std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str()); - break; - } - default: - break; - } - - ImGui::EndTooltip(); - } - } - - auto contentCursorPos = cursorPos; - contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing(); - ImGui::SetCursorPos(contentCursorPos); - - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintCurrent, false); - ImGui::SameLine(); - if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); - ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); - ImGui::TextUnformatted(label.c_str()); - ImGui::PopStyleColor(); - if (isReferenced) ImGui::PopFont(); - - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; - if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get())) - { - auto animationIndex = reference.animationIndex; - auto targetType = type; - auto targetID = id; - auto targetGroupType = row.rootGroupType; - auto targetGroupId = row.rootGroupId; - edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto item = command_item_get(document, animationIndex, targetType, targetID, - targetGroupType, targetGroupId); - if (!item) return; - item->isVisible = !item->isVisible; - }); - } - overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN) - : localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN)); - - if (type == NULL_) - { - if (auto null = null_get(id)) - { - auto& isShowRect = null->isShowRect; - auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; - ImGui::SetCursorPos( - ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get())) - { - auto nullID = id; - edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES, - [=, this](Manager&, Document& document) - { - auto nulls = document.anm2.element_get(ElementType::NULLS); - auto null = nulls ? child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID) - : nullptr; - if (!null) return; - null->isShowRect = !null->isShowRect; - }); - } - overlay_icon(resources.icons[rectIcon].id, iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN) - : localize.get(TOOLTIP_NULL_RECT_HIDDEN)); - } - } - - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - } - else - { - auto cursorPos = ImGui::GetCursorPos(); - ImGui::PushStyleColor(ImGuiCol_Button, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4()); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4()); - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f); - ImGui::SetCursorPos( - ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - - auto& isShowUnused = settings.timelineIsShowUnused; - auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; - if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get())) - isShowUnused = !isShowUnused; - overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent, false); - ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN) - : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); - - auto& showLayersOnly = settings.timelineIsOnlyShowLayers; - auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS; - ImGui::SetCursorPos( - ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, - (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get())) - showLayersOnly = !showLayersOnly; - overlay_icon(resources.icons[layersIcon].id, iconTintCurrent, false); - ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE) - : localize.get(TOOLTIP_ALL_ITEMS_VISIBLE)); - ImGui::PopStyleVar(2); - ImGui::PopStyleColor(3); - - ImGui::SetCursorPos(cursorPos); - - ImGui::BeginDisabled(); - ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - ImGui::Text("(?)"); - ImGui::PopStyleColor(); - auto tooltipShortcuts = std::vformat( - localize.get(TOOLTIP_TIMELINE_SHORTCUTS), - std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, - settings.shortcutShortenFrame, settings.shortcutExtendFrame, - settings.shortcutPreviousFrame, settings.shortcutNextFrame, - settings.shortcutPreviousItem, settings.shortcutNextItem)); - ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); - ImGui::EndDisabled(); - } + ImGui::BeginDisabled(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); + ImGui::Text("(?)"); + ImGui::PopStyleColor(); + auto tooltipShortcuts = + std::vformat(localize.get(TOOLTIP_TIMELINE_SHORTCUTS), + std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward, + settings.shortcutShortenFrame, settings.shortcutExtendFrame, + settings.shortcutPreviousFrame, settings.shortcutNextFrame, + settings.shortcutPreviousItem, settings.shortcutNextItem)); + ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str()); + ImGui::EndDisabled(); } - ImGui::EndChild(); - ImGui::PopStyleColor(); - ImGui::PopStyleVar(2); - - ImGui::PopID(); } + ImGui::EndChild(); + ImGui::PopStyleColor(); + ImGui::PopStyleVar(2); + + ImGui::PopID(); + } void TimelineContext::items_child() -{ - auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y); + { + auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + bool isItemsChildOpen = ImGui::BeginChild("##Items Child", itemsChildSize, ImGuiChildFlags_Borders); + ImGui::PopStyleVar(); + if (isItemsChildOpen) + { + auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - + ImGui::GetTextLineHeightWithSpacing() - + ImGui::GetStyle().ItemSpacing.y * 2); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - bool isItemsChildOpen = ImGui::BeginChild("##Items Child", itemsChildSize, ImGuiChildFlags_Borders); - ImGui::PopStyleVar(); - if (isItemsChildOpen) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) { - auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y - - ImGui::GetTextLineHeightWithSpacing() - - ImGui::GetStyle().ItemSpacing.y * 2); - - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar)) + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + auto rowReferences = timeline_row_references_get(); + row_selection_clear(); + for (auto rowReference : rowReferences) + row_selection_insert(rowReference); + if (!rowReferences.empty()) { - auto rowReferences = timeline_row_references_get(); - row_selection_clear(); - for (auto rowReference : rowReferences) - row_selection_insert(rowReference); - if (!rowReferences.empty()) - { - rowSelectionAnchor = rowReferences.front(); - isRowSelectionAnchorSet = true; - } - frames_selection_reset_for(document); + rowSelectionAnchor = rowReferences.front(); + isRowSelectionAnchorSet = true; + } + frames_selection_reset_for(document); + } + + if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) && + !item_references_groupable_get().empty()) + item_group(); + + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); + if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) + { + ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + ImGui::SetScrollY(scroll.y); + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Items"); + + auto item_child_row = [&](const TimelineItemRow& row, int index) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + item_child(row, index); + }; + + int index{}; + item_child_row({.type = NONE}, index++); + if (animation) + for (const auto& row : timeline_item_rows_get()) + item_child_row(row, index++); + + if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); } - if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) && - !item_references_groupable_get().empty()) - item_group(); - - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f); - if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY)) - { - ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - ImGui::SetScrollY(scroll.y); - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Items"); - - auto item_child_row = [&](const TimelineItemRow& row, int index) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - item_child(row, index); - }; - - int index{}; - item_child_row({.type = NONE}, index++); - if (animation) - for (const auto& row : timeline_item_rows_get()) - item_child_row(row, index++); - - if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - ImGui::Dummy(ImVec2(0, style.ScrollbarSize)); - } - - ImGui::EndTable(); - } - ImGui::PopStyleVar(2); - - item_context_menu(); + ImGui::EndTable(); } ImGui::PopStyleVar(2); - ImGui::EndChild(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); - auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); - - ImGui::BeginDisabled(!animation); - { - shortcut(manager.chords[SHORTCUT_ADD]); - if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); - ImGui::SameLine(); - - auto selectedRows = selected_row_references_get(); - auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) - { return row.type == LAYER || row.type == NULL_; }); - ImGui::BeginDisabled(!isRemoveAvailable); - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); - ImGui::EndDisabled(); - } - ImGui::EndDisabled(); - - ImGui::PopStyleVar(); + item_context_menu(); } + ImGui::PopStyleVar(2); ImGui::EndChild(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY())); + auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x); + + ImGui::BeginDisabled(!animation); + { + shortcut(manager.chords[SHORTCUT_ADD]); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd); + ImGui::SameLine(); + + auto selectedRows = selected_row_references_get(); + auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) + { return row.type == LAYER || row.type == NULL_; }); + ImGui::BeginDisabled(!isRemoveAvailable); + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove); + ImGui::EndDisabled(); + } + ImGui::EndDisabled(); + + ImGui::PopStyleVar(); } + ImGui::EndChild(); + } }