diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 437f145..44b2da0 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -184,7 +184,8 @@ namespace anm2ed::imgui } auto fps = std::max(model.info.fps, 1); - playback.tick(fps, animation->frameNum, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, + auto range = model::animation_play_range_get(*animation); + playback.tick(fps, range.x, range.y, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, deltaSeconds); frameTime = playback.time; diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index 1a45998..2bc1fac 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -101,6 +101,8 @@ namespace anm2ed::imgui {0.3765f, 0.6784f, 0.2980f, 1.0f}, {0.6353f, 0.2235f, 0.3647f, 1.0f}}; + constexpr auto MARKER_ALPHA = 0.5f; + constexpr auto MARKER_OUTSIDE_COLOR = IM_COL32(0, 0, 0, 96); constexpr auto FRAME_MULTIPLE = 5; constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f; @@ -234,6 +236,8 @@ namespace anm2ed::imgui void rows_move_to_row(std::vector draggedRows, TimelineRow targetRow, bool isDropAfter, bool isDropIntoGroup = false); void fit_animation_length(); + void marker_set(bool, int); + void markers_remove(); void frame_references_copy(const std::set& selectedFrames); void copy(); void cut(); diff --git a/src/imgui/window/timeline/edit.cpp b/src/imgui/window/timeline/edit.cpp index 079870c..5c5fb0f 100644 --- a/src/imgui/window/timeline/edit.cpp +++ b/src/imgui/window/timeline/edit.cpp @@ -293,4 +293,30 @@ namespace anm2ed::imgui std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), *errorString)); }); } + + // Sets the animation's start or end marker at a time, moving the other one if it would end up on the wrong side. + void TimelineContext::marker_set(bool isStart, int time) + { + if (!animation) return; + edit_push(isStart ? EDIT_START_MARKER : EDIT_END_MARKER, + [=, animationIndex = reference.animationIndex](model::Model& model) + { + auto animation = model.animation_edit(animationIndex); + if (!animation) return; + auto marker = std::clamp(time, 0, std::max(animation->frameNum - 1, 0)); + (isStart ? animation->startMarker : animation->endMarker) = marker; + auto& other = isStart ? animation->endMarker : animation->startMarker; + if (other != -1 && (isStart ? other < marker : other > marker)) other = marker; + }); + } + + void TimelineContext::markers_remove() + { + edit_push(EDIT_REMOVE_MARKERS, + [animationIndex = reference.animationIndex](model::Model& model) + { + if (auto animation = model.animation_edit(animationIndex)) + animation->startMarker = animation->endMarker = -1; + }); + } } diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index b22af51..0e60bff 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -226,6 +226,49 @@ namespace anm2ed::imgui if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; + // Markers show as faded playheads, with the numbers outside the range they set darkened. + if (length > 0 && animation) + { + auto x_get = [&](int time) { return cursorScreenPos.x + frameSize.x * (float)time; }; + auto range = model::animation_play_range_get(*animation); + auto bottom = cursorScreenPos.y + frameSize.y; + if (animation->startMarker != -1) + drawList->AddRectFilled(cursorScreenPos, ImVec2(x_get(range.x), bottom), MARKER_OUTSIDE_COLOR); + if (animation->endMarker != -1) + drawList->AddRectFilled(ImVec2(x_get(range.y), cursorScreenPos.y), + ImVec2(cursorScreenPos.x + framesSize.x, bottom), MARKER_OUTSIDE_COLOR); + auto markerTint = playheadIconTint; + markerTint.w *= MARKER_ALPHA; + for (auto marker : {animation->startMarker, animation->endMarker}) + if (marker != -1) + drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(icon::PLAYHEAD), + ImVec2(x_get(marker), cursorScreenPos.y), ImVec2(x_get(marker) + frameSize.x, bottom), + ImVec2(0, 0), ImVec2(1, 1), ImGui::GetColorU32(markerTint)); + } + + isRulerHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); + if (isRulerHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Right)) markerTime = hoveredTime; + Actions markerActions{}; + auto isAnimation = [&]() { return animation != nullptr; }; + markerActions.add({.label = LABEL_ADD_START_MARKER, + .shortcut = SHORTCUT_START_MARKER, + .isEnabled = isAnimation, + .run = [&]() { marker_set(true, markerTime); }}); + markerActions.add({.label = LABEL_ADD_END_MARKER, + .shortcut = SHORTCUT_END_MARKER, + .isEnabled = isAnimation, + .run = [&]() { marker_set(false, markerTime); }}); + markerActions.separator(); + markerActions.add( + {.label = LABEL_REMOVE_MARKERS, + .shortcut = -1, + .isEnabled = [&]() { return animation && (animation->startMarker != -1 || animation->endMarker != -1); }, + .run = [&]() { markers_remove(); }}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + actions_context_window_draw("##Marker Menu", markerActions, settings); + ImGui::PopStyleVar(2); + if (length > 0) { ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index 7cc0f79..7a1300d 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -153,8 +153,12 @@ namespace anm2ed::imgui 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, ImGuiPopupFlags_MouseButtonRight, - ImGuiHoveredFlags_ChildWindows); + // The numbered row has its own (marker) menu. + if (isRulerHovered) + actions_popup_draw("##Context Menu", actions, settings); + else + actions_context_window_draw("##Context Menu", actions, settings, ImGuiPopupFlags_MouseButtonRight, + ImGuiHoveredFlags_ChildWindows); ImGui::PopStyleVar(2); } diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp index 519137f..6598829 100644 --- a/src/imgui/window/timeline/timeline.cpp +++ b/src/imgui/window/timeline/timeline.cpp @@ -185,6 +185,8 @@ namespace anm2ed::imgui if (!animation) return; if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); + if (shortcut(manager.chords[SHORTCUT_START_MARKER], shortcut::GLOBAL)) marker_set(true, (int)playback.time); + if (shortcut(manager.chords[SHORTCUT_END_MARKER], shortcut::GLOBAL)) marker_set(false, (int)playback.time); if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) { diff --git a/src/imgui/window/timeline/timeline.hpp b/src/imgui/window/timeline/timeline.hpp index bd4f877..e94022a 100644 --- a/src/imgui/window/timeline/timeline.hpp +++ b/src/imgui/window/timeline/timeline.hpp @@ -112,6 +112,8 @@ namespace anm2ed::imgui struct TimelineState { bool isDragging{}; + bool isRulerHovered{}; + int markerTime{}; bool isWindowHovered{}; bool isHorizontalScroll{}; popup::ItemProperties itemProperties{}; diff --git a/src/model/model.cpp b/src/model/model.cpp index 4280737..972b189 100644 --- a/src/model/model.cpp +++ b/src/model/model.cpp @@ -368,6 +368,15 @@ namespace anm2ed::model return length; } + // The frames playback stays within: [start, end), from the markers (or the whole animation). + glm::ivec2 animation_play_range_get(const Animation& animation) + { + auto length = std::max(animation.frameNum, 1); + auto start = animation.startMarker != -1 ? std::clamp(animation.startMarker, 0, length - 1) : 0; + auto end = animation.endMarker != -1 ? std::clamp(animation.endMarker + 1, start + 1, length) : length; + return {start, end}; + } + int animation_length_get(const Animation& animation) { int length{}; diff --git a/src/model/model.hpp b/src/model/model.hpp index 497f61b..1cc3348 100644 --- a/src/model/model.hpp +++ b/src/model/model.hpp @@ -96,6 +96,9 @@ namespace anm2ed::model std::string name{}; int frameNum{1}; bool isLoop{true}; + // Playback stays between these frames (inclusive) when set; -1 for none. Saved only in the editor's copy. + int startMarker{-1}; + int endMarker{-1}; Track root{.type = ItemType::ROOT, .frames = {Frame{}}}; std::vector layers{}; std::vector nulls{}; @@ -379,6 +382,7 @@ namespace anm2ed::model int track_frames_count_get(const Track&); int track_length_get(const Track&); int animation_length_get(const Animation&); + glm::ivec2 animation_play_range_get(const Animation&); const Track* animation_track_get(const Animation&, int, int, int = NONE, int = -1); Track* animation_track_get(Animation&, int, int, int = NONE, int = -1); TrackGroup* animation_track_group_get(Animation&, int, int); diff --git a/src/model/xml.cpp b/src/model/xml.cpp index dc784d8..c49bc85 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -35,7 +35,7 @@ namespace anm2ed::model constexpr std::string_view KNOWN_ATTRIBUTES[] = { "Name", "CreatedBy", "CreatedOn", "Binding", "Value", "DefaultAnimation", "Path", "Vertex", "Fragment", "Id", "LayerId", "NullId", "SpritesheetId", "Fps", "Version", "FrameNum", "Delay", "AtFrame", "EventId", "RegionId", - "ShaderId", "SoundId", "GroupId", "Index", "Loop", "Visible", "ShowRect", "IsExpanded", "Enabled", "Rotation", + "ShaderId", "SoundId", "GroupId", "Index", "Loop", "StartMarker", "EndMarker", "Visible", "ShowRect", "IsExpanded", "Enabled", "Rotation", "XPivot", "YPivot", "XCrop", "YCrop", "XPosition", "YPosition", "Width", "Height", "XScale", "YScale", "ShearX", "ShearY", "RedTint", "GreenTint", "BlueTint", "AlphaTint", "RedOffset", "GreenOffset", "BlueOffset", "Interpolated", "Origin", "BakeInterpolation", "BakeDelay", "BakeCount", "OriginalDelay"}; @@ -423,6 +423,8 @@ namespace anm2ed::model Animation animation{.name = string_get(element, "Name"), .frameNum = int_get(element, "FrameNum", 1), .isLoop = bool_get(element, "Loop", true), + .startMarker = int_get(element, "StartMarker"), + .endMarker = int_get(element, "EndMarker"), .root = {.type = ItemType::ROOT}, .layout = {}, .extras = extras_read(element)}; @@ -1389,6 +1391,9 @@ namespace anm2ed::model sink.attribute("Name", animation.name); sink.attribute("FrameNum", animation.frameNum); sink.attribute("Loop", animation.isLoop); + if (writer.is(SERIALIZE_EXTENSIONS)) + for (auto [name, marker] : {std::pair{"StartMarker", animation.startMarker}, {"EndMarker", animation.endMarker}}) + if (marker != -1) sink.attribute(name, marker); if (groupId != -1 && is_group_id_written(writer)) sink.attribute("GroupId", groupId); extras_write(sink, animation.extras); diff --git a/src/playback.cpp b/src/playback.cpp index cff7a0e..22f16d4 100644 --- a/src/playback.cpp +++ b/src/playback.cpp @@ -18,26 +18,25 @@ namespace anm2ed void Playback::clamp(int length) { time = glm::clamp(time, 0.0f, (float)length - 1.0f); } - void Playback::tick(int fps, int length, bool isLoop, float deltaSeconds) + // Plays the frames [start, end); a playhead outside them starts at start. + void Playback::tick(int fps, int start, int end, bool isLoop, float deltaSeconds) { if (isLoop) isFinished = false; - if (isFinished || !isPlaying || fps <= 0 || length <= 0) return; + if (isFinished || !isPlaying || fps <= 0 || end <= start) return; if (deltaSeconds <= 0.0f) return; + if (!std::isfinite(time) || time < (float)start || time >= (float)end) time = (float)start; time += deltaSeconds * (float)fps; - if (!std::isfinite(time)) time = 0.0f; - if (isLoop) { - time = std::fmod(time, (float)length); - if (time < 0.0f) time += (float)length; + time = (float)start + std::fmod(time - (float)start, (float)(end - start)); return; } - if (time >= (float)length) + if (time >= (float)end) { - time = (float)length - 1.0f; + time = (float)end - 1.0f; isPlaying = false; isFinished = true; timing_reset(); diff --git a/src/playback.hpp b/src/playback.hpp index db94c5e..1239abc 100644 --- a/src/playback.hpp +++ b/src/playback.hpp @@ -12,7 +12,7 @@ namespace anm2ed void toggle(); void timing_reset(); void clamp(int); - void tick(int, int, bool, float); + void tick(int, int, int, bool, float); void decrement(int); void increment(int); diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index ea7a7e9..84ecc5c 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -118,6 +118,8 @@ namespace anm2ed X(EDIT_ADD_SOUND, "Add Sound", "Añadir Sonido", "Добавить звук", "添加声音", "사운드 추가") \ X(EDIT_ADD_SHADER, "Add Shader", "Add Shader", "Add Shader", "Add Shader", "Add Shader") \ X(EDIT_ADD_TRIGGER_SOUND, "Add Trigger Sound", "Añadir Sonido del Trigger", "Добавить звук триггера", "添加事件触发器声音", "트리거 사운드 추가") \ + X(EDIT_END_MARKER, "Set End Marker", "Poner Marcador de Fin", "Конечный маркер", "设置结束标记", "끝 마커 설정") \ + X(EDIT_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удаление маркеров", "移除标记", "마커 제거") \ X(EDIT_REMOVE_TRIGGER_SOUND, "Remove Trigger Sound", "Remover Sonido del Trigger", "Удалить звук триггера", "移除事件触发器声音", "트리거 사운드 제거") \ X(EDIT_ANIMATION_LENGTH, "Animation Length", "Duracion De Animacion", "Длина анимации", "动画时长", "애니메이션 길이") \ X(EDIT_AUTHOR, "Author", "Autor", "Автор", "制作者", "작성자") \ @@ -137,6 +139,7 @@ namespace anm2ed X(EDIT_FPS, "FPS", "FPS", "FPS", "每秒帧数(FPS)", "FPS") \ X(EDIT_GROUP_ITEMS, "Group Item(s)", "Agrupar item(s)", "Сгруппировать элементы", "将项目分组", "항목 그룹화") \ X(EDIT_REMOVE_GROUP, "Remove Group", "Eliminar grupo", "Удалить группу", "删除组", "그룹 삭제") \ + X(EDIT_START_MARKER, "Set Start Marker", "Poner Marcador de Inicio", "Начальный маркер", "设置起始标记", "시작 마커 설정") \ X(EDIT_TOGGLE_GROUP_EXPANDED, "Toggle Group Expanded", "Alternar grupo expandido", "Развернуть/свернуть группу", "展开/折叠组", "그룹 펼침 전환") \ X(EDIT_FRAME_COLOR_OFFSET, "Frame Color Offset", "Offset de color de Frame", "Смещение цвета кадра", "帧颜色偏移", "프레임 색상 오프셋") \ X(EDIT_FRAME_CROP, "Frame Crop", "Recorte de Frame", "Обрезка кадра", "帧裁剪", "프레임 자르기") \ @@ -248,6 +251,8 @@ namespace anm2ed X(FORMAT_TINT, "Tint: {0}, {1}, {2}, {3}", "Tint: {0}, {1}, {2}, {3}", "Оттенок: {0}, {1}, {2}, {3}", "色调: {0}, {1}, {2}, {3}", "색조: {0}, {1}, {2}, {3}") \ X(FORMAT_TOOLTIP_SHORTCUT, "{0}\n(Shortcut: {1})", "{0}\n(Shortcut: {1})", "{0}\n(Сочетание клавиш: {1})", "{0}\n(快捷键: {1})", "{0}\n(단축키: {1})") \ X(FORMAT_VISIBLE, "Visible: {0}", "Visible: {0}", "Видимо: {0}", "可见: {0}", "표시: {0}") \ + X(LABEL_ADD_END_MARKER, "Add End Marker Here", "Añadir Marcador de Fin Aquí", "Поставить конечный маркер здесь", "在此添加结束标记", "여기에 끝 마커 추가") \ + X(LABEL_ADD_START_MARKER, "Add Start Marker Here", "Añadir Marcador de Inicio Aquí", "Поставить начальный маркер здесь", "在此添加起始标记", "여기에 시작 마커 추가") \ X(LABEL_ADJUST, "Adjust", "Ajustar", "Отрегулировать", "调节", "조정") \ X(LABEL_ALT_ICONS, "Alt Icons", "Iconos Alternos", "Альт-иконки", "替代图标", "대체 아이콘") \ X(LABEL_ANIMATIONS_CHILD, "Animations", "Animaciones", "", "动画", "애니메이션") \ @@ -255,6 +260,7 @@ namespace anm2ed X(LABEL_AUTO_SPRITESHEET_RELOAD, "Auto Spritesheet Reload", "Recarga Automática de Spritesheets", "Автоперезагрузка спрайт-листов", "自动重新加载图集", "스프라이트 시트 자동 새로고침") \ X(LABEL_ONLY_SELECTED_ITEM, "Only Selected Item", "Solo el Elemento Seleccionado", "Только выбранный элемент", "仅选中项目", "선택한 항목만") \ X(LABEL_PIVOT_PATH, "Pivot Path", "Trayectoria del Pivote", "Путь опорной точки", "枢轴路径", "피벗 경로") \ + X(LABEL_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удалить маркеры", "移除标记", "마커 제거") \ X(LABEL_SPRITESHEETS_PACK_POPUP, "Pack Spritesheet", "Empaquetar spritesheet", "Упаковать спрайт-лист", "打包图集", "스프라이트 시트 패킹") \ X(LABEL_SPRITESHEETS_MERGE_POPUP, "Merge Spritesheets", "Combinar Spritesheets", "Объединить спрайт-листы", "合并图集", "스프라이트 시트 병합") \ X(LABEL_PACK_PADDING, "Padding", "Relleno", "Отступ", "填充", "패딩") \ @@ -474,6 +480,7 @@ namespace anm2ed X(SHORTCUT_STRING_DEFAULT, "Default", "Predeterminado", "По умолчанию", "默认", "기본값") \ X(SHORTCUT_STRING_DRAW, "Draw", "Dibujar", "Рисовать", "绘画", "그리기") \ X(SHORTCUT_STRING_DUPLICATE, "Duplicate", "Duplicar", "Дублировать", "拷贝", "복제") \ + X(SHORTCUT_STRING_END_MARKER, "End Marker", "Marcador de Fin", "Конечный маркер", "结束标记", "끝 마커") \ X(SHORTCUT_STRING_ERASE, "Erase", "Borrar", "Стереть", "擦除", "지우기") \ X(SHORTCUT_STRING_EXIT, "Exit", "Salir", "Выйти", "退出", "종료") \ X(SHORTCUT_STRING_EXTEND_FRAME, "Extend Frame", "Extender Frame", "Удлиннить кадр", "延长帧", "프레임 확장") \ @@ -507,6 +514,7 @@ namespace anm2ed X(SHORTCUT_STRING_SPLIT, "Split", "Dividir", "", "", "") \ X(SHORTCUT_STRING_BAKE, "Bake", "Bake", "Запечь", "提前渲染", "베이크") \ X(SHORTCUT_STRING_SHORTEN_FRAME, "Shorten Frame", "Acortar Frame", "Укоротить кадр", "缩短帧时长", "프레임 단축") \ + X(SHORTCUT_STRING_START_MARKER, "Start Marker", "Marcador de Inicio", "Начальный маркер", "起始标记", "시작 마커") \ X(SHORTCUT_STRING_UNDO, "Undo", "Deshacer", "Отменить", "撤销", "실행 취소") \ X(SHORTCUT_STRING_ZOOM_IN, "Zoom In", "Zoom In", "Увеличить", "视图放大", "확대") \ X(SHORTCUT_STRING_ZOOM_OUT, "Zoom Out", "Zoom Out", "Уменьшить", "视图缩小", "축소") \ diff --git a/src/settings.hpp b/src/settings.hpp index 5fb7662..c76736d 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -267,6 +267,8 @@ namespace anm2ed X(SHORTCUT_PREVIOUS_FRAME, shortcutPreviousFrame, SHORTCUT_STRING_PREVIOUS_FRAME, STRING, "F7") \ X(SHORTCUT_NEXT_FRAME, shortcutNextFrame, SHORTCUT_STRING_NEXT_FRAME, STRING, "F8") \ /* Item */ \ + X(SHORTCUT_START_MARKER, shortcutStartMarker, SHORTCUT_STRING_START_MARKER, STRING, "Shift+Comma") \ + X(SHORTCUT_END_MARKER, shortcutEndMarker, SHORTCUT_STRING_END_MARKER, STRING, "Shift+Period") \ X(SHORTCUT_PREVIOUS_ITEM, shortcutPreviousItem, SHORTCUT_STRING_PREVIOUS_ITEM, STRING, "Shift+F7") \ X(SHORTCUT_NEXT_ITEM, shortcutNextItem, SHORTCUT_STRING_NEXT_ITEM, STRING, "Shift+F8") \ /* Animation */ \ diff --git a/tests/operations.cpp b/tests/operations.cpp index f594fb3..2a48407 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -1,6 +1,7 @@ #include "common.hpp" #include "model/frames.hpp" +#include "playback.hpp" #include "util/pack.hpp" using namespace anm2ed; @@ -289,3 +290,27 @@ TEST_CASE("spritesheet pixel edits") operation_check("spritesheets_merge", model); } } + +TEST_CASE("markers stay in the editor's copy and bound playback") +{ + auto model = fixture_load("01_minimal.anm2"); + auto animation = model.animation_edit(0); + REQUIRE(animation); + animation->frameNum = 10; + animation->startMarker = 2; + animation->endMarker = 5; + CHECK(model::animation_play_range_get(*animation) == glm::ivec2(2, 6)); + + auto text = model::model_to_string(model); + CHECK(game_document_get(text).find("Marker") == std::string::npos); + auto reloaded = model_load(text); + CHECK(reloaded.animation_get(0)->startMarker == 2); + CHECK(reloaded.animation_get(0)->endMarker == 5); + + Playback playback{}; + playback.isPlaying = true; + playback.tick(10, 2, 6, true, 0.1f); + CHECK(playback.time == doctest::Approx(3.0f)); + playback.tick(10, 2, 6, true, 0.5f); + CHECK(playback.time == doctest::Approx(4.0f)); +}