From 4c569cb1e598f43548880fec165f4995b2bec0b7 Mon Sep 17 00:00:00 2001 From: shweet Date: Sat, 3 Oct 2026 18:35:22 -0400 Subject: [PATCH] Stage 10a: delete dead code, merge tiny files, unify duplicated concepts - Dead code: util/map, util/unordered_map, unused vector/math/string/input helpers, Document getters, special-interpolation bake leftovers, triggers_sort, SnapshotStack::max_size_get, AudioStream capture API. - Merges: util/xml, util/string, resource/strings.cpp inlined; constants into input.hpp; tooltip into layout; Recorder into render; onionskin, tools, welcome and frame properties are panel functions; timeline popups.cpp folded into timeline.cpp. - util/origin.hpp replaced by model Origin (the merge setting stays a combo index, so saved preferences keep their meaning). - Item type names/icons/colors moved from model/common.hpp to the timeline header; the model no longer includes icon/strings headers. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 4 +- src/document.cpp | 17 +- src/document.hpp | 8 +- src/edit/edit.hpp | 1 - src/edit/frames.cpp | 6 - src/imgui/actions.cpp | 14 +- src/imgui/dockspace.cpp | 8 +- src/imgui/dockspace.hpp | 10 +- src/imgui/window/animation_preview.cpp | 33 ++-- src/imgui/window/animation_preview.hpp | 4 +- src/imgui/window/canvas_view.cpp | 2 - src/imgui/window/frame_properties.cpp | 5 +- src/imgui/window/frame_properties.hpp | 18 -- src/imgui/window/onionskin.cpp | 6 +- src/imgui/window/onionskin.hpp | 12 -- src/imgui/window/panel.hpp | 14 ++ src/imgui/window/recorder.cpp | 203 ---------------------- src/imgui/window/recorder.hpp | 52 ------ src/imgui/window/spritesheet_editor.cpp | 1 - src/imgui/window/spritesheets.cpp | 6 +- src/imgui/window/timeline/context.hpp | 1 - src/imgui/window/timeline/popups.cpp | 213 ----------------------- src/imgui/window/timeline/timeline.cpp | 209 +++++++++++++++++++++++ src/imgui/window/timeline/timeline.hpp | 54 ++++++ src/imgui/window/tools.cpp | 8 +- src/imgui/window/tools.hpp | 21 --- src/imgui/window/welcome.cpp | 6 +- src/imgui/window/welcome.hpp | 13 -- src/model/common.hpp | 55 ------ src/model/frames.cpp | 18 -- src/model/frames.hpp | 1 - src/model/xml.cpp | 22 +-- src/model/xml.hpp | 1 - src/render.cpp | 214 ++++++++++++++++++++++-- src/render.hpp | 48 ++++++ src/resource/audio_stream.cpp | 31 ---- src/resource/audio_stream.hpp | 4 - src/resource/strings.cpp | 3 - src/resource/strings.hpp | 2 +- src/settings.hpp | 3 +- src/snapshots.cpp | 1 - src/snapshots.hpp | 1 - src/util/imgui/constants.hpp | 9 - src/util/imgui/input.cpp | 40 ----- src/util/imgui/input.hpp | 9 +- src/util/imgui/layout.cpp | 7 + src/util/imgui/layout.hpp | 3 + src/util/imgui/tooltip.cpp | 16 -- src/util/imgui/tooltip.hpp | 8 - src/util/map.hpp | 24 --- src/util/math.cpp | 2 - src/util/math.hpp | 2 - src/util/origin.hpp | 11 -- src/util/string.cpp | 25 --- src/util/string.hpp | 11 -- src/util/unordered_map.hpp | 11 -- src/util/vector.hpp | 65 ------- src/util/xml.cpp | 13 -- src/util/xml.hpp | 10 -- tests/common.hpp | 7 +- 60 files changed, 605 insertions(+), 1021 deletions(-) delete mode 100644 src/imgui/window/frame_properties.hpp delete mode 100644 src/imgui/window/onionskin.hpp delete mode 100644 src/imgui/window/recorder.cpp delete mode 100644 src/imgui/window/recorder.hpp delete mode 100644 src/imgui/window/timeline/popups.cpp delete mode 100644 src/imgui/window/tools.hpp delete mode 100644 src/imgui/window/welcome.hpp delete mode 100644 src/resource/strings.cpp delete mode 100644 src/util/imgui/constants.hpp delete mode 100644 src/util/imgui/tooltip.cpp delete mode 100644 src/util/imgui/tooltip.hpp delete mode 100644 src/util/map.hpp delete mode 100644 src/util/origin.hpp delete mode 100644 src/util/string.cpp delete mode 100644 src/util/string.hpp delete mode 100644 src/util/unordered_map.hpp delete mode 100644 src/util/xml.cpp delete mode 100644 src/util/xml.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 523c5b3..f78dc0f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -107,8 +107,8 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS set(CORE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src) file(GLOB CORE_SRC CONFIGURE_DEPENDS ${CORE_DIR}/edit/*.cpp ${CORE_DIR}/model/*.cpp) -foreach(CORE_FILE log resource/strings resource/image resource/audio_data resource/asset_store util/file util/path util/math util/string util/time util/working_directory - util/xml util/pack util/imgui/multiselect snapshots playback selection) +foreach(CORE_FILE log resource/image resource/audio_data resource/asset_store util/file util/path util/math util/time util/working_directory + util/pack util/imgui/multiselect snapshots playback selection) list(APPEND CORE_SRC ${CORE_DIR}/${CORE_FILE}.cpp) endforeach() list(REMOVE_ITEM PROJECT_SRC ${CORE_SRC}) diff --git a/src/document.cpp b/src/document.cpp index 46ef9b5..932b36d 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -492,7 +492,7 @@ namespace anm2ed } bool Document::spritesheets_merge(const std::set& ids, bool isAppendRight, bool isMakeRegions, - bool isMakePrimaryRegion, origin::Type regionOrigin) + bool isMakePrimaryRegion, Origin origin) { if (ids.size() < 2) return false; for (auto id : ids) @@ -501,7 +501,6 @@ namespace anm2ed auto baseId = *ids.begin(); auto base = model::item_get(model.content.spritesheets, baseId); - auto origin = regionOrigin == origin::ORIGIN_CENTER ? Origin::CENTER : Origin::TOP_LEFT; auto mergedTexture = *texture_get(baseId); std::unordered_map> regionIdMap{}; @@ -581,13 +580,6 @@ namespace anm2ed isForceDirty = false; } - void Document::spritesheet_hashes_reset() - { - spritesheetHashes.clear(); - spritesheetSaveHashes.clear(); - spritesheet_hashes_sync(); - } - void Document::spritesheet_hashes_sync() { std::set validIds{}; @@ -920,13 +912,6 @@ namespace anm2ed return result; } - const model::Frame* Document::frame_get() const { return model.frame_get(reference_get()); } - const model::Track* Document::item_get() const { return model.track_get(reference_get()); } - const model::Spritesheet* Document::spritesheet_get() const - { - return model::item_get(model.content.spritesheets, focused_id_get(SelectionKind::SPRITESHEETS)); - } - void Document::spritesheets_add(const std::vector& paths) { auto& items = model.content.spritesheets; diff --git a/src/document.hpp b/src/document.hpp index 3970a02..17b0e75 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -17,7 +17,6 @@ #include -#include "origin.hpp" #include "shader.hpp" #include "types.hpp" @@ -112,7 +111,7 @@ namespace anm2ed resource::Shader* shader_get(int); bool regions_trim(int, const std::set&); bool spritesheet_pack(int, int); - bool spritesheets_merge(const std::set&, bool, bool, bool, origin::Type); + bool spritesheets_merge(const std::set&, bool, bool, bool, Origin); void hash_set(); void clean(); void change(); @@ -145,7 +144,6 @@ namespace anm2ed void spritesheet_hash_set_saved(int); bool spritesheet_is_dirty(int); bool spritesheet_any_dirty(); - void spritesheet_hashes_reset(); void spritesheet_hashes_sync(); Reference reference_get() const; void reference_set(Reference); @@ -173,10 +171,6 @@ namespace anm2ed void frame_references_clear(); std::vector layer_references_get(); - const model::Frame* frame_get() const; - const model::Track* item_get() const; - const model::Spritesheet* spritesheet_get() const; - void spritesheets_add(const std::vector&); void sounds_add(const std::vector&); diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp index 6dd5b63..fa8d01e 100644 --- a/src/edit/edit.hpp +++ b/src/edit/edit.hpp @@ -70,7 +70,6 @@ namespace anm2ed::edit Uids frames_move(model::Model&, const std::set&, Reference, int); Uids frame_durations_set(model::Model&, const std::map&); Uids trigger_at_frame_set(model::Model&, Reference, int); - Uids triggers_sort(model::Model&, Reference); Uids frames_paste(model::Model&, Reference, const std::set&, const std::string&, int, std::string*); Uids root_bake_into(model::Model&, const std::set&, const std::set&, RootBakeOptions); diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 94223aa..db34a0f 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -216,12 +216,6 @@ namespace anm2ed::edit return {}; } - Uids triggers_sort(Model& model, Reference reference) - { - if (auto track = model.track_edit(reference)) frames_sort_by_at_frame(*track); - return {}; - } - // Pastes clipboard frames after the track's selected frames (or its current frame); triggers go at `time`, stepping // past occupied frames. Frames lose regions that do not exist on the target layer. Uids frames_paste(Model& model, Reference reference, const std::set& selection, const std::string& text, diff --git a/src/imgui/actions.cpp b/src/imgui/actions.cpp index d4d997d..bb06736 100644 --- a/src/imgui/actions.cpp +++ b/src/imgui/actions.cpp @@ -2,8 +2,8 @@ #include +#include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" namespace anm2ed::imgui { @@ -47,12 +47,12 @@ namespace anm2ed::imgui void actions_undo_redo_add(Actions& actions, Manager& manager, Document& document) { - actions.add(ACTION_UNDO, [&document]() { return document.is_able_to_undo(); }, - [&manager]() - { manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); }); - actions.add(ACTION_REDO, [&document]() { return document.is_able_to_redo(); }, - [&manager]() - { manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); }); + actions.add( + ACTION_UNDO, [&document]() { return document.is_able_to_undo(); }, [&manager]() + { manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); }); + actions.add( + ACTION_REDO, [&document]() { return document.is_able_to_redo(); }, [&manager]() + { manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); }); } void actions_menu_draw(Actions& actions, Settings& settings) diff --git a/src/imgui/dockspace.cpp b/src/imgui/dockspace.cpp index 2ac4bf4..25bc0f0 100644 --- a/src/imgui/dockspace.cpp +++ b/src/imgui/dockspace.cpp @@ -51,10 +51,10 @@ namespace anm2ed::imgui regions_update(panel, regions); } if (settings.windowIsEvents) panel_update(events, events_update); - if (settings.windowIsFrameProperties) frameProperties.update(manager, settings); + if (settings.windowIsFrameProperties) frame_properties_update(manager, settings, frameProperties); if (settings.windowIsLayers) panel_update(layers, layers_update); if (settings.windowIsNulls) panel_update(nulls, nulls_update); - if (settings.windowIsOnionskin) onionskin.update(manager, settings); + if (settings.windowIsOnionskin) onionskin_update(manager, settings); if (settings.windowIsShaders) { auto panel = panel_make(shaders.state); @@ -68,13 +68,13 @@ namespace anm2ed::imgui spritesheets_update(panel, spritesheets); } if (settings.windowIsTimeline) timeline.update(manager, settings, resources, clipboard); - if (settings.windowIsTools) tools.update(manager, settings, resources); + if (settings.windowIsTools) tools_update(manager, settings, resources, toolsColorEditPopup); isCanvasFocused = (settings.windowIsAnimationPreview && animationPreview.is_focused_get()) || (settings.windowIsSpritesheetEditor && spritesheetEditor.is_focused_get()); } } else - welcome.update(manager, resources, dialog, taskbar, documents); + welcome_update(manager, resources, dialog, taskbar, documents); autosaveRestore.update(manager); } diff --git a/src/imgui/dockspace.hpp b/src/imgui/dockspace.hpp index 4069451..f871e1e 100644 --- a/src/imgui/dockspace.hpp +++ b/src/imgui/dockspace.hpp @@ -4,14 +4,10 @@ #include "popup/autosave_restore.hpp" #include "taskbar.hpp" #include "window/animation_preview.hpp" -#include "window/frame_properties.hpp" -#include "window/onionskin.hpp" #include "window/panel.hpp" #include "window/shaders.hpp" #include "window/spritesheet_editor.hpp" #include "window/timeline/timeline.hpp" -#include "window/tools.hpp" -#include "window/welcome.hpp" namespace anm2ed::imgui { @@ -22,17 +18,15 @@ namespace anm2ed::imgui AnimationsPanel animations{}; RegionsPanel regions{}; PanelState events{}; - FrameProperties frameProperties; + FramePropertiesPanel frameProperties{}; PanelState layers{}; PanelState nulls{}; - Onionskin onionskin; ShadersPanel shaders{}; SpritesheetEditor spritesheetEditor; SpritesheetsPanel spritesheets{}; PanelState sounds{}; Timeline timeline; - Tools tools; - Welcome welcome; + PopupHelper toolsColorEditPopup{PopupHelper(LABEL_TOOLS_COLOR_EDIT_POPUP, POPUP_TO_CONTENT, POPUP_BY_ITEM)}; AutosaveRestore autosaveRestore; public: diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 7db1c60..e984c40 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -28,7 +28,7 @@ #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" +#include "window/timeline/timeline.hpp" using namespace anm2ed::types; using namespace anm2ed::util; @@ -38,7 +38,7 @@ using namespace glm; namespace anm2ed::imgui { - constexpr auto NULL_COLOR = vec4(0.0f, 0.0f, 1.0f, 0.90f); + constexpr auto NULL_RECT_COLOR = vec4(0.0f, 0.0f, 1.0f, 0.90f); constexpr auto SELECTED_LAYER_BORDER_COLOR = vec4(1.0f, 0.1059f, 0.5882f, 1.0f); constexpr auto TARGET_SIZE = vec2(32, 32); constexpr auto POINT_SIZE = vec2(4, 4); @@ -209,19 +209,20 @@ namespace anm2ed::imgui const model::Animation* animation) { auto animationFps = std::max(document.model.info.fps, 1); - RecorderOptions options{.type = (render::Type)settings.renderType, - .path = settings.renderPath, - .format = settings.renderFormat, - .ffmpegPath = settings.renderFFmpegPath, - .start = manager.recordingStart, - .end = manager.recordingEnd, - .animationFps = animationFps, - .fps = render::fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), - .rows = settings.renderRows, - .columns = settings.renderColumns, - .isSound = settings.timelineIsSound, - .isIsolated = settings.renderIsUseIsolatedAnimation, - .isBounded = settings.renderIsUseAnimationBounds}; + render::RecorderOptions options{ + .type = (render::Type)settings.renderType, + .path = settings.renderPath, + .format = settings.renderFormat, + .ffmpegPath = settings.renderFFmpegPath, + .start = manager.recordingStart, + .end = manager.recordingEnd, + .animationFps = animationFps, + .fps = render::fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), + .rows = settings.renderRows, + .columns = settings.renderColumns, + .isSound = settings.timelineIsSound, + .isIsolated = settings.renderIsUseIsolatedAnimation, + .isBounded = settings.renderIsUseAnimationBounds}; if (options.isBounded) { recordSize = size; @@ -573,7 +574,7 @@ namespace anm2ed::imgui { auto isShowRect = model::item_get(sampleModel.content.nulls, draw.id)->isShowRect; auto isSelected = isActiveDocument && draw.id == reference.itemID && referenceItemType == ItemType::NULL_; - auto color = isOnion ? onionColor : isSelected ? color::RED : NULL_COLOR; + auto color = isOnion ? onionColor : isSelected ? color::RED : NULL_RECT_COLOR; auto markerSize = isShowRect ? POINT_SIZE : TARGET_SIZE; texture_render(shaderTexture, isShowRect ? resources.icon_id_get(icon::POINT) : targetIcon, transform * marker_model_get(markerSize), color); diff --git a/src/imgui/window/animation_preview.hpp b/src/imgui/window/animation_preview.hpp index 6431066..22961ac 100644 --- a/src/imgui/window/animation_preview.hpp +++ b/src/imgui/window/animation_preview.hpp @@ -6,7 +6,7 @@ #include "audio_stream.hpp" #include "canvas_view.hpp" #include "manager.hpp" -#include "recorder.hpp" +#include "render.hpp" #include "resources.hpp" #include "settings.hpp" @@ -21,7 +21,7 @@ namespace anm2ed::imgui bool isMoveDragging{}; glm::vec2 moveOffset{}; glm::vec2 nullRectScaleAnchor{}; - Recorder recorder{}; + render::Recorder recorder{}; glm::vec2 recordSize{}; glm::vec2 recordPan{}; float recordZoom{}; diff --git a/src/imgui/window/canvas_view.cpp b/src/imgui/window/canvas_view.cpp index 9132278..f97fe29 100644 --- a/src/imgui/window/canvas_view.cpp +++ b/src/imgui/window/canvas_view.cpp @@ -4,11 +4,9 @@ #include "actions.hpp" #include "edit/edit.hpp" -#include "util/imgui/constants.hpp" #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" using namespace anm2ed::types; using namespace anm2ed::util; diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index e083414..c242041 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -1,4 +1,4 @@ -#include "frame_properties.hpp" +#include "panel.hpp" #include #include @@ -45,8 +45,9 @@ namespace anm2ed::imgui constexpr FlipButton FLIP_BUTTONS[] = {{LABEL_FLIP_X, EDIT_FRAME_FLIP_X, TOOLTIP_FLIP_X}, {LABEL_FLIP_Y, EDIT_FRAME_FLIP_Y, TOOLTIP_FLIP_Y}}; - void FrameProperties::update(Manager& manager, Settings& settings) + void frame_properties_update(Manager& manager, Settings& settings, FramePropertiesPanel& panel) { + auto& [changeAllFrameProperties, isBatchMode] = panel; auto& document = *manager.get(); auto frameSelectionCount = document.frame_references_get(Document::FrameReferenceFallback::NONE).size(); if (frameSelectionCount == 0 && document.reference_get().frameIndex >= 0) frameSelectionCount = 1; diff --git a/src/imgui/window/frame_properties.hpp b/src/imgui/window/frame_properties.hpp deleted file mode 100644 index 29ae294..0000000 --- a/src/imgui/window/frame_properties.hpp +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#include - -#include "manager.hpp" -#include "wizard/change_all_frame_properties.hpp" - -namespace anm2ed::imgui -{ - class FrameProperties - { - wizard::ChangeAllFrameProperties changeAllFrameProperties{}; - bool isBatchMode{}; - - public: - void update(Manager&, Settings&); - }; -} diff --git a/src/imgui/window/onionskin.cpp b/src/imgui/window/onionskin.cpp index 9de558d..bf054b4 100644 --- a/src/imgui/window/onionskin.cpp +++ b/src/imgui/window/onionskin.cpp @@ -1,11 +1,11 @@ -#include "onionskin.hpp" +#include "panel.hpp" #include #include "strings.hpp" #include "util/imgui/input.hpp" +#include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" using namespace anm2ed::types; using namespace glm; @@ -14,7 +14,7 @@ namespace anm2ed::imgui { constexpr auto FRAMES_MAX = 100; - void Onionskin::update(Manager& manager, Settings& settings) + void onionskin_update(Manager& manager, Settings& settings) { auto& isEnabled = settings.onionskinIsEnabled; auto& beforeCount = settings.onionskinBeforeCount; diff --git a/src/imgui/window/onionskin.hpp b/src/imgui/window/onionskin.hpp deleted file mode 100644 index dd9489d..0000000 --- a/src/imgui/window/onionskin.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "manager.hpp" - -namespace anm2ed::imgui -{ - class Onionskin - { - public: - void update(Manager&, Settings&); - }; -} diff --git a/src/imgui/window/panel.hpp b/src/imgui/window/panel.hpp index b1a1fa5..b87b99c 100644 --- a/src/imgui/window/panel.hpp +++ b/src/imgui/window/panel.hpp @@ -16,6 +16,7 @@ #include "util/imgui/multiselect.hpp" #include "util/imgui/popup.hpp" #include "util/imgui/selectable.hpp" +#include "wizard/change_all_frame_properties.hpp" // Panels are plain functions: each draws from the document and its selection, and queues edits as commands. namespace anm2ed::imgui @@ -132,6 +133,15 @@ namespace anm2ed::imgui int mergeReference{-1}; }; + struct FramePropertiesPanel + { + wizard::ChangeAllFrameProperties changeAllFrameProperties{}; + bool isBatchMode{}; + }; + + class Taskbar; + class Documents; + void animations_update(Panel&, AnimationsPanel&); void layers_update(Panel&); void nulls_update(Panel&); @@ -139,6 +149,10 @@ namespace anm2ed::imgui void sounds_update(Panel&); void spritesheets_update(Panel&, SpritesheetsPanel&); void regions_update(Panel&, RegionsPanel&); + void frame_properties_update(Manager&, Settings&, FramePropertiesPanel&); + void onionskin_update(Manager&, Settings&); + void tools_update(Manager&, Settings&, Resources&, PopupHelper&); + void welcome_update(Manager&, Resources&, Dialog&, Taskbar&, Documents&); template std::vector item_ids_get(const Items& items) { diff --git a/src/imgui/window/recorder.cpp b/src/imgui/window/recorder.cpp deleted file mode 100644 index ef3da21..0000000 --- a/src/imgui/window/recorder.cpp +++ /dev/null @@ -1,203 +0,0 @@ -#include "recorder.hpp" - -#include -#include -#include - -#include "audio.hpp" -#include "log.hpp" -#include "path.hpp" -#include "toast.hpp" - -using namespace anm2ed::resource; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ - constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000; - constexpr int ALPHA_OPAQUE = 255; - constexpr float CHANNEL_MAX = 255.0f; - - std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, render::Type type) - { - auto fallback = path::from_utf8(std::format("frame_{:06}.png", index)); - if (type != render::PNGS) return fallback; - try - { - auto filename = path::from_utf8(std::vformat(path::to_utf8(format), std::make_format_args(index))).filename(); - if (filename.empty()) return fallback; - if (filename.extension().empty()) filename.replace_extension(render::EXTENSIONS[render::SPRITESHEET]); - return filename; - } - catch (...) - { - return fallback; - } - } - - // PNG sequences go straight to their folder; other outputs collect frames in a temporary folder beside the output. - std::filesystem::path frames_directory_create(const RecorderOptions& options) - { - std::error_code ec{}; - if (options.type == render::PNGS) - { - std::filesystem::create_directories(options.path, ec); - return options.path; - } - auto directory = options.path.parent_path(); - if (directory.empty()) directory = std::filesystem::current_path(); - std::filesystem::create_directories(directory, ec); - auto timestamp = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); - for (int suffix = 0; suffix < TEMP_DIRECTORY_ATTEMPTS; ++suffix) - { - auto temporary = directory / path::from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); - if (std::filesystem::create_directories(temporary, ec)) return temporary; - } - return {}; - } - - // Rendered pixels are premultiplied; outputs on a transparent background want straight alpha. - void pixels_unpremultiply(std::vector& pixels) - { - for (std::size_t index = 0; index + 3 < pixels.size(); index += image::CHANNELS) - { - auto alpha = pixels[index + 3]; - if (alpha == ALPHA_OPAQUE) continue; - for (int channel = 0; channel < 3; ++channel) - pixels[index + channel] = - alpha == 0 - ? 0 - : (uint8_t)glm::clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX); - } - } - - void sounds_detach(const Document& document, MIX_Mixer* mixer) - { - for (auto& [id, _] : document.sounds) - if (auto sound = document.sound_get(id)) audio::track_detach(*sound, mixer); - } - - // Mixes each frame's trigger sound into one stream at the render frame rate. - bool audio_stream_generate(AudioStream& audioStream, const Document& document, const std::vector& soundIds, - int fps) - { - audioStream.stream.clear(); - if (soundIds.empty() || fps <= 0) return true; - - SDL_AudioSpec mixSpec = audioStream.spec; - mixSpec.format = SDL_AUDIO_F32; - auto mixer = MIX_CreateMixer(&mixSpec); - if (!mixer) return false; - - auto channels = std::max(mixSpec.channels, 1); - auto framesPerStep = (double)std::max(mixSpec.freq, 1) / (double)fps; - auto accumulator = 0.0; - std::vector buffer{}; - auto isGenerated = true; - for (auto soundId : soundIds) - { - if (auto sound = document.sound_get(soundId)) audio::play(*sound, false, mixer); - accumulator += framesPerStep; - auto sampleFrames = std::max((int)std::floor(accumulator), 1); - accumulator -= (double)sampleFrames; - buffer.resize((std::size_t)sampleFrames * (std::size_t)channels); - if (!(isGenerated = MIX_Generate(mixer, buffer.data(), (int)(buffer.size() * sizeof(float))))) break; - audioStream.stream.insert(audioStream.stream.end(), buffer.begin(), buffer.end()); - } - sounds_detach(document, mixer); - MIX_DestroyMixer(mixer); - if (!isGenerated) audioStream.stream.clear(); - return isGenerated; - } - - bool Recorder::start(const RecorderOptions& recorderOptions) - { - options = recorderOptions; - index = 0; - count = render::frame_count_get(options.start, options.end, options.animationFps, options.fps); - frames.clear(); - soundIds.clear(); - soundTime = -1; - directory = frames_directory_create(options); - return !directory.empty(); - } - - bool Recorder::is_done() const { return index >= count; } - - float Recorder::time_get() const - { - return render::frame_time_get(options.start, index, options.animationFps, options.fps); - } - - // A trigger sound is taken once per animation frame, however many render frames it spans. - bool Recorder::is_sound_frame() const { return (int)std::floor(time_get()) != soundTime; } - - bool Recorder::frame_capture(std::vector pixels, glm::ivec2 size, int soundId) - { - soundTime = (int)std::floor(time_get()); - soundIds.push_back(soundId); - if (options.isIsolated || options.isBounded) pixels_unpremultiply(pixels); - auto framePath = directory / frame_filename_get(options.format, index, options.type); - if (!Image::write_pixels_png(framePath, size, pixels.data())) return false; - frames.push_back(framePath); - ++index; - return true; - } - - void Recorder::finish(const Document& document, AudioStream& audioStream) - { - auto pathString = path::to_utf8(options.path); - if (options.type == render::PNGS) - toast_log(frames.empty() ? Level::ERROR : Level::INFO, - frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); - else if (options.type == render::SPRITESHEET) - { - auto layout = render::spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); - auto first = frames.empty() ? Image{} : Image(frames.front()); - if (frames.empty()) - toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); - else if (!first.is_valid()) - toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); - else - { - Image sheet{}; - sheet.size = first.size * glm::ivec2(layout.columns, layout.rows); - sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * image::CHANNELS); - for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) - if (auto frame = Image(frames[i]); frame.size == first.size) - sheet.paste(frame, first.size * glm::ivec2(i % layout.columns, i / layout.columns)); - auto isSaved = sheet.write_png(options.path); - toast_log(isSaved ? Level::INFO : Level::ERROR, - isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); - } - } - else - { - audioStream.stream.clear(); - if (options.isSound && options.type != render::GIF && - !audio_stream_generate(audioStream, document, soundIds, options.fps)) - { - toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED)); - logger.error("Failed to generate deterministic render audio stream; exporting without audio."); - } - auto isRendered = - animation_render(options.ffmpegPath, options.path, frames, audioStream, options.type, options.fps); - toast_log(isRendered ? Level::INFO : Level::ERROR, - isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); - } - cancel(); - } - - // Stops; the temporary frame folder is removed (a PNG sequence's own folder is kept). - void Recorder::cancel() - { - std::error_code ec{}; - if (options.type != render::PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec); - directory.clear(); - frames.clear(); - soundIds.clear(); - index = count = 0; - } -} diff --git a/src/imgui/window/recorder.hpp b/src/imgui/window/recorder.hpp deleted file mode 100644 index 4c013fb..0000000 --- a/src/imgui/window/recorder.hpp +++ /dev/null @@ -1,52 +0,0 @@ -#pragma once - -#include -#include - -#include "audio_stream.hpp" -#include "document.hpp" -#include "render.hpp" - -namespace anm2ed::imgui -{ - struct RecorderOptions - { - render::Type type{}; - std::filesystem::path path{}; - std::filesystem::path format{}; - std::filesystem::path ffmpegPath{}; - int start{}; - int end{}; - int animationFps{1}; - int fps{1}; - int rows{}; - int columns{}; - bool isSound{}; - bool isIsolated{}; - bool isBounded{}; - }; - - // A render in progress: which animation times to capture, the frames captured so far (written to disk) and the - // trigger sound of each, and assembling the output when done. - class Recorder - { - public: - RecorderOptions options{}; - int index{}; - int count{}; - - bool start(const RecorderOptions&); - bool is_done() const; - float time_get() const; - bool is_sound_frame() const; - bool frame_capture(std::vector, glm::ivec2, int); - void finish(const Document&, AudioStream&); - void cancel(); - - private: - std::filesystem::path directory{}; - std::vector frames{}; - std::vector soundIds{}; - int soundTime{-1}; - }; -} diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index c5eee52..65771e7 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -16,7 +16,6 @@ #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" using namespace anm2ed::types; using namespace anm2ed::resource; diff --git a/src/imgui/window/spritesheets.cpp b/src/imgui/window/spritesheets.cpp index a043b8e..70b36e4 100644 --- a/src/imgui/window/spritesheets.cpp +++ b/src/imgui/window/spritesheets.cpp @@ -16,6 +16,8 @@ namespace anm2ed::imgui constexpr int SPRITESHEET_CARD_LINES = 4; constexpr int MERGE_OPTIONS_ROWS = 6; constexpr int PADDING_MAX = 100; + // The merge region origin setting indexes this (top-left or center). + constexpr Origin MERGE_REGION_ORIGINS[] = {Origin::TOP_LEFT, Origin::CENTER}; auto& spritesheets_get(model::Model& model) { return model.content.spritesheets; } @@ -122,7 +124,7 @@ namespace anm2ed::imgui if (!ImGui::BeginPopupModal(popup.label(), &popup.isOpen, ImGuiWindowFlags_NoResize)) return popup.end(); settings.mergeSpritesheetsRegionOrigin = - glm::clamp(settings.mergeSpritesheetsRegionOrigin, (int)origin::TOP_LEFT, (int)origin::ORIGIN_CENTER); + glm::clamp(settings.mergeSpritesheetsRegionOrigin, 0, (int)std::size(MERGE_REGION_ORIGINS) - 1); if (ImGui::BeginChild("##Merge Spritesheets Options", child_size_get(MERGE_OPTIONS_ROWS), ImGuiChildFlags_Borders)) { ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN)); @@ -156,7 +158,7 @@ namespace anm2ed::imgui [ids = spritesheets.mergeIds, isAppendRight = settings.mergeSpritesheetsOrigin == APPEND_RIGHT, isMakeRegions = settings.mergeSpritesheetsIsMakeRegions, isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, - regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin](Document& document) + regionOrigin = MERGE_REGION_ORIGINS[settings.mergeSpritesheetsRegionOrigin]](Document& document) { spritesheet_textures_edit( document, EDIT_MERGE_SPRITESHEETS, diff --git a/src/imgui/window/timeline/context.hpp b/src/imgui/window/timeline/context.hpp index 2ff0fec..d49be1c 100644 --- a/src/imgui/window/timeline/context.hpp +++ b/src/imgui/window/timeline/context.hpp @@ -21,7 +21,6 @@ #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" #include "model/frames.hpp" #include "vector.hpp" diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp deleted file mode 100644 index af60d27..0000000 --- a/src/imgui/window/timeline/popups.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include "context.hpp" - -namespace anm2ed::imgui -{ - void TimelineContext::draw() - { - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); - if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline)) - { - isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | - ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); - frames_child(); - if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) - { - if (frameMoveDropTarget) frames_move_to(*frameMoveDropTarget); - frameMoveDrag = {}; - } - items_child(); - } - ImGui::PopStyleVar(); - ImGui::End(); - - if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document); - group_properties_update(); - - makeManyRegionsPopup.trigger(); - if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) - { - input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); - ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); - - auto result = popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); - if (result == PopupButton::CONFIRM) - edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, - [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, - mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET - : RegionFrameMapping::PRESERVE](model::Model& model) - { return edit::regions_generate(model, {}, targetFrames, format, mapping); }); - if (result != PopupButton::NONE) makeManyRegionsPopup.close(); - - ImGui::EndPopup(); - } - makeManyRegionsPopup.end(); - - bakePopup.trigger(); - - if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize)) - { - auto& interval = settings.bakeInterval; - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; - - auto frame = frame_get(); - - input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, - frame ? frame->duration : FRAME_DURATION_MIN); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - frames_bake(); - bakePopup.close(); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - - ImGui::EndPopup(); - } - - bakeIntoOtherFramesPopup.trigger(); - - if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen, - ImGuiWindowFlags_NoResize)) - { - auto& isRoundRotation = settings.bakeIsRoundRotation; - auto& isRoundScale = settings.bakeIsRoundScale; - auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; - auto& isUseRootPivot = settings.bakeIsUseRootPivot; - int target = (int)bakeIntoOtherFramesTarget; - ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, - (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); - ImGui::SameLine(); - ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); - bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; - - auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; - ImGui::BeginDisabled(isCurrentSelection); - ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); - ImGui::SameLine(); - ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); - ImGui::EndDisabled(); - - ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); - - ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); - - ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); - - ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); - - auto widgetSize = widget_size_with_row_get(2); - - shortcut(manager.chords[SHORTCUT_CONFIRM]); - ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) - { - bake_into_other_frames(); - bakeIntoOtherFramesPopup.close(); - } - ImGui::EndDisabled(); - - ImGui::SameLine(); - - shortcut(manager.chords[SHORTCUT_CANCEL]); - if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close(); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); - - ImGui::EndPopup(); - } - - if (animation) - { - if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); - - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) - { - playback_stop(); - playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL)) - { - playback_stop(); - playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - struct FrameResize - { - 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 (!isResizeChordHeld[i]) edit_begin_push(resize.edit); - command_push( - [=, this](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - if (auto frame = document.model.frame_edit(frameReference)) - frame->duration = - std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); - document.change(); - }); - } - isResizeChordHeld[i] = isPressed; - } - - 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 || isNextFrame) - if (auto item = selected_item_get(); item && !item->frames.empty()) - { - auto frameReference = reference; - frameReference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, - (int)item->frames.size() - 1); - reference_set(frameReference); - document.frame_focus_select(); - document.frameTime = model::frame_time_from_index_get(*item, reference.frameIndex); - } - - if (isPreviousItem) reference_set_adjacent_item(-1); - if (isNextItem) reference_set_adjacent_item(1); - } - - if (isTextPushed) ImGui::PopStyleColor(); - } -} diff --git a/src/imgui/window/timeline/timeline.cpp b/src/imgui/window/timeline/timeline.cpp index 2b58de5..58a3396 100644 --- a/src/imgui/window/timeline/timeline.cpp +++ b/src/imgui/window/timeline/timeline.cpp @@ -38,4 +38,213 @@ namespace anm2ed::imgui context = std::make_unique(std::move(state), manager, settings, resources, clipboard); context->update(); } + + void TimelineContext::draw() + { + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); + if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline)) + { + isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | + ImGuiHoveredFlags_AllowWhenBlockedByActiveItem); + frames_child(); + if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + if (frameMoveDropTarget) frames_move_to(*frameMoveDropTarget); + frameMoveDrag = {}; + } + items_child(); + } + ImGui::PopStyleVar(); + ImGui::End(); + + if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document); + group_properties_update(); + + makeManyRegionsPopup.trigger(); + if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize)) + { + input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat); + ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames); + + auto result = popup_buttons_draw(manager, localize.get(LABEL_MAKE_MANY_REGIONS)); + if (result == PopupButton::CONFIRM) + edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, + [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, + mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET + : RegionFrameMapping::PRESERVE](model::Model& model) + { return edit::regions_generate(model, {}, targetFrames, format, mapping); }); + if (result != PopupButton::NONE) makeManyRegionsPopup.close(); + + ImGui::EndPopup(); + } + makeManyRegionsPopup.end(); + + bakePopup.trigger(); + + if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize)) + { + auto& interval = settings.bakeInterval; + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; + + auto frame = frame_get(); + + input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN, + frame ? frame->duration : FRAME_DURATION_MIN); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + + auto widgetSize = widget_size_with_row_get(2); + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + frames_bake(); + bakePopup.close(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS)); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + + ImGui::EndPopup(); + } + + bakeIntoOtherFramesPopup.trigger(); + + if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen, + ImGuiWindowFlags_NoResize)) + { + auto& isRoundRotation = settings.bakeIsRoundRotation; + auto& isRoundScale = settings.bakeIsRoundScale; + auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation; + auto& isUseRootPivot = settings.bakeIsUseRootPivot; + int target = (int)bakeIntoOtherFramesTarget; + ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target, + (int)BakeIntoOtherFramesTarget::CURRENT_SELECTION); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION)); + ImGui::SameLine(); + ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL)); + bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target; + + auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION; + ImGui::BeginDisabled(isCurrentSelection); + ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls); + ImGui::EndDisabled(); + + ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION)); + + ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE)); + + ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION)); + + ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT)); + + auto widgetSize = widget_size_with_row_get(2); + + shortcut(manager.chords[SHORTCUT_CONFIRM]); + ImGui::BeginDisabled(!is_bake_into_other_frames_ready()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) + { + bake_into_other_frames(); + bakeIntoOtherFramesPopup.close(); + } + ImGui::EndDisabled(); + + ImGui::SameLine(); + + shortcut(manager.chords[SHORTCUT_CANCEL]); + if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES)); + + ImGui::EndPopup(); + } + + if (animation) + { + if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); + + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) + { + playback_stop(); + playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL)) + { + playback_stop(); + playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + struct FrameResize + { + 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 (!isResizeChordHeld[i]) edit_begin_push(resize.edit); + command_push( + [=, this](Manager&, Document& document) + { + for (auto frameReference : selectedFrames) + if (auto frame = document.model.frame_edit(frameReference)) + frame->duration = + std::clamp(frame->duration + resize.delta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + document.change(); + }); + } + isResizeChordHeld[i] = isPressed; + } + + 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 || isNextFrame) + if (auto item = selected_item_get(); item && !item->frames.empty()) + { + auto frameReference = reference; + frameReference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, + (int)item->frames.size() - 1); + reference_set(frameReference); + document.frame_focus_select(); + document.frameTime = model::frame_time_from_index_get(*item, reference.frameIndex); + } + + if (isPreviousItem) reference_set_adjacent_item(-1); + if (isNextItem) reference_set_adjacent_item(1); + } + + if (isTextPushed) ImGui::PopStyleColor(); + } } diff --git a/src/imgui/window/timeline/timeline.hpp b/src/imgui/window/timeline/timeline.hpp index 4c30443..09dab0a 100644 --- a/src/imgui/window/timeline/timeline.hpp +++ b/src/imgui/window/timeline/timeline.hpp @@ -7,6 +7,7 @@ #include #include "clipboard.hpp" +#include "icon.hpp" #include "manager.hpp" #include "popup/item_properties.hpp" #include "resources.hpp" @@ -16,6 +17,59 @@ namespace anm2ed::imgui { + inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); + inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); + inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); + + inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); + inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); + inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); + + inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); + inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); + inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); + + inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); + inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); + inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); + +#define ANM2_ITEM_TYPES \ + X(NONE, STRING_UNDEFINED, resource::icon::NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ + X(ROOT, BASIC_ROOT, resource::icon::ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ + X(LAYER, BASIC_LAYER_ANIMATION, resource::icon::LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ + X(NULL_, BASIC_NULL_ANIMATION, resource::icon::NULL_, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ + X(TRIGGER, BASIC_TRIGGERS, resource::icon::TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) + + constexpr StringType TYPE_STRINGS[] = { +#define X(symbol, string, icon, color, colorActive, colorHovered) string, + ANM2_ITEM_TYPES +#undef X + }; + + constexpr resource::icon::Type TYPE_ICONS[] = { +#define X(symbol, string, icon, color, colorActive, colorHovered) icon, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR[] = { +#define X(symbol, string, icon, color, colorActive, colorHovered) color, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { +#define X(symbol, string, icon, color, colorActive, colorHovered) colorActive, + ANM2_ITEM_TYPES +#undef X + }; + + inline const glm::vec4 TYPE_COLOR_HOVERED[] = { +#define X(symbol, string, icon, color, colorActive, colorHovered) colorHovered, + ANM2_ITEM_TYPES +#undef X + }; + struct TimelineContext; // A timeline row: a track (in a group or not), a group, or a group's root. groupType/groupId name the group a diff --git a/src/imgui/window/tools.cpp b/src/imgui/window/tools.cpp index 7c45ee9..fe20e7b 100644 --- a/src/imgui/window/tools.cpp +++ b/src/imgui/window/tools.cpp @@ -1,13 +1,13 @@ -#include "tools.hpp" +#include "panel.hpp" #include #include "strings.hpp" #include "tool.hpp" #include "types.hpp" +#include "util/imgui/layout.hpp" #include "util/imgui/shortcut.hpp" -#include "util/imgui/tooltip.hpp" using namespace anm2ed::resource; using namespace anm2ed::types; @@ -15,7 +15,7 @@ using namespace glm; namespace anm2ed::imgui { - void Tools::update(Manager& manager, Settings& settings, Resources& resources) + void tools_update(Manager& manager, Settings& settings, Resources& resources, PopupHelper& colorEditPopup) { auto& document = *manager.get(); @@ -66,8 +66,6 @@ namespace anm2ed::imgui if (ImGui::ColorButton(labelText, to_imvec4(settings.toolColor), ImGuiColorEditFlags_NoTooltip, to_imvec2(size))) tool_use((tool::Type)i); - - colorEditPosition = ImGui::GetCursorScreenPos(); } else { diff --git a/src/imgui/window/tools.hpp b/src/imgui/window/tools.hpp deleted file mode 100644 index e6e8831..0000000 --- a/src/imgui/window/tools.hpp +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include "manager.hpp" -#include "resources.hpp" -#include "settings.hpp" -#include "strings.hpp" - -namespace anm2ed::imgui -{ - class Tools - { - bool isOpenColorEdit{}; - ImVec2 colorEditPosition{}; - - PopupHelper colorEditPopup{ - PopupHelper(LABEL_TOOLS_COLOR_EDIT_POPUP, POPUP_TO_CONTENT, POPUP_BY_ITEM)}; - - public: - void update(Manager&, Settings&, Resources&); - }; -} diff --git a/src/imgui/window/welcome.cpp b/src/imgui/window/welcome.cpp index 775e886..de9f2ad 100644 --- a/src/imgui/window/welcome.cpp +++ b/src/imgui/window/welcome.cpp @@ -1,4 +1,6 @@ -#include "welcome.hpp" +#include "documents.hpp" +#include "panel.hpp" +#include "taskbar.hpp" #include #include @@ -13,7 +15,7 @@ using namespace anm2ed::resource; namespace anm2ed::imgui { - void Welcome::update(Manager& manager, Resources& resources, Dialog& dialog, Taskbar& taskbar, Documents& documents) + void welcome_update(Manager& manager, Resources& resources, Dialog& dialog, Taskbar& taskbar, Documents& documents) { auto viewport = ImGui::GetMainViewport(); auto windowHeight = viewport->Size.y - taskbar.height - documents.height; diff --git a/src/imgui/window/welcome.hpp b/src/imgui/window/welcome.hpp deleted file mode 100644 index 1a6cc44..0000000 --- a/src/imgui/window/welcome.hpp +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once - -#include "documents.hpp" -#include "taskbar.hpp" - -namespace anm2ed::imgui -{ - class Welcome - { - public: - void update(Manager&, Resources&, Dialog&, Taskbar&, Documents&); - }; -}; diff --git a/src/model/common.hpp b/src/model/common.hpp index b1d551e..f6ced6b 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -7,8 +7,6 @@ #include -#include "icon.hpp" -#include "strings.hpp" #include "types.hpp" #define ANM2_ELEMENT_TYPES \ @@ -106,59 +104,6 @@ namespace anm2ed inline constexpr int APPEND_RIGHT = (int)SpritesheetMergeOrigin::APPEND_RIGHT; inline constexpr int APPEND_BOTTOM = (int)SpritesheetMergeOrigin::APPEND_BOTTOM; - inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); - inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); - inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); - - inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f); - inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f); - inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f); - - inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f); - inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f); - inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f); - - inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f); - inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); - -#define ANM2_ITEM_TYPES \ - X(NONE, STRING_UNDEFINED, resource::icon::NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ - X(ROOT, BASIC_ROOT, resource::icon::ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ - X(LAYER, BASIC_LAYER_ANIMATION, resource::icon::LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ - X(NULL_, BASIC_NULL_ANIMATION, resource::icon::NULL_, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ - X(TRIGGER, BASIC_TRIGGERS, resource::icon::TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) - - constexpr StringType TYPE_STRINGS[] = { -#define X(symbol, string, icon, color, colorActive, colorHovered) string, - ANM2_ITEM_TYPES -#undef X - }; - - constexpr resource::icon::Type TYPE_ICONS[] = { -#define X(symbol, string, icon, color, colorActive, colorHovered) icon, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR[] = { -#define X(symbol, string, icon, color, colorActive, colorHovered) color, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR_ACTIVE[] = { -#define X(symbol, string, icon, color, colorActive, colorHovered) colorActive, - ANM2_ITEM_TYPES -#undef X - }; - - inline const glm::vec4 TYPE_COLOR_HOVERED[] = { -#define X(symbol, string, icon, color, colorActive, colorHovered) colorHovered, - ANM2_ITEM_TYPES -#undef X - }; - enum class RegionFrameMapping { PRESERVE, diff --git a/src/model/frames.cpp b/src/model/frames.cpp index 87b84db..7f566c3 100644 --- a/src/model/frames.cpp +++ b/src/model/frames.cpp @@ -203,24 +203,6 @@ namespace anm2ed::model } } - // Bakes every ease-in/ease-out frame (not linear ones) in every track into single-step frames. - void special_interpolated_frames_bake(Model& model, int interval, bool isRoundScale, bool isRoundRotation) - { - for (int i = 0; i < model.animations_count_get(); ++i) - animation_tracks_each(*model.animation_edit(i), - [&](Track& track) - { - if (track.type == ItemType::TRIGGER) return; - for (int index = (int)track.frames.size() - 1; index >= 0; --index) - { - auto interpolation = track.frames[index].interpolation; - if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) - continue; - frame_bake(track, index, interval, isRoundScale, isRoundRotation); - } - }); - } - // Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn. glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform) { diff --git a/src/model/frames.hpp b/src/model/frames.hpp index 73fb74d..932bf0b 100644 --- a/src/model/frames.hpp +++ b/src/model/frames.hpp @@ -19,6 +19,5 @@ namespace anm2ed::model void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); void frames_sort_by_at_frame(Track&); void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&); - void special_interpolated_frames_bake(Model&, int, bool, bool); glm::vec4 animation_rect(const Model&, const Animation&, bool); } diff --git a/src/model/xml.cpp b/src/model/xml.cpp index c087695..c21d0f6 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -13,7 +13,6 @@ #include "math.hpp" #include "path.hpp" #include "time.hpp" -#include "util/xml.hpp" using namespace tinyxml2; using namespace anm2ed::util; @@ -1337,7 +1336,9 @@ namespace anm2ed::model { XMLDocument document{}; document.InsertEndChild(element_write(document, node)); - return xml::document_to_string(document); + XMLPrinter printer{}; + document.Print(&printer); + return printer.CStr(); } void node_hash(std::uint64_t& hash, const XmlNode& node) @@ -1430,23 +1431,6 @@ namespace anm2ed::model return hash; } - bool is_special_interpolated_frames(const Model& model) - { - for (auto [index, animation] : model.animations_get()) - { - bool isSpecial{}; - animation_tracks_each(*animation, - [&](const Track& track) - { - for (const auto& frame : track.frames) - isSpecial |= - track.type != ItemType::TRIGGER && is_special_interpolation(frame.interpolation); - }); - if (isSpecial) return true; - } - return false; - } - std::string frame_to_string(const Frame& frame, ItemType type) { return node_to_string(frame_write(Writer(CLIPBOARD_FLAGS), frame, type)); diff --git a/src/model/xml.hpp b/src/model/xml.hpp index affd2e7..fbd00af 100644 --- a/src/model/xml.hpp +++ b/src/model/xml.hpp @@ -16,7 +16,6 @@ namespace anm2ed::model std::string model_to_string(const Model&, Options = {}); std::string model_serialize(const Model&, Flags); std::uint64_t model_hash(const Model&); - bool is_special_interpolated_frames(const Model&); std::string frame_to_string(const Frame&, ItemType); std::string animation_to_string(const Animation&, int = -1); diff --git a/src/render.cpp b/src/render.cpp index 2585190..b7901d5 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -1,6 +1,8 @@ #include "render.hpp" #include +#include +#include #include #include #include @@ -9,15 +11,16 @@ #include +#include "audio.hpp" +#include "document.hpp" #include "file.hpp" #include "log.hpp" #include "path.hpp" #include "process.hpp" +#include "toast.hpp" -#if _WIN32 - #include "string.hpp" -#endif - +using namespace anm2ed::imgui; +using namespace anm2ed::resource; using namespace anm2ed::util; namespace anm2ed @@ -59,7 +62,8 @@ namespace anm2ed if (type != render::GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && audioStream.spec.channels > 0) { - auto tempFilenameUtf8 = std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); + auto tempFilenameUtf8 = + std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); audioPath = temporaryDirectory / path::from_utf8(tempFilenameUtf8); auto data = (const char*)audioStream.stream.data(); @@ -104,8 +108,8 @@ namespace anm2ed auto framePattern = temporaryDirectory / path::from_utf8("frame_%06d.png"); auto framePatternString = path::to_utf8(framePattern); - command = std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, - framePatternString); + command = + std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, framePatternString); if (!audioInputArguments.empty()) command += " " + audioInputArguments; command += std::format(" -fps_mode cfr -r {}", fps); @@ -113,10 +117,9 @@ namespace anm2ed switch (type) { case render::GIF: - command += - " -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];" - "[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\"" - " -loop 0"; + command += " -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];" + "[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\"" + " -loop 0"; command += std::format(" \"{}\"", pathString); break; case render::WEBM: @@ -142,7 +145,7 @@ namespace anm2ed } #if _WIN32 - command = string::quote(command); + command = "\"" + command + "\""; #endif logger.command(command); @@ -171,3 +174,190 @@ namespace anm2ed return true; } } + +namespace anm2ed::render +{ + constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000; + constexpr int ALPHA_OPAQUE = 255; + constexpr float CHANNEL_MAX = 255.0f; + + std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, Type type) + { + auto fallback = path::from_utf8(std::format("frame_{:06}.png", index)); + if (type != PNGS) return fallback; + try + { + auto filename = path::from_utf8(std::vformat(path::to_utf8(format), std::make_format_args(index))).filename(); + if (filename.empty()) return fallback; + if (filename.extension().empty()) filename.replace_extension(EXTENSIONS[SPRITESHEET]); + return filename; + } + catch (...) + { + return fallback; + } + } + + // PNG sequences go straight to their folder; other outputs collect frames in a temporary folder beside the output. + std::filesystem::path frames_directory_create(const RecorderOptions& options) + { + std::error_code ec{}; + if (options.type == PNGS) + { + std::filesystem::create_directories(options.path, ec); + return options.path; + } + auto directory = options.path.parent_path(); + if (directory.empty()) directory = std::filesystem::current_path(); + std::filesystem::create_directories(directory, ec); + auto timestamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + for (int suffix = 0; suffix < TEMP_DIRECTORY_ATTEMPTS; ++suffix) + { + auto temporary = directory / path::from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); + if (std::filesystem::create_directories(temporary, ec)) return temporary; + } + return {}; + } + + // Rendered pixels are premultiplied; outputs on a transparent background want straight alpha. + void pixels_unpremultiply(std::vector& pixels) + { + for (std::size_t index = 0; index + 3 < pixels.size(); index += image::CHANNELS) + { + auto alpha = pixels[index + 3]; + if (alpha == ALPHA_OPAQUE) continue; + for (int channel = 0; channel < 3; ++channel) + pixels[index + channel] = + alpha == 0 + ? 0 + : (uint8_t)glm::clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX); + } + } + + void sounds_detach(const Document& document, MIX_Mixer* mixer) + { + for (auto& [id, _] : document.sounds) + if (auto sound = document.sound_get(id)) audio::track_detach(*sound, mixer); + } + + // Mixes each frame's trigger sound into one stream at the render frame rate. + bool audio_stream_generate(AudioStream& audioStream, const Document& document, const std::vector& soundIds, + int fps) + { + audioStream.stream.clear(); + if (soundIds.empty() || fps <= 0) return true; + + SDL_AudioSpec mixSpec = audioStream.spec; + mixSpec.format = SDL_AUDIO_F32; + auto mixer = MIX_CreateMixer(&mixSpec); + if (!mixer) return false; + + auto channels = std::max(mixSpec.channels, 1); + auto framesPerStep = (double)std::max(mixSpec.freq, 1) / (double)fps; + auto accumulator = 0.0; + std::vector buffer{}; + auto isGenerated = true; + for (auto soundId : soundIds) + { + if (auto sound = document.sound_get(soundId)) audio::play(*sound, false, mixer); + accumulator += framesPerStep; + auto sampleFrames = std::max((int)std::floor(accumulator), 1); + accumulator -= (double)sampleFrames; + buffer.resize((std::size_t)sampleFrames * (std::size_t)channels); + if (!(isGenerated = MIX_Generate(mixer, buffer.data(), (int)(buffer.size() * sizeof(float))))) break; + audioStream.stream.insert(audioStream.stream.end(), buffer.begin(), buffer.end()); + } + sounds_detach(document, mixer); + MIX_DestroyMixer(mixer); + if (!isGenerated) audioStream.stream.clear(); + return isGenerated; + } + + bool Recorder::start(const RecorderOptions& recorderOptions) + { + options = recorderOptions; + index = 0; + count = frame_count_get(options.start, options.end, options.animationFps, options.fps); + frames.clear(); + soundIds.clear(); + soundTime = -1; + directory = frames_directory_create(options); + return !directory.empty(); + } + + bool Recorder::is_done() const { return index >= count; } + + float Recorder::time_get() const { return frame_time_get(options.start, index, options.animationFps, options.fps); } + + // A trigger sound is taken once per animation frame, however many render frames it spans. + bool Recorder::is_sound_frame() const { return (int)std::floor(time_get()) != soundTime; } + + bool Recorder::frame_capture(std::vector pixels, glm::ivec2 size, int soundId) + { + soundTime = (int)std::floor(time_get()); + soundIds.push_back(soundId); + if (options.isIsolated || options.isBounded) pixels_unpremultiply(pixels); + auto framePath = directory / frame_filename_get(options.format, index, options.type); + if (!Image::write_pixels_png(framePath, size, pixels.data())) return false; + frames.push_back(framePath); + ++index; + return true; + } + + void Recorder::finish(const Document& document, AudioStream& audioStream) + { + auto pathString = path::to_utf8(options.path); + if (options.type == PNGS) + toast_log(frames.empty() ? Level::ERROR : Level::INFO, + frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); + else if (options.type == SPRITESHEET) + { + auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); + auto first = frames.empty() ? Image{} : Image(frames.front()); + if (frames.empty()) + toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); + else if (!first.is_valid()) + toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); + else + { + Image sheet{}; + sheet.size = first.size * glm::ivec2(layout.columns, layout.rows); + sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * image::CHANNELS); + for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) + if (auto frame = Image(frames[i]); frame.size == first.size) + sheet.paste(frame, first.size * glm::ivec2(i % layout.columns, i / layout.columns)); + auto isSaved = sheet.write_png(options.path); + toast_log(isSaved ? Level::INFO : Level::ERROR, + isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); + } + } + else + { + audioStream.stream.clear(); + if (options.isSound && options.type != GIF && + !audio_stream_generate(audioStream, document, soundIds, options.fps)) + { + toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED)); + logger.error("Failed to generate deterministic render audio stream; exporting without audio."); + } + auto isRendered = + animation_render(options.ffmpegPath, options.path, frames, audioStream, options.type, options.fps); + toast_log(isRendered ? Level::INFO : Level::ERROR, + isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); + } + cancel(); + } + + // Stops; the temporary frame folder is removed (a PNG sequence's own folder is kept). + void Recorder::cancel() + { + std::error_code ec{}; + if (options.type != PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec); + directory.clear(); + frames.clear(); + soundIds.clear(); + index = count = 0; + } +} diff --git a/src/render.hpp b/src/render.hpp index 95c2c20..ecce636 100644 --- a/src/render.hpp +++ b/src/render.hpp @@ -2,10 +2,17 @@ #include #include +#include +#include #include "audio_stream.hpp" #include "texture.hpp" +namespace anm2ed +{ + class Document; +} + namespace anm2ed::render { #define RENDER_LIST \ @@ -103,6 +110,47 @@ namespace anm2ed::render return {rows, columns}; } + + struct RecorderOptions + { + Type type{}; + std::filesystem::path path{}; + std::filesystem::path format{}; + std::filesystem::path ffmpegPath{}; + int start{}; + int end{}; + int animationFps{1}; + int fps{1}; + int rows{}; + int columns{}; + bool isSound{}; + bool isIsolated{}; + bool isBounded{}; + }; + + // A render in progress: which animation times to capture, the frames captured so far (written to disk) and the + // trigger sound of each, and assembling the output when done. + class Recorder + { + public: + RecorderOptions options{}; + int index{}; + int count{}; + + bool start(const RecorderOptions&); + bool is_done() const; + float time_get() const; + bool is_sound_frame() const; + bool frame_capture(std::vector, glm::ivec2, int); + void finish(const Document&, AudioStream&); + void cancel(); + + private: + std::filesystem::path directory{}; + std::vector frames{}; + std::vector soundIds{}; + int soundTime{-1}; + }; } namespace anm2ed diff --git a/src/resource/audio_stream.cpp b/src/resource/audio_stream.cpp index d569d71..2394b3b 100644 --- a/src/resource/audio_stream.cpp +++ b/src/resource/audio_stream.cpp @@ -23,35 +23,4 @@ namespace anm2ed AudioStream::AudioStream(MIX_Mixer* mixer) { MIX_GetMixerFormat(mixer, &spec); } - void AudioStream::capture_begin(MIX_Mixer* mixer) - { - stream.clear(); - callbackSamples = 0; - captureStartCounter = SDL_GetPerformanceCounter(); - firstCallbackCounter = 0; - isFirstCallbackCaptured = false; - MIX_SetPostMixCallback(mixer, callback, this); - } - - void AudioStream::capture_end(MIX_Mixer* mixer) - { - MIX_SetPostMixCallback(mixer, nullptr, this); - stream.clear(); - } - - double AudioStream::callback_latency_seconds_get() const - { - auto freq = std::max(spec.freq, 1); - auto channels = std::max(spec.channels, 1); - auto framesPerCallback = (double)callbackSamples / (double)channels; - return framesPerCallback / (double)freq; - } - - double AudioStream::capture_start_delay_seconds_get() const - { - if (!isFirstCallbackCaptured || captureStartCounter == 0 || firstCallbackCounter < captureStartCounter) return 0.0; - auto frequency = SDL_GetPerformanceFrequency(); - if (frequency == 0) return 0.0; - return (double)(firstCallbackCounter - captureStartCounter) / (double)frequency; - } } diff --git a/src/resource/audio_stream.hpp b/src/resource/audio_stream.hpp index f5fe532..ee2f189 100644 --- a/src/resource/audio_stream.hpp +++ b/src/resource/audio_stream.hpp @@ -18,9 +18,5 @@ namespace anm2ed bool isFirstCallbackCaptured{}; AudioStream(MIX_Mixer*); - void capture_begin(MIX_Mixer*); - void capture_end(MIX_Mixer*); - double callback_latency_seconds_get() const; - double capture_start_delay_seconds_get() const; }; } diff --git a/src/resource/strings.cpp b/src/resource/strings.cpp deleted file mode 100644 index 1bd224d..0000000 --- a/src/resource/strings.cpp +++ /dev/null @@ -1,3 +0,0 @@ -#include "strings.hpp" - -anm2ed::Localizer localize; diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 5f582f7..9bbe14a 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -817,7 +817,7 @@ namespace anm2ed }; } -extern anm2ed::Localizer localize; +inline anm2ed::Localizer localize; namespace anm2ed { diff --git a/src/settings.hpp b/src/settings.hpp index 0a168d5..fae888b 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -6,7 +6,6 @@ #include #include "model/common.hpp" -#include "origin.hpp" #include "render.hpp" #include "strings.hpp" #include "types.hpp" @@ -164,7 +163,7 @@ namespace anm2ed X(MERGE_SPRITESHEETS_ORIGIN, mergeSpritesheetsOrigin, STRING_UNDEFINED, INT, APPEND_RIGHT) \ X(MERGE_SPRITESHEETS_IS_MAKE_REGIONS, mergeSpritesheetsIsMakeRegions, STRING_UNDEFINED, BOOL, true) \ X(MERGE_SPRITESHEETS_IS_MAKE_PRIMARY_REGION, mergeSpritesheetsIsMakePrimaryRegion, STRING_UNDEFINED, BOOL, true) \ - X(MERGE_SPRITESHEETS_REGION_ORIGIN, mergeSpritesheetsRegionOrigin, STRING_UNDEFINED, INT, origin::TOP_LEFT) \ + X(MERGE_SPRITESHEETS_REGION_ORIGIN, mergeSpritesheetsRegionOrigin, STRING_UNDEFINED, INT, 0) \ X(PACK_PADDING, packPadding, STRING_UNDEFINED, INT, 1) \ X(EXPORT_REGION_PATH, exportRegionPath, STRING_UNDEFINED, PATH, "./region.png") \ X(EXPORT_REGION_IS_MAKE_SPRITESHEET, isExportRegionMakeSpritesheet, STRING_UNDEFINED, BOOL, true) \ diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 689153b..bcbf992 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -77,7 +77,6 @@ namespace anm2ed } void SnapshotStack::max_size_set(int value) { maxSize = std::max(value, 0); } - int SnapshotStack::max_size_get() { return maxSize; } // Starts an undoable edit: remembers the state before it (cheap; animations are shared). void Snapshots::push(const std::string& message) diff --git a/src/snapshots.hpp b/src/snapshots.hpp index eb3a7c1..f2d2784 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -54,7 +54,6 @@ namespace anm2ed void trim_to_limit(); static void max_size_set(int); - static int max_size_get(); private: static int maxSize; diff --git a/src/util/imgui/constants.hpp b/src/util/imgui/constants.hpp deleted file mode 100644 index 5c2691d..0000000 --- a/src/util/imgui/constants.hpp +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -namespace anm2ed::imgui -{ - constexpr auto DRAG_SPEED = 0.25f; - constexpr auto DRAG_SPEED_FAST = 1.00f; - constexpr auto STEP = 1.0f; - constexpr auto STEP_FAST = 5.0f; -} diff --git a/src/util/imgui/input.cpp b/src/util/imgui/input.cpp index f999cea..46ceb56 100644 --- a/src/util/imgui/input.cpp +++ b/src/util/imgui/input.cpp @@ -42,15 +42,6 @@ namespace anm2ed::imgui return edited; } - bool combo_negative_one_indexed(const std::string& label, int* index, std::vector& strings) - { - *index += 1; - bool isActivated = ImGui::Combo(label.c_str(), index, strings.data(), (int)strings.size()); - *index -= 1; - - return isActivated; - } - bool combo_id_mapped(const std::string& label, int* id, const std::vector& ids, const std::vector& labelStrings) { @@ -78,37 +69,6 @@ namespace anm2ed::imgui return isActivated; } - edit_state::Type drag_int_persistent(const char* label, int* value, float speed, int min, int max, const char* format, - ImGuiSliderFlags flags) - { - static bool isEditing{}; - static int start{INT_MAX}; - auto persistent = value ? *value : 0; - - ImGui::DragInt(label, &persistent, speed, min, max, format, flags); - if (!value) return edit_state::NONE; - if (ImGui::IsItemActivated() && persistent != start) - { - isEditing = true; - start = *value; - return edit_state::START; - } - else if (ImGui::IsItemDeactivatedAfterEdit()) - { - isEditing = false; - *value = persistent; - start = INT_MAX; - return edit_state::END; - } - else if (isEditing) - { - *value = persistent; - return edit_state::DURING; - } - - return edit_state::NONE; - } - edit_state::Type drag_float_persistent(const char* label, float* value, float speed, float min, float max, const char* format, ImGuiSliderFlags flags) { diff --git a/src/util/imgui/input.hpp b/src/util/imgui/input.hpp index 4884c99..4759b28 100644 --- a/src/util/imgui/input.hpp +++ b/src/util/imgui/input.hpp @@ -7,11 +7,15 @@ #include #include -#include "constants.hpp" #include "types.hpp" namespace anm2ed::imgui { + constexpr auto DRAG_SPEED = 0.25f; + constexpr auto DRAG_SPEED_FAST = 1.00f; + constexpr auto STEP = 1.0f; + constexpr auto STEP_FAST = 5.0f; + int input_text_callback(ImGuiInputTextCallbackData*); bool input_text_string(const char*, std::string*, ImGuiInputTextFlags = 0); bool input_text_path(const char*, std::filesystem::path*, ImGuiInputTextFlags = 0); @@ -19,8 +23,6 @@ namespace anm2ed::imgui bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", ImGuiInputTextFlags = 0); - types::edit_state::Type drag_int_persistent(const char*, int*, float = DRAG_SPEED, int = {}, int = {}, - const char* = "%d", ImGuiSliderFlags = 0); types::edit_state::Type drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", ImGuiSliderFlags = 0); types::edit_state::Type drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, @@ -28,6 +30,5 @@ namespace anm2ed::imgui types::edit_state::Type color_edit3_persistent(const char*, glm::vec3*, ImGuiColorEditFlags = 0); types::edit_state::Type color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - bool combo_negative_one_indexed(const std::string&, int*, std::vector&); bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); } diff --git a/src/util/imgui/layout.cpp b/src/util/imgui/layout.cpp index 9c613db..077d580 100644 --- a/src/util/imgui/layout.cpp +++ b/src/util/imgui/layout.cpp @@ -1,5 +1,7 @@ #include "layout.hpp" +#include "strings.hpp" + namespace anm2ed::imgui { float row_widget_width_get(int count, float width) @@ -35,4 +37,9 @@ namespace anm2ed::imgui { return ImVec2(ImGui::GetTextLineHeightWithSpacing(), ImGui::GetTextLineHeightWithSpacing()); } + + void set_item_tooltip_shortcut(const char* tooltip, const std::string& shortcut) + { + ImGui::SetItemTooltip("%s", localize_format(FORMAT_TOOLTIP_SHORTCUT, tooltip, shortcut).c_str()); + } } diff --git a/src/util/imgui/layout.hpp b/src/util/imgui/layout.hpp index 0bc530f..ff88f46 100644 --- a/src/util/imgui/layout.hpp +++ b/src/util/imgui/layout.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include namespace anm2ed::imgui @@ -11,4 +13,5 @@ namespace anm2ed::imgui ImVec2 size_without_footer_get(int = 1); ImVec2 child_size_get(int = 1); ImVec2 icon_size_get(); + void set_item_tooltip_shortcut(const char*, const std::string& = {}); } diff --git a/src/util/imgui/tooltip.cpp b/src/util/imgui/tooltip.cpp deleted file mode 100644 index 10e3b87..0000000 --- a/src/util/imgui/tooltip.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "tooltip.hpp" - -#include - -#include - -#include "strings.hpp" - -namespace anm2ed::imgui -{ - void set_item_tooltip_shortcut(const char* tooltip, const std::string& shortcut) - { - ImGui::SetItemTooltip( - "%s", std::vformat(localize.get(FORMAT_TOOLTIP_SHORTCUT), std::make_format_args(tooltip, shortcut)).c_str()); - } -} diff --git a/src/util/imgui/tooltip.hpp b/src/util/imgui/tooltip.hpp deleted file mode 100644 index 1ba162c..0000000 --- a/src/util/imgui/tooltip.hpp +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include - -namespace anm2ed::imgui -{ - void set_item_tooltip_shortcut(const char*, const std::string& = {}); -} diff --git a/src/util/map.hpp b/src/util/map.hpp deleted file mode 100644 index 6a75c89..0000000 --- a/src/util/map.hpp +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -namespace anm2ed::util::map -{ - template int next_id_get(std::map& map) - { - int id = 0; - - for (auto& [key, value] : map) - { - if (key != id) break; - ++id; - } - - return id; - } - - template T1* find(std::map& map, T0 index) - { - return map.contains(index) ? &map[index] : nullptr; - } -} diff --git a/src/util/math.cpp b/src/util/math.cpp index 6307f43..09051e4 100644 --- a/src/util/math.cpp +++ b/src/util/math.cpp @@ -12,8 +12,6 @@ namespace anm2ed::util::math constexpr auto FLOAT_FORMAT_EPSILON = 1e-7f; constexpr float FLOAT_FORMAT_POW10[] = {1.f, 10.f, 100.f, 1000.f, 10000.f, 100000.f, 1000000.f, 10000000.f}; - float round_nearest_multiple(float value, float multiple) { return (roundf((value) / (multiple)) * (multiple)); } - int float_decimals_needed(float value) { for (int decimalCount = 0; decimalCount <= FLOAT_FORMAT_MAX_DECIMALS; ++decimalCount) diff --git a/src/util/math.hpp b/src/util/math.hpp index f26e57c..3de3d66 100644 --- a/src/util/math.hpp +++ b/src/util/math.hpp @@ -19,8 +19,6 @@ namespace anm2ed::util::math 1.0f, 1.0f, uvMax.x, uvMax.y, 0.0f, 1.0f, uvMin.x, uvMax.y}; } - float round_nearest_multiple(float, float); - int float_decimals_needed(float); const char* float_format_get(float); diff --git a/src/util/origin.hpp b/src/util/origin.hpp deleted file mode 100644 index fa3481a..0000000 --- a/src/util/origin.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -namespace anm2ed::origin -{ - enum Type - { - TOP_LEFT, - ORIGIN_CENTER, - CUSTOM - }; -} diff --git a/src/util/string.cpp b/src/util/string.cpp deleted file mode 100644 index a2a427e..0000000 --- a/src/util/string.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "string.hpp" - -#include - -namespace anm2ed::util::string -{ - std::string to_lower(const std::string& string) - { - std::string transformed = string; - std::ranges::transform(transformed, transformed.begin(), [](const unsigned char c) { return std::tolower(c); }); - return transformed; - } - - std::string backslash_replace(const std::string& string) - { - std::string transformed = string; - for (char& character : transformed) - if (character == '\\') character = '/'; - return transformed; - } - - std::string quote(const std::string& string) { return "\"" + string + "\""; } - - bool to_bool(const std::string& string) { return to_lower(string) == "true"; } -} diff --git a/src/util/string.hpp b/src/util/string.hpp deleted file mode 100644 index 968656c..0000000 --- a/src/util/string.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -namespace anm2ed::util::string -{ - std::string to_lower(const std::string&); - std::string backslash_replace(const std::string&); - std::string quote(const std::string&); - bool to_bool(const std::string&); -} diff --git a/src/util/unordered_map.hpp b/src/util/unordered_map.hpp deleted file mode 100644 index 2c37e77..0000000 --- a/src/util/unordered_map.hpp +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -namespace anm2ed::util::unordered_map -{ - template T1* find(std::unordered_map& map, T0 index) - { - return map.contains(index) ? &map[index] : nullptr; - } -} diff --git a/src/util/vector.hpp b/src/util/vector.hpp index fd48c25..9d8e567 100644 --- a/src/util/vector.hpp +++ b/src/util/vector.hpp @@ -20,71 +20,6 @@ namespace anm2ed::util::vector } template bool in_bounds(std::vector& v, int index) { return index >= 0 && index < (int)v.size(); } - template void clamp_in_bounds(std::vector& v, int& index) - { - index = std::clamp(index, 0, (int)v.size() - 1); - } - - template int move_index(std::vector& v, int source, int dest) - { - auto size = (int)(v.size()); - if (source < 0 || source >= size) return -1; - dest = std::clamp(dest, 0, size - 1); - - if (source == dest) return dest; - - auto isInsertAfter = source < dest; - - T item = std::move(v[source]); - v.erase(v.begin() + source); - - if (dest > source) --dest; // destination shifts when removing earlier slot - if (isInsertAfter) ++dest; // drop after original target - - dest = std::clamp(dest, 0, (int)(v.size())); - v.insert(v.begin() + dest, std::move(item)); - return dest; - } - - template std::set move_indices(std::vector& v, std::vector& indices, int index) - { - if (indices.empty()) return {}; - - std::vector sorted = indices; - std::sort(sorted.begin(), sorted.end()); - sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end()); - - // Determine if we are dragging items from below the target (insert before) or above (insert after) - bool insertAfter = !sorted.empty() && sorted.front() <= index; - - std::vector moveItems; - moveItems.reserve(sorted.size()); - for (int i : sorted) - moveItems.push_back(std::move(v[i])); - - for (auto i : sorted | std::views::reverse) - v.erase(v.begin() + i); - - int originalSize = (int)v.size() + (int)sorted.size(); - int reference = insertAfter ? index + 1 : index; - reference = std::clamp(reference, 0, originalSize); - - int removedBeforeReference = 0; - for (int i : sorted) - if (i < reference) ++removedBeforeReference; - - int insertPos = reference - removedBeforeReference; - insertPos = std::clamp(insertPos, 0, (int)v.size()); - - v.insert(v.begin() + insertPos, std::make_move_iterator(moveItems.begin()), - std::make_move_iterator(moveItems.end())); - - std::set moveIndices{}; - for (int i = 0; i < (int)moveItems.size(); i++) - moveIndices.insert(insertPos + i); - - return moveIndices; - } template std::set move_indices_to_position(std::vector& v, const std::vector& indices, int insertPos) diff --git a/src/util/xml.cpp b/src/util/xml.cpp deleted file mode 100644 index 5a413d5..0000000 --- a/src/util/xml.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include "xml.hpp" - -using namespace tinyxml2; - -namespace anm2ed::util::xml -{ - std::string document_to_string(XMLDocument& self) - { - XMLPrinter printer{}; - self.Print(&printer); - return std::string(printer.CStr()); - } -} diff --git a/src/util/xml.hpp b/src/util/xml.hpp deleted file mode 100644 index dba0ed5..0000000 --- a/src/util/xml.hpp +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -#include - -namespace anm2ed::util::xml -{ - std::string document_to_string(tinyxml2::XMLDocument&); -} diff --git a/tests/common.hpp b/tests/common.hpp index 78b29b8..9c1e7bc 100644 --- a/tests/common.hpp +++ b/tests/common.hpp @@ -8,9 +8,10 @@ #include #include +#include + #include "edit/edit.hpp" #include "model/xml.hpp" -#include "util/xml.hpp" namespace anm2ed::test { @@ -86,7 +87,9 @@ namespace anm2ed::test document.Parse(text.c_str()); if (auto source = document.RootElement()->FirstChildElement("SourceDocument")) document.RootElement()->DeleteChild(source); - return util::xml::document_to_string(document); + tinyxml2::XMLPrinter printer{}; + document.Print(&printer); + return printer.CStr(); } // Save/reload properties every document must hold.