diff --git a/src/anm2/anm2.cpp b/src/anm2/anm2.cpp index 0835959..8505d81 100644 --- a/src/anm2/anm2.cpp +++ b/src/anm2/anm2.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -1346,6 +1347,60 @@ namespace anm2ed } } + void Anm2::region_ids_remap() + { + auto content = child_first_get(root, ElementType::CONTENT); + auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr; + if (!spritesheets) return; + + std::map> remaps{}; + for (auto& spritesheet : spritesheets->children) + { + if (spritesheet.type != ElementType::SPRITESHEET) continue; + + int nextId{}; + std::map remap{}; + for (auto& region : spritesheet.children) + { + if (region.type != ElementType::REGION) continue; + remap[region.id] = nextId; + if (region.id != nextId) + { + region.id = nextId; + } + ++nextId; + } + if (!remap.empty()) remaps[spritesheet.id] = std::move(remap); + } + + auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (remaps.empty() || !layers || !animations) return; + + for (auto& animation : animations->children) + { + if (animation.type != ElementType::ANIMATION) continue; + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, [&](Element& layerAnimation) + { + auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId); + auto remapIt = layer ? remaps.find(layer->spritesheetId) : remaps.end(); + if (remapIt == remaps.end()) return; + + for (auto& frame : layerAnimation.children) + { + if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; + auto regionIt = remapIt->second.find(frame.regionId); + if (regionIt == remapIt->second.end()) continue; + if (frame.regionId == regionIt->second) continue; + frame.regionId = regionIt->second; + } + }); + } + } + Anm2 Anm2::normalized_for_serialize() const { auto normalized = *this; @@ -1353,19 +1408,20 @@ namespace anm2ed auto content = child_first_get(normalized.root, ElementType::CONTENT); if (content) std::erase_if(content->children, [](const Element& element) { return element.tag == "Groups"; }); - auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr; - if (!layers) return normalized; - - std::unordered_map remap{}; - int nextId{}; - for (auto& layer : layers->children) + if (auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr) { - if (layer.type != ElementType::LAYER_ELEMENT) continue; - remap[layer.id] = nextId; - layer.id = nextId++; + std::unordered_map remap{}; + int nextId{}; + for (auto& layer : layers->children) + { + if (layer.type != ElementType::LAYER_ELEMENT) continue; + remap[layer.id] = nextId; + layer.id = nextId++; + } + layer_animation_ids_remap(normalized.root, remap); } - layer_animation_ids_remap(normalized.root, remap); + normalized.region_ids_remap(); return normalized; } diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index a3e6c3e..73a2fbc 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -325,6 +325,7 @@ namespace anm2ed bool is_special_interpolated_frames() const; void special_interpolated_frames_bake(int, bool, bool); void region_frames_sync(bool); + void region_ids_remap(); Anm2 normalized_for_serialize() const; Element* element_get(ElementType); diff --git a/src/canvas.cpp b/src/canvas.cpp index 8e149f3..9e6d689 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -13,6 +13,18 @@ using namespace anm2ed::util; namespace anm2ed { + void canvas_blend_premultiplied_set() + { + glEnable(GL_BLEND); + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + void canvas_blend_straight_set() + { + glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_BLEND); + } + Canvas::Canvas() = default; Canvas::Canvas(vec2 size) @@ -109,6 +121,8 @@ namespace anm2ed void Canvas::axes_render(Shader& shader, float zoom, vec2 pan, vec4 color) const { + canvas_blend_premultiplied_set(); + auto originNDC = transform_get(zoom, pan) * vec4(0.0f, 0.0f, 0.0f, 1.0f); originNDC /= originNDC.w; @@ -127,10 +141,13 @@ namespace anm2ed glBindVertexArray(0); glUseProgram(0); + canvas_blend_straight_set(); } void Canvas::grid_render(Shader& shader, float zoom, vec2 pan, ivec2 size, ivec2 offset, vec4 color) const { + canvas_blend_premultiplied_set(); + auto transform = glm::inverse(transform_get(zoom, pan)); glUseProgram(shader.id); @@ -145,11 +162,14 @@ namespace anm2ed glBindVertexArray(0); glUseProgram(0); + canvas_blend_straight_set(); } void Canvas::texture_render(Shader& shader, GLuint& texture, mat4 transform, vec4 tint, vec3 colorOffset, float* vertices) const { + canvas_blend_premultiplied_set(); + glUseProgram(shader.id); glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_TEXTURE), 0); @@ -172,12 +192,14 @@ namespace anm2ed glBindTexture(GL_TEXTURE_2D, 0); glUseProgram(0); - glEnable(GL_BLEND); + canvas_blend_straight_set(); } void Canvas::rect_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, float dashGap, float dashOffset) const { + canvas_blend_premultiplied_set(); + glUseProgram(shader.id); glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); @@ -209,10 +231,13 @@ namespace anm2ed glBindVertexArray(0); glUseProgram(0); + canvas_blend_straight_set(); } void Canvas::rect_fill_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color) const { + canvas_blend_premultiplied_set(); + glUseProgram(shader.id); glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); @@ -225,6 +250,7 @@ namespace anm2ed glBindVertexArray(0); glUseProgram(0); + canvas_blend_straight_set(); } float Canvas::zoom_level_get(float zoom, int levelDelta) const diff --git a/src/document.cpp b/src/document.cpp index 48e58a3..6350aab 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -309,7 +309,7 @@ namespace anm2ed isForceDirty(other.isForceDirty), spritesheetHashes(std::move(other.spritesheetHashes)), spritesheetSaveHashes(std::move(other.spritesheetSaveHashes)), texturePaths(std::move(other.texturePaths)), soundPaths(std::move(other.soundPaths)), isAnimationPreviewSet(other.isAnimationPreviewSet), - isSpritesheetEditorSet(other.isSpritesheetEditorSet) + isSpritesheetEditorSet(other.isSpritesheetEditorSet), editTarget(other.editTarget) { } diff --git a/src/document.hpp b/src/document.hpp index b997cc7..0fc0a76 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -44,6 +44,14 @@ namespace anm2ed CURRENT, }; + enum class EditTarget + { + NONE, + FRAME, + REGION, + SPRITESHEET + }; + std::filesystem::path path{}; uint64_t tabId{}; @@ -90,6 +98,7 @@ namespace anm2ed std::unordered_map soundPaths{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; + EditTarget editTarget{EditTarget::NONE}; Document(const std::filesystem::path&, bool = false, std::string* = nullptr); Document(const Document&) = delete; diff --git a/src/imgui/actions.hpp b/src/imgui/actions.hpp index 665d6d4..fd235ae 100644 --- a/src/imgui/actions.hpp +++ b/src/imgui/actions.hpp @@ -22,6 +22,7 @@ namespace anm2ed::imgui X(ACTION_DEFAULT, BASIC_DEFAULT, SHORTCUT_DEFAULT) \ X(ACTION_RENAME, BASIC_RENAME, SHORTCUT_RENAME) \ X(ACTION_PROPERTIES, BASIC_PROPERTIES, -1) \ + X(ACTION_REVERSE, BASIC_REVERSE, -1) \ X(ACTION_CUT, BASIC_CUT, SHORTCUT_CUT) \ X(ACTION_COPY, BASIC_COPY, SHORTCUT_COPY) \ X(ACTION_PASTE, BASIC_PASTE, SHORTCUT_PASTE) \ diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index fadbce7..fa75e7d 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -997,7 +997,7 @@ namespace anm2ed::imgui sync_checker_pan(); render_checker_background(ImGui::GetWindowDrawList(), min, max, -size - checkerPan, CHECKER_SIZE); } - ImGui::Image(texture, to_imvec2(size)); + image_premultiplied_draw(texture, to_imvec2(size)); isPreviewHovered = ImGui::IsItemHovered(); diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 1e6efd4..308512e 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -60,7 +60,9 @@ namespace anm2ed::imgui if (auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, reference.itemID)) return layer->spritesheetId; return -1; }; - if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get(); selectedLayerSpritesheet != -1) + if (auto selectedLayerSpritesheet = selected_layer_spritesheet_get(); + selectedLayerSpritesheet != -1 && document.editTarget != Document::EditTarget::REGION && + document.editTarget != Document::EditTarget::SPRITESHEET) referenceSpritesheet = selectedLayerSpritesheet; auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, referenceSpritesheet); auto texture = document.texture_get(referenceSpritesheet); @@ -257,7 +259,11 @@ namespace anm2ed::imgui frame && reference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; int highlightedRegionId = -1; - if (isReferenceLayerOnSpritesheet && frame->regionId != -1 && region_get(frame->regionId)) + if (document.editTarget == Document::EditTarget::REGION && regionReference != -1 && region_get(regionReference)) + { + highlightedRegionId = regionReference; + } + else if (isReferenceLayerOnSpritesheet && frame->regionId != -1 && region_get(frame->regionId)) { highlightedRegionId = frame->regionId; } @@ -318,7 +324,7 @@ namespace anm2ed::imgui render_checker_background(drawList, min, max, -size * 0.5f - checkerPan, CHECKER_SIZE); else drawList->AddRectFilled(min, max, ImGui::GetColorU32(to_imvec4(vec4(backgroundColor, 1.0f)))); - ImGui::Image(this->texture, to_imvec2(size)); + image_premultiplied_draw(this->texture, to_imvec2(size)); if (ImGui::IsItemHovered()) { @@ -612,8 +618,12 @@ namespace anm2ed::imgui auto region_selection_set = [&](int id) { + document.editTarget = Document::EditTarget::REGION; + regionReference = id; + regionSelection = {id}; manager.command_push({manager.selected, [=](Manager&, Document& document) { + document.editTarget = Document::EditTarget::REGION; document.region.reference = id; document.region.selection = {id}; }}); @@ -665,12 +675,13 @@ namespace anm2ed::imgui auto& toolInfo = tool::INFO[useTool]; auto& areaType = toolInfo.areaType; - auto selectedFrameToolReferences = selectedFrameReferences; + auto isRegionEditTarget = document.editTarget == Document::EditTarget::REGION; + auto selectedFrameToolReferences = isRegionEditTarget ? std::set{} : selectedFrameReferences; bool isAreaAllowed = areaType == tool::ALL || areaType == tool::SPRITESHEET_EDITOR; bool isFrameRequired = !(useTool == tool::PAN || useTool == tool::DRAW || useTool == tool::ERASE || useTool == tool::COLOR_PICKER); bool isMultiFrameToolSelection = selectedFrameToolReferences.size() > 1; - bool isRegionInUse = !isMultiFrameToolSelection && frame && frame->regionId != -1 && + bool isRegionInUse = !isRegionEditTarget && !isMultiFrameToolSelection && frame && frame->regionId != -1 && (useTool == tool::CROP || useTool == tool::MOVE); bool isFrameAvailable = !isFrameRequired || (frame && !isRegionInUse && !selectedFrameToolReferences.empty()) || (useTool == tool::CROP && !regionSelection.empty()) || @@ -709,7 +720,7 @@ namespace anm2ed::imgui if (isMouseDown || isMouseMiddleDown) pan += mouseDelta; break; case tool::MOVE: - if ((isRegionInUse || selectedFrameReferences.empty()) && regionReference != -1) + if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && regionReference != -1) { if (!spritesheet) break; auto region = region_get(regionReference); @@ -770,7 +781,7 @@ namespace anm2ed::imgui if (isEnd) document_change_push(Document::FRAMES); break; case tool::CROP: - if ((isRegionInUse || selectedFrameReferences.empty()) && !regionSelection.empty()) + if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && !regionSelection.empty()) { if (!spritesheet || regionSelection.empty()) break; if (isBegin) snapshot_push(EDIT_REGION_CROP); diff --git a/src/imgui/window/timeline.cpp b/src/imgui/window/timeline.cpp index ec9a039..5b0661c 100644 --- a/src/imgui/window/timeline.cpp +++ b/src/imgui/window/timeline.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -265,12 +266,14 @@ namespace anm2ed::imgui auto frame_selection_set_for = [&](Document& targetDocument, Reference frameReference) { group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; targetDocument.frame_references_set({frameReference}); frames_selection_sync_for(targetDocument); }; auto frame_selection_toggle_for = [&](Document& targetDocument, Reference frameReference) { group_selection_reset_for(targetDocument); + targetDocument.editTarget = Document::EditTarget::FRAME; auto selection = targetDocument.frame_references_get(Document::FrameReferenceFallback::NONE); auto itemReference = item_reference_from_frame_get(frameReference); if (selection.contains(frameReference)) @@ -295,6 +298,7 @@ namespace anm2ed::imgui 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; @@ -335,7 +339,10 @@ namespace anm2ed::imgui { 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()); @@ -570,6 +577,168 @@ namespace anm2ed::imgui { frames_delete_for(document, selectedFrames); }); }; + auto frames_duplicate = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (selectedFrames.empty()) return; + + edit_command_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, + [=, 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_get(document, itemReference.animationIndex, + itemReference.itemType, itemReference.itemID); + if (!item) continue; + + std::vector validIndices{}; + std::vector duplicatedFrames{}; + for (auto i : indices) + { + if (!vector::in_bounds(item->children, i)) continue; + validIndices.push_back(i); + duplicatedFrames.push_back(item->children[i]); + } + if (validIndices.empty()) continue; + + auto insertIndex = validIndices.back() + 1; + item->children.insert(item->children.begin() + insertIndex, + std::make_move_iterator(duplicatedFrames.begin()), + std::make_move_iterator(duplicatedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = Reference{itemReference.animationIndex, itemReference.itemType, + itemReference.itemID, insertIndex + offset}; + duplicatedSelection.insert(targetReference); + auto sourceReference = Reference{itemReference.animationIndex, itemReference.itemType, + itemReference.itemID, 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_get(document, document.reference.animationIndex, + document.reference.itemType, document.reference.itemID)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); + }; + + auto is_frames_reverse_available = [&](std::set selectedFrames) + { + std::map counts{}; + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + ++counts[itemReference]; + } + return std::ranges::any_of(counts, [](const auto& item) { return item.second >= 2; }); + }; + + auto frames_reverse = [&]() + { + auto selectedFrames = frame_references_for_current_get(); + std::erase_if(selectedFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + if (!is_frames_reverse_available(selectedFrames)) return; + + edit_command_push(EDIT_REVERSE_FRAMES, Document::FRAMES, + [=, 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_get(document, itemReference.animationIndex, + itemReference.itemType, itemReference.itemID); + if (!item || indices.size() < 2) continue; + + std::vector validIndices{}; + std::vector reversedFrames{}; + for (auto i : indices) + { + if (!vector::in_bounds(item->children, i)) continue; + validIndices.push_back(i); + reversedFrames.push_back(std::move(item->children[i])); + } + if (validIndices.size() < 2) continue; + + auto insertIndex = validIndices.front(); + for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) + item->children.erase(item->children.begin() + *it); + + std::ranges::reverse(reversedFrames); + item->children.insert(item->children.begin() + insertIndex, + std::make_move_iterator(reversedFrames.begin()), + std::make_move_iterator(reversedFrames.end())); + + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = Reference{itemReference.animationIndex, itemReference.itemType, + itemReference.itemID, insertIndex + offset}; + reversedSelection.insert(targetReference); + auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; + auto sourceReference = Reference{itemReference.animationIndex, itemReference.itemType, + itemReference.itemID, 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_get(document, document.reference.animationIndex, + document.reference.itemType, document.reference.itemID)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); + }; + auto frames_bake = [&]() { auto selectedFrames = frame_references_for_current_get(); @@ -728,7 +897,7 @@ namespace anm2ed::imgui auto isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; auto isUseRootPivot = settings.bakeIsUseRootPivot; edit_command_push(EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, - [=](Manager&, Document& document) mutable + [=, this](Manager&, Document& document) mutable { auto animation = command_animation_get(document, document.reference.animationIndex); if (!animation) return; @@ -789,25 +958,72 @@ namespace anm2ed::imgui } } + std::set selectedRootFrameIndices{}; for (auto rootReference : selectedRootFrames) { auto rootFrame = command_frame_get(document, rootReference); if (!rootFrame) continue; - rootFrame->position = {}; - rootFrame->scale = {100.0f, 100.0f}; - rootFrame->rotation = {}; - rootFrame->tint = types::color::WHITE; - rootFrame->colorOffset = {}; + 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); + defaultRootSelection.insert({document.reference.animationIndex, ROOT, -1, + rewrittenFrameIndex}); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + defaultDuration = 0; + }; + + for (const auto& frame : root->children) + { + if (frame.type != ElementType::FRAME) + { + default_root_frame_push(); + rootFrames.push_back(frame); + continue; + } + + if (selectedRootFrameIndices.contains(frameIndex)) + defaultDuration += frame.duration; + else + { + default_root_frame_push(); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + } + ++frameIndex; + } + default_root_frame_push(); + + root->children = std::move(rootFrames); + document.frame_references_set(std::move(defaultRootSelection)); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; }); }; + std::optional frameSplitTimeAtCursor; + auto frame_split = [&]() { auto selectedFrames = frame_references_for_current_get(); if (selectedFrames.size() != 1) return; auto targetReference = *selectedFrames.begin(); - auto playheadTime = (int)std::floor(playback.time); + auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); if (targetReference.itemType == TRIGGER) return; edit_command_push(EDIT_SPLIT_FRAME, Document::FRAMES, @@ -826,7 +1042,7 @@ namespace anm2ed::imgui auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); int frameStart = (int)std::round(frameStartTime); - int firstDuration = playheadTime - frameStart + 1; + int firstDuration = splitTime - frameStart + 1; if (firstDuration <= 0 || firstDuration >= originalDuration) return; @@ -1597,6 +1813,7 @@ namespace anm2ed::imgui auto selectedBakeFrames = selectedFrames; std::erase_if(selectedBakeFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + auto isReverseFrames = is_frames_reverse_available(selectedFrames); 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); @@ -1611,10 +1828,13 @@ namespace anm2ed::imgui .shortcut = SHORTCUT_INSERT_FRAME, .isEnabled = [&]() { return item; }, .run = [&]() { frame_insert(); }}); - actions.add({.label = LABEL_DELETE, - .shortcut = SHORTCUT_REMOVE, - .isEnabled = [=]() { return !selectedFrames.empty(); }, - .run = [&]() { frames_delete_action(); }}); + actions.add(ACTION_DUPLICATE, [=]() { return !selectedBakeFrames.empty(); }, [&]() { frames_duplicate(); }); + actions.add({.label = LABEL_SPLIT, + .shortcut = SHORTCUT_SPLIT, + .isEnabled = [=]() { return selectedBakeFrames.size() == 1; }, + .run = [&]() { frame_split(); }}); + actions.add(ACTION_REVERSE, [=]() { return isReverseFrames; }, [&]() { frames_reverse(); }); + actions.separator(); actions.add({.label = LABEL_BAKE, .shortcut = SHORTCUT_BAKE, .isEnabled = [=]() { return !selectedBakeFrames.empty(); }, @@ -1627,15 +1847,17 @@ namespace anm2ed::imgui .shortcut = SHORTCUT_FIT, .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, .run = [&]() { fit_animation_length(); }}); - actions.add({.label = LABEL_SPLIT, - .shortcut = SHORTCUT_SPLIT, - .isEnabled = [=]() { return selectedBakeFrames.size() == 1; }, - .run = [&]() { frame_split(); }}); + actions.separator(); actions.add({.label = LABEL_MAKE_REGION, .shortcut = -1, .isEnabled = [&]() { return isMakeRegion; }, .run = [&]() { make_region(); }}); actions.separator(); + actions.add({.label = LABEL_DELETE, + .shortcut = SHORTCUT_REMOVE, + .isEnabled = [=]() { return !selectedFrames.empty(); }, + .run = [&]() { frames_delete_action(); }}); + actions.separator(); actions.add(ACTION_CUT, [=]() { return !selectedFrames.empty(); }, cut); actions.add(ACTION_COPY, [=]() { return !selectedFrames.empty(); }, copy); actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, paste); @@ -2594,6 +2816,11 @@ namespace anm2ed::imgui auto framesSize = ImVec2(frameSize.x * length, frameSize.y); auto cursorPos = ImGui::GetCursorPos(); auto cursorScreenPos = ImGui::GetCursorScreenPos(); + if (frameSize.x > 0.0f && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + { + auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; + frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); + } auto border = glm::max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f); auto borderLineLength = frameSize.y / 5; auto frameMin = std::max(0, (int)std::floor(scroll.x / frameSize.x) - 1); diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index 55fbdb4..857134d 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -1454,6 +1454,7 @@ namespace anm2ed::imgui ImGui::SetNextItemStorageID(id); if (ImGui::Selectable("##Region Selectable", isSelected, 0, regionChildSize)) { + document.editTarget = Document::EditTarget::REGION; reference = id; document.reference = {document.reference.animationIndex}; frame.reference = -1; @@ -1511,7 +1512,6 @@ namespace anm2ed::imgui ImGui::TextUnformatted(nameCStr); ImGui::PopFont(); - ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); ImGui::TextUnformatted( std::vformat(localize.get(FORMAT_CROP), std::make_format_args(region->crop.x, region->crop.y)) .c_str()); @@ -2106,6 +2106,7 @@ namespace anm2ed::imgui ImGui::SetNextItemStorageID(id); if (ImGui::Selectable("##Spritesheet Selectable", isSelected, 0, spritesheetChildSize)) { + document.editTarget = Document::EditTarget::SPRITESHEET; reference = id; region.reference = -1; region.selection.clear(); diff --git a/src/imgui/wizard/about.cpp b/src/imgui/wizard/about.cpp index d6f61c1..f18231f 100644 --- a/src/imgui/wizard/about.cpp +++ b/src/imgui/wizard/about.cpp @@ -10,6 +10,7 @@ #include "log.hpp" #include "math.hpp" #include "strings.hpp" +#include "util/imgui/draw.hpp" using namespace anm2ed::resource; using namespace anm2ed::util; @@ -310,7 +311,7 @@ namespace anm2ed::imgui::wizard auto size = friendSizes[index]; auto min = ImVec2(centerX - size.x * 0.5f, rowMin.y + (rowHeight - size.y) * 0.5f); auto max = ImVec2(min.x + size.x, min.y + size.y); - drawList->AddImage((ImTextureID)(intptr_t)about.friendStates[index].canvas->texture, min, max); + image_premultiplied_draw(drawList, (ImTextureID)(intptr_t)about.friendStates[index].canvas->texture, min, max); }; drawList->PushClipRect(rowMin, rowMax, true); diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index 460c474..3ab3037 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -117,7 +117,7 @@ namespace anm2ed::imgui::wizard if (isTransparent) render_checker_background(ImGui::GetWindowDrawList(), previewMin, previewMax, -to_vec2(previewSize) * 0.5f, CHECKER_SIZE); - ImGui::Image(texture, previewSize); + image_premultiplied_draw(texture, previewSize); ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x); ImGui::SliderFloat("##Time", &time, 0.0f, 1.0f, ""); diff --git a/src/resource/shader.hpp b/src/resource/shader.hpp index 5509882..38c1044 100644 --- a/src/resource/shader.hpp +++ b/src/resource/shader.hpp @@ -45,7 +45,7 @@ namespace anm2ed::resource::shader uniform vec4 u_color; void main() { - o_fragColor = u_color; + o_fragColor = vec4(u_color.rgb * u_color.a, u_color.a); } )"; @@ -61,6 +61,7 @@ namespace anm2ed::resource::shader vec4 texColor = texture(u_texture, i_uv_out); texColor *= u_tint; texColor.rgb += u_color_offset; + texColor.rgb *= texColor.a; o_fragColor = texColor; } )"; @@ -108,7 +109,7 @@ namespace anm2ed::resource::shader if (alpha <= 0.0) discard; - o_fragColor = vec4(u_color.rgb, u_color.a * alpha); + o_fragColor = vec4(u_color.rgb * u_color.a * alpha, u_color.a * alpha); } )"; @@ -181,7 +182,7 @@ namespace anm2ed::resource::shader if (alpha <= 0.0) discard; - o_fragColor = vec4(u_color.rgb, u_color.a * alpha); + o_fragColor = vec4(u_color.rgb * u_color.a * alpha, u_color.a * alpha); } )"; diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 1b76c2b..27a8160 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -85,6 +85,7 @@ namespace anm2ed X(BASIC_REMOVE, "Remove", "Remover", "Удалить", "删除", "제거") \ X(BASIC_REMOVE_UNUSED, "Remove Unused", "Remover no utilizados", "Удалить неизпользуемые", "删除未使用", "미사용 시트 제거") \ X(BASIC_REPLACE, "Replace", "Reemplazar", "Заменить", "替换", "교체") \ + X(BASIC_REVERSE, "Reverse", "Invertir", "Развернуть", "反转", "역순") \ X(BASIC_ROOT, "Root", "Root", "Корень", "根", "Root") \ X(BASIC_ROTATION, "Rotation", "Rotacion", "Поворот", "旋转", "회전") \ X(BASIC_SAVE, "Save", "Guardar", "Сохранить", "保存", "저장") \ @@ -121,6 +122,7 @@ namespace anm2ed X(EDIT_DELETE_FRAMES, "Delete Frame(s)", "Eliminar Frame(s)", "Удалить кадры", "删除多个/单个帧", "프레임 삭제하기") \ X(EDIT_DRAW, "Draw", "Dibujar", "Рисовать", "画笔", "그리기") \ X(EDIT_DUPLICATE_ANIMATIONS, "Duplicate Animation(s)", "Duplicar Animacion(es)", "Дублировать кадры", "复制动画", "애니메이션 복제") \ + X(EDIT_DUPLICATE_FRAMES, "Duplicate Frame(s)", "Duplicar Frame(s)", "Дублировать кадры", "复制帧", "프레임 복제") \ X(EDIT_ERASE, "Erase", "Borrar", "Стереть", "擦除", "지우기") \ X(EDIT_EXTEND_FRAME, "Extend Frame", "Extender Frame", "Удлиннить кадр", "延长帧时长", "프레임 확장") \ X(EDIT_FIT_ANIMATION_LENGTH, "Fit Animation Length", "Encajar Largo de animacion", "Подогнать к длине анимации", "匹配动画时长", "애니메이션 길이 맞추기") \ @@ -164,6 +166,7 @@ namespace anm2ed X(EDIT_RELOAD_SPRITESHEETS, "Reload Spritesheet(s)", "Recargar Spritesheet(s)", "Перезагрузить спрайт-листы", "重新加载图集", "스프라이트 시트 다시 불러오기") \ X(EDIT_RELOAD_SOUNDS, "Reload Sound(s)", "Recargar Sonido(s)", "Перезагрузить звук(и)", "重新加载声音", "사운드 다시 불러오기") \ X(EDIT_REMOVE_ANIMATIONS, "Remove Animation(s)", "Remover Animacion(es)", "Удалить анимации", "删除动画层", "애니메이션 제거") \ + X(EDIT_REVERSE_FRAMES, "Reverse Frame(s)", "Invertir Frame(s)", "Развернуть кадры", "反转帧", "프레임 역순") \ X(EDIT_REMOVE_ITEMS, "Remove Item(s)", "Remover Item(s)", "Удалить предметы", "删除物品", "항목 제거") \ X(EDIT_REMOVE_UNUSED_EVENTS, "Remove Unused Events", "Remover Eventos No Utilizados", "Удалить неизпользуемые события", "删除未使用的事件", "미사용 이벤트 제거") \ X(EDIT_REMOVE_UNUSED_REGIONS, "Remove Unused Regions", "Remover Regiones No Utilizadas", "Удалить неиспользуемые регионы", "删除未使用的区域", "미사용 영역 제거") \ @@ -662,7 +665,7 @@ namespace anm2ed X(TOOLTIP_SETTINGS_SAVE, "Use the configured settings.", "Usa las opciones configuradas.", "Использовать настроенные настройки.", "应用更改的设置.", "구성된 설정을 사용합니다.") \ X(TOOLTIP_SET_DEFAULT_ANIMATION, "Set the selected animation as the default.", "Ajusta la animacion seleccionada como predeterminada.", "Установить выбранную анимацию как анимацию по умолчанию.", "把当前所选动画设置为默认动画.", "선택한 애니메이션을 기본 애니메이션으로 설정합니다.") \ X(TOOLTIP_SET_TO_RECOMMENDED, "Use a recommended value for rows/columns.", "Usa un valor recomendado para las filas/columnas.", "Использовать рекомендованное значение для рядов/колонн.", "应用列/行的推荐值.", "행/열에 권장값을 사용합니다.") \ - X(TOOLTIP_SPLIT, "Based on the playhead time, split the selected frame into two.", "Basado en tiempo del encabezado de reproduccion, divide el Frame seleccionado en dos.", "С учётом позиции ползунка воспроизведения разделяет выбранный кадр на два.", "根据播放头位置,将所选帧拆分成两个。", "재생 헤드 시간에 따라 선택한 프레임을 두 개로 분할합니다.") \ + X(TOOLTIP_SPLIT, "Based on the cursor position, split the selected frame into two.", "Basado en la posicion del cursor, divide el Frame seleccionado en dos.", "С учётом позиции курсора разделяет выбранный кадр на два.", "根据光标位置,将所选帧拆分成两个。", "커서 위치에 따라 선택한 프레임을 두 개로 분할합니다.") \ X(TOOLTIP_SIZE, "Change the crop size the frame uses.", "Cambia el tamaño de recorte que usa el Frame.", "Изменить размер обрезки, который использует этот кадр.", "更改此帧的裁剪大小.", "프레임에 대응되는 스프라이트 시트의 사용 영역의 크기를 변경합니다.") \ X(TOOLTIP_SOUND, "Toggle sounds playing with triggers.\nSet a trigger's sounds in Frame Properties.", "Alterna los sonidos reproducidos con triggers.\nConfigura los sonidos de un trigger en Propiedades de Frame.", "Переключить воспроизведение звуков у триггеров.\nНастраивайте звуки триггера в свойствах кадра.", "切换是否在触发器触发时播放声音.\n可在帧属性中设置触发器的声音.", "트리거와 함께 사운드를 재생할지 정합니다.\n트리거 사운드는 프레임 속성에서 설정하세요.") \ X(TEXT_SOUND_PLAY, "Click to play.", "Click para reproducir.", "Нажмите, чтобы возпроизвести.", "点击播放.", "클릭하여 재생합니다.") \ diff --git a/src/util/imgui/draw.cpp b/src/util/imgui/draw.cpp index d48f165..0b53fd2 100644 --- a/src/util/imgui/draw.cpp +++ b/src/util/imgui/draw.cpp @@ -2,6 +2,8 @@ #include +#include + namespace anm2ed::imgui { constexpr ImU32 DROP_LINE_COLOR = IM_COL32(255, 255, 0, 255); @@ -42,6 +44,27 @@ namespace anm2ed::imgui drawList->AddLine(ImVec2(min.x, y), ImVec2(max.x, y), DROP_LINE_COLOR, DROP_LINE_THICKNESS); } + void image_premultiplied_blend_set(const ImDrawList*, const ImDrawCmd*) + { + glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + void image_premultiplied_draw(ImTextureID texture, ImVec2 size) + { + auto drawList = ImGui::GetWindowDrawList(); + drawList->AddCallback(image_premultiplied_blend_set, nullptr); + ImGui::Image(texture, size); + drawList->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + } + + void image_premultiplied_draw(ImDrawList* drawList, ImTextureID texture, ImVec2 min, ImVec2 max) + { + if (!drawList) return; + drawList->AddCallback(image_premultiplied_blend_set, nullptr); + drawList->AddImage(texture, min, max); + drawList->AddCallback(ImDrawCallback_ResetRenderState, nullptr); + } + void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, glm::vec2 offset, float step) { if (!drawList || step <= 0.0f) return; diff --git a/src/util/imgui/draw.hpp b/src/util/imgui/draw.hpp index 63ffe23..b09a72b 100644 --- a/src/util/imgui/draw.hpp +++ b/src/util/imgui/draw.hpp @@ -8,5 +8,7 @@ namespace anm2ed::imgui bool is_drop_after(ImVec2, ImVec2); void drop_box_draw(ImDrawList*, ImVec2, ImVec2); void drop_line_draw(ImDrawList*, ImVec2, ImVec2, bool); + void image_premultiplied_draw(ImTextureID, ImVec2); + void image_premultiplied_draw(ImDrawList*, ImTextureID, ImVec2, ImVec2); void render_checker_background(ImDrawList*, ImVec2, ImVec2, glm::vec2, float); }