diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index b74d9ec..41d526c 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -8,7 +9,6 @@ #include #include #include -#include #include #include @@ -193,6 +193,20 @@ namespace anm2ed #undef X }; + enum class RegionFrameMapping + { + PRESERVE, + SET + }; + + enum FileMergePreset + { + FILE_MERGE_PRESET_MERGE_BY_NAME, + FILE_MERGE_PRESET_APPEND_AS_NEW, + FILE_MERGE_PRESET_REPLACE_MATCHING, + FILE_MERGE_PRESET_COUNT + }; + enum class ChangeType { ADJUST, @@ -401,8 +415,8 @@ namespace anm2ed template ElementPointer shader_uniform_component_get(E& uniform, int index) { - return child_find( - uniform, [&](const Element& child) { return child.type == ElementType::COMPONENT && child.index == index; }); + return child_find(uniform, [&](const Element& child) + { return child.type == ElementType::COMPONENT && child.index == index; }); } template ElementPointer element_first_get(E& element, ElementType type) @@ -432,8 +446,7 @@ namespace anm2ed } template - ElementPointer animation_item_get(E& animation, ItemType type, int id = -1, int groupType = NONE, - int groupId = -1) + ElementPointer animation_item_get(E& animation, ItemType type, int id = -1, int groupType = NONE, int groupId = -1) { auto trackType = TYPE_TRACKS[(int)type]; auto isGrouped = groupType != NONE && groupId != -1; @@ -495,6 +508,7 @@ namespace anm2ed int element_child_max_id_get(const Element&, ElementType); bool element_child_id_erase(Element&, ElementType, int); int track_frames_count_get(const Element&); + int animations_count_get(const Element&); float interpolation_factor(Interpolation, float); void frame_mix(Element&, const Element&, float); Element frame_generate(const Element&, float); @@ -542,5 +556,8 @@ namespace anm2ed bool animations_deserialize(const std::string&, int, std::set&, std::string* = nullptr, std::set* = nullptr); int animations_merge(int, std::set&, types::merge::Type = types::merge::APPEND, bool = true); + bool file_merge(const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); + bool regions_generate(const std::set&, const std::set&, const std::string&, RegionFrameMapping); + void regions_scan(); }; } diff --git a/src/anm2/internal.hpp b/src/anm2/internal.hpp index 4d6e151..6db7868 100644 --- a/src/anm2/internal.hpp +++ b/src/anm2/internal.hpp @@ -61,7 +61,6 @@ namespace anm2ed ElementType group_child_type_get(ElementType); Element* content_container_get(Element&, ElementType); std::unordered_map child_ids_compact(Element&, ElementType); - int animations_count_get(const Element&); int animations_child_index_get(const Element&, int); int animations_child_insert_index_get(const Element&, int); Element root_animation_make(); @@ -88,6 +87,35 @@ namespace anm2ed void special_interpolated_frames_bake(Element&, int, bool, bool); void all_interpolated_frames_bake(Element&, int, bool, bool); int color_write(float); + bool is_region_matched(const Element&, const Element&); + Element* region_match_get(Element&, const Element&); + + template void layer_frames_each(Element& root, Element& animation, Callback&& callback) + { + auto layers = content_container_get(root, ElementType::LAYERS); + auto spritesheets = content_container_get(root, ElementType::SPRITESHEETS); + auto tracks = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layers || !spritesheets || !tracks) return; + + tracks_each(*tracks, ElementType::LAYER_ANIMATION, + [&](Element& track) + { + auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, track.layerId); + auto spritesheet = + layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (!spritesheet) return; + for (auto& frame : track.children) + if (frame.type == ElementType::FRAME) callback(frame, *spritesheet); + }); + } + + template void layer_frames_each(Element& root, Callback&& callback) + { + if (auto animations = element_first_get(root, ElementType::ANIMATIONS)) + for (auto& animation : animations->children) + if (animation.type == ElementType::ANIMATION) layer_frames_each(root, animation, callback); + } + std::uint64_t anm2_hash_get(const Element&, Options); std::uint64_t element_hash(const Element&, Flags); } diff --git a/src/anm2/merge.cpp b/src/anm2/merge.cpp index 40bba96..9bc187e 100644 --- a/src/anm2/merge.cpp +++ b/src/anm2/merge.cpp @@ -104,7 +104,8 @@ namespace anm2ed [&](const Element& child) { return child.type == ElementType::GROUP && - child.name == sourceGroup.name && !matchedGroupIds.contains(child.id); + child.name == sourceGroup.name && + !matchedGroupIds.contains(child.id); }); if (destinationGroup == destinationTracks->children.end()) @@ -182,4 +183,228 @@ namespace anm2ed finalAnimation->frameNum = animation_length_get(*finalAnimation); return finalIndex; } + + bool Anm2::file_merge(const std::filesystem::path& path, const std::filesystem::path& directory, + FileMergePreset preset) + { + Anm2 source(path); + if (!source.isValid) return false; + + auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; + std::map> remaps{}; + + auto path_remap = [&](const std::filesystem::path& original) + { + if (directory.empty() || original.empty()) return original; + std::error_code ec{}; + auto absolute = + original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec); + if (ec) absolute = path.parent_path() / original; + auto relative = std::filesystem::relative(absolute, directory, ec); + return ec ? original : relative; + }; + + auto id_remap = [&](ElementType type, int id) + { + auto it = remaps[type].find(id); + return it == remaps[type].end() ? -1 : it->second; + }; + + auto name_find = [](Element& container, ElementType type, const std::string& name) + { return child_find(container, [&](const Element& child) { return child.type == type && child.name == name; }); }; + + auto name_unique_get = [&](Element& container, ElementType type, const std::string& name) + { + auto candidate = name; + for (int i = 2; name_find(container, type, candidate); ++i) + candidate = std::format("{} {}", name, i); + return candidate; + }; + + auto named_element_merge = [&](Element& container, Element item) + { + auto existing = isAppendAsNew ? nullptr : name_find(container, item.type, item.name); + if (existing) + { + item.id = existing->id; + *existing = item; + return item.id; + } + item.id = element_child_next_id_get(container, item.type); + if (isAppendAsNew) item.name = name_unique_get(container, item.type, item.name); + container.children.push_back(item); + return item.id; + }; + + auto spritesheet_import = [&](int sourceId) + { + auto& remap = remaps[ElementType::SPRITESHEET]; + if (remap.contains(sourceId)) return remap[sourceId]; + auto spritesheet = source.element_get(ElementType::SPRITESHEET, sourceId); + auto destination = element_get(ElementType::SPRITESHEETS); + if (sourceId < 0 || !spritesheet || !destination) return -1; + + auto imported = *spritesheet; + imported.id = element_child_next_id_get(*destination, ElementType::SPRITESHEET); + imported.path = path_remap(imported.path); + destination->children.push_back(imported); + return remap[sourceId] = imported.id; + }; + + auto sourceSounds = source.element_get(ElementType::SOUNDS); + auto destinationSounds = element_get(ElementType::SOUNDS); + if (sourceSounds && destinationSounds) + for (auto sound : sourceSounds->children) + { + if (sound.type != ElementType::SOUND_ELEMENT) continue; + auto sourceId = sound.id; + sound.path = path_remap(sound.path); + auto existing = isAppendAsNew ? nullptr + : child_find(*destinationSounds, [&](const Element& child) + { return child.type == sound.type && child.path == sound.path; }); + sound.id = existing ? existing->id : element_child_next_id_get(*destinationSounds, sound.type); + if (existing) + *existing = sound; + else + destinationSounds->children.push_back(sound); + remaps[sound.type][sourceId] = sound.id; + } + + for (auto type : {ElementType::LAYER_ELEMENT, ElementType::NULL_ELEMENT, ElementType::EVENT_ELEMENT}) + { + auto sourceContainer = source.element_get(ELEMENT_CONTAINERS[(int)type]); + auto destinationContainer = element_get(ELEMENT_CONTAINERS[(int)type]); + if (!sourceContainer || !destinationContainer) continue; + for (auto item : sourceContainer->children) + { + if (item.type != type) continue; + if (type == ElementType::LAYER_ELEMENT) + { + auto existing = isAppendAsNew ? nullptr : name_find(*destinationContainer, type, item.name); + item.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(item.spritesheetId); + } + remaps[type][item.id] = named_element_merge(*destinationContainer, item); + } + } + + auto item_remap = [&](Element& item) + { + for (auto& frame : item.children) + { + if (frame.type != ElementType::FRAME && frame.type != ElementType::TRIGGER) continue; + for (auto& soundId : frame.soundIds) + soundId = id_remap(ElementType::SOUND_ELEMENT, soundId); + frame.eventId = id_remap(ElementType::EVENT_ELEMENT, frame.eventId); + } + }; + + auto animation_build = [&](const Element& incoming) + { + auto animation = element_make(ElementType::ANIMATION); + animation.name = incoming.name; + animation.frameNum = incoming.frameNum; + animation.isLoop = incoming.isLoop; + + auto single_track_build = [&](ElementType type) + { + if (auto track = child_first_get(incoming, type)) item_remap(animation.children.emplace_back(*track)); + }; + + single_track_build(ElementType::ROOT_ANIMATION); + for (const auto& row : TRACK_CONTAINERS) + { + auto sourceTracks = child_first_get(incoming, row.container); + if (!sourceTracks) continue; + auto container = element_make(row.container); + for (auto item : sourceTracks->children) + { + if (item.type == ElementType::GROUP) + { + std::erase_if(item.children, + [](const Element& child) { return child.type != ElementType::ROOT_ANIMATION; }); + if (item.children.empty()) item.children.push_back(root_animation_make()); + if (item.id == -1) item.id = element_child_next_id_get(container, ElementType::GROUP); + container.children.push_back(item); + continue; + } + if (item.type != row.track) continue; + item.*(row.id) = id_remap(row.element, item.*(row.id)); + if (item.*(row.id) < 0) continue; + item_remap(item); + container.children.push_back(item); + } + animation.children.push_back(container); + } + single_track_build(ElementType::TRIGGERS); + return animation; + }; + + auto sourceAnimations = source.element_get(ElementType::ANIMATIONS); + auto destinationAnimations = element_get(ElementType::ANIMATIONS); + if (!sourceAnimations || !destinationAnimations) return true; + + std::string defaultAnimationName{}; + for (const auto& incoming : sourceAnimations->children) + { + if (incoming.type != ElementType::ANIMATION) continue; + auto processed = animation_build(incoming); + auto destination = name_find(*destinationAnimations, ElementType::ANIMATION, processed.name); + if (isAppendAsNew) + processed.name = name_unique_get(*destinationAnimations, ElementType::ANIMATION, processed.name); + if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; + + if (!destination || isAppendAsNew) + { + destinationAnimations->children.push_back(processed); + continue; + } + + if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING) + { + *destination = processed; + continue; + } + + destination->isLoop = processed.isLoop; + for (auto type : {ElementType::ROOT_ANIMATION, ElementType::TRIGGERS}) + if (auto track = child_first_get(processed, type); track && !track->children.empty()) + child_ensure(*destination, type) = *track; + + for (const auto& row : TRACK_CONTAINERS) + { + auto sourceTracks = child_first_get(processed, row.container); + if (!sourceTracks) continue; + auto& destinationTracks = child_ensure(*destination, row.container); + + std::unordered_map groupRemap{}; + for (auto item : sourceTracks->children) + { + if (item.type != ElementType::GROUP) continue; + auto sourceGroupId = item.id; + item.id = element_child_next_id_get(destinationTracks, ElementType::GROUP); + destinationTracks.children.push_back(item); + groupRemap[sourceGroupId] = item.id; + } + + for (auto item : sourceTracks->children) + { + if (item.type != row.track) continue; + if (item.groupId != -1) item.groupId = groupRemap.contains(item.groupId) ? groupRemap[item.groupId] : -1; + if (auto existing = track_find(destinationTracks, row.track, track_id_get(item))) + { + if (!item.children.empty()) *existing = item; + } + else + destinationTracks.children.push_back(item); + } + } + + destination->frameNum = std::max({destination->frameNum, processed.frameNum, animation_length_get(*destination)}); + } + + if (destinationAnimations->defaultAnimation.empty() && !sourceAnimations->defaultAnimation.empty()) + destinationAnimations->defaultAnimation = + defaultAnimationName.empty() ? sourceAnimations->defaultAnimation : defaultAnimationName; + return true; + } } diff --git a/src/anm2/normalize.cpp b/src/anm2/normalize.cpp index eea7815..0d755b4 100644 --- a/src/anm2/normalize.cpp +++ b/src/anm2/normalize.cpp @@ -15,25 +15,6 @@ namespace anm2ed }); } - template void layer_frames_each(Element& root, Callback&& callback) - { - auto layers = content_container_get(root, ElementType::LAYERS); - auto spritesheets = content_container_get(root, ElementType::SPRITESHEETS); - if (!layers || !spritesheets) return; - - animations_tracks_each(root, ElementType::LAYER_ANIMATION, - [&](Element& track) - { - auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, track.layerId); - auto spritesheet = layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, - layer->spritesheetId) - : nullptr; - if (!spritesheet) return; - for (auto& frame : track.children) - if (frame.type == ElementType::FRAME) callback(frame, *spritesheet); - }); - } - void shader_ids_repair(Element& root) { auto shaders = content_container_get(root, ElementType::SHADERS); @@ -69,21 +50,13 @@ namespace anm2ed void region_frame_ids_repair(Element& root) { layer_frames_each(root, - [](Element& frame, const Element& spritesheet) + [](Element& frame, Element& spritesheet) { - auto is_region_match = [&](const Element& region) - { - return region.type == ElementType::REGION && - glm::ivec2(region.crop) == glm::ivec2(frame.crop) && - glm::ivec2(region.size) == glm::ivec2(frame.size) && - glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); - }; - auto region = frame.regionId == -1 ? nullptr : child_id_get(spritesheet, ElementType::REGION, frame.regionId); - if (region && is_region_match(*region)) return; - if (auto candidate = child_find(spritesheet, is_region_match)) frame.regionId = candidate->id; + if (region && is_region_matched(*region, frame)) return; + if (auto match = region_match_get(spritesheet, frame)) frame.regionId = match->id; }); } diff --git a/src/anm2/regions.cpp b/src/anm2/regions.cpp new file mode 100644 index 0000000..26638fe --- /dev/null +++ b/src/anm2/regions.cpp @@ -0,0 +1,82 @@ +#include "internal.hpp" + +namespace anm2ed +{ + std::string region_name_get(const std::string& format, int number) + { + try + { + return std::vformat(format, std::make_format_args(number)); + } + catch (const std::format_error&) + { + return format; + } + } + + bool is_region_matched(const Element& region, const Element& frame) + { + return region.type == ElementType::REGION && glm::ivec2(region.crop) == glm::ivec2(frame.crop) && + glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); + } + + Element* region_match_get(Element& spritesheet, const Element& frame) + { + return child_find(spritesheet, [&](const Element& region) { return is_region_matched(region, frame); }); + } + + bool Anm2::regions_generate(const std::set& animationIndices, const std::set& frameReferences, + const std::string& format, RegionFrameMapping mapping) + { + std::vector> frames{}; + for (auto animationIndex : animationIndices) + if (auto animation = element_get(ElementType::ANIMATION, animationIndex)) + layer_frames_each(root, *animation, + [&](Element& frame, Element& spritesheet) { frames.emplace_back(&frame, &spritesheet); }); + + for (auto frameReference : frameReferences) + { + if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) continue; + auto frame = element_get(frameReference); + auto layer = element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); + auto spritesheet = layer ? element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (frame && frame->type == ElementType::FRAME && frame->regionId == -1 && spritesheet) + frames.emplace_back(frame, spritesheet); + } + + std::unordered_map regionNumbers{}; + bool isChanged{}; + for (auto [frame, spritesheet] : frames) + { + auto region = region_match_get(*spritesheet, *frame); + if (!region) + { + auto id = element_child_next_id_get(*spritesheet, ElementType::REGION); + region = &spritesheet->children.emplace_back(element_make(ElementType::REGION)); + region->id = id; + region->name = region_name_get(format, ++regionNumbers[spritesheet->id]); + region->crop = frame->crop; + region->size = frame->size; + region->pivot = frame->pivot; + isChanged = true; + } + if (mapping == RegionFrameMapping::SET && frame->regionId != region->id) + { + frame->regionId = region->id; + isChanged = true; + } + } + + return isChanged; + } + + void Anm2::regions_scan() + { + layer_frames_each(root, + [](Element& frame, Element& spritesheet) + { + if (frame.regionId != -1) return; + if (auto region = region_match_get(spritesheet, frame)) frame.regionId = region->id; + }); + } +} diff --git a/src/dialog.cpp b/src/dialog.cpp index 542d868..e5013e4 100644 --- a/src/dialog.cpp +++ b/src/dialog.cpp @@ -85,8 +85,7 @@ namespace anm2ed auto pathUtf8 = path::to_utf8(path); system(std::format("xdg-open \"{}\" &", pathUtf8).c_str()); #else - toasts.push(localize.get(TOAST_NOT_SUPPORTED)); - logger.warning(localize.get(TOAST_NOT_SUPPORTED, anm2ed::ENGLISH)); + toast_log(Level::WARNING, TOAST_NOT_SUPPORTED); #endif } diff --git a/src/document.cpp b/src/document.cpp index 33d2d08..7c01fe3 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -1,23 +1,21 @@ #include "document.hpp" #include -#include #include +#include #include #include #include #include -#include #include #include #include #include -#include - #include "file.hpp" #include "log.hpp" #include "manager.hpp" +#include "pack.hpp" #include "path.hpp" #include "strings.hpp" #include "toast.hpp" @@ -30,47 +28,15 @@ using namespace glm; namespace anm2ed::document { + constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; + constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; + uint64_t document_tab_id_next() { static uint64_t next{1}; return next++; } - ItemType item_type_get(int type) { return static_cast(type); } - - int animation_count_get(const Anm2& data) - { - int count{}; - if (auto animations = data.element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) ++count; - return count; - } - - std::string region_name_get(const std::string& format, int number) - { - try - { - return std::vformat(format, std::make_format_args(number)); - } - catch (const std::format_error&) - { - return format; - } - } - - const Element* shader_element_get(const Anm2& anm2, int id) - { - auto shaders = anm2.element_get(ElementType::SHADERS); - return shaders ? child_id_get(*shaders, ElementType::SHADER, id) : nullptr; - } - - Element* shader_element_get(Anm2& anm2, int id) - { - auto shaders = anm2.element_get(ElementType::SHADERS); - return shaders ? child_id_get(*shaders, ElementType::SHADER, id) : nullptr; - } - std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) { auto loadPath = path::backslash_handle(path); @@ -101,31 +67,33 @@ namespace anm2ed::document { auto end = source.find('\n', position); auto isEnd = end == std::string_view::npos; - auto line = source.substr(position, isEnd ? std::string_view::npos : end - position); - output += std::format("{:4}: {}\n", lineNumber++, line); + output += std::format("{:4}: {}\n", lineNumber++, + source.substr(position, isEnd ? std::string_view::npos : end - position)); if (isEnd) break; position = end + 1; } return output; } + void shader_status_format_append(std::string* status, StringType format, StringType argument) + { + if (!status) return; + auto argumentString = std::string(localize.get(argument)); + *status += std::vformat(localize.get(format), std::make_format_args(argumentString)) + "\n"; + } + bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, StringType label, std::string* status, const char* fallback = nullptr) { + if (shaderPath.empty() && !fallback) + { + shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, label); + return false; + } if (shaderPath.empty()) { - if (fallback) - { - source = fallback; - return true; - } - - if (status) - { - auto labelString = std::string(localize.get(label)); - *status += std::vformat(localize.get(LABEL_SHADER_PATH_EMPTY), std::make_format_args(labelString)) + "\n"; - } - return false; + source = fallback; + return true; } auto absolute = path::case_insensitive_find(shader_absolute_path_get(document, shaderPath)); @@ -139,319 +107,150 @@ namespace anm2ed::document return false; } - void shader_uniform_configs_apply(const Element& shaderElement, resource::Shader& shader) - { - for (auto& uniform : shader.uniforms) - { - auto config = shader_uniform_get(shaderElement, uniform.name); - if (!config) continue; - - if (!config->binding.empty()) - { - auto binding = resource::shader::uniform_binding_get(config->binding); - if (resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) uniform.binding = binding; - } - if (!config->value.empty()) resource::shader::uniform_value_parse(uniform, config->value); - for (int index = 0; index < (int)uniform.components.size(); ++index) - { - auto component = shader_uniform_component_get(*config, index); - if (!component) continue; - - if (!component->binding.empty()) - { - auto binding = resource::shader::uniform_binding_get(component->binding); - if (binding == resource::shader::UNIFORM_BINDING_MANUAL || - binding == resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) - uniform.components[index].binding = binding; - } - if (!component->value.empty()) - { - std::stringstream stream{component->value}; - stream >> uniform.components[index].value; - } - } - } - } - - bool shader_uniform_configs_trim(Element& shaderElement, const resource::Shader& shader) - { - auto component_count_get = [](resource::shader::UniformValueType type) - { - if (type == resource::shader::UNIFORM_VALUE_VEC2) return 2; - if (type == resource::shader::UNIFORM_VALUE_VEC3) return 3; - if (type == resource::shader::UNIFORM_VALUE_VEC4) return 4; - return 0; - }; - - bool isChanged{}; - for (auto it = shaderElement.children.begin(); it != shaderElement.children.end();) - { - if (it->type != ElementType::UNIFORM) - { - ++it; - continue; - } - - auto uniform = std::find_if(shader.uniforms.begin(), shader.uniforms.end(), - [&](const resource::shader::Uniform& uniform) { return uniform.name == it->name; }); - if (uniform == shader.uniforms.end()) - { - it = shaderElement.children.erase(it); - isChanged = true; - continue; - } - - if (!it->binding.empty()) - { - auto binding = resource::shader::uniform_binding_get(it->binding); - if (!resource::shader::is_uniform_binding_valid(binding, uniform->valueType)) - { - it->binding.clear(); - isChanged = true; - } - } - - auto componentCount = component_count_get(uniform->valueType); - auto isComponents = - resource::shader::uniform_binding_get(it->binding) == resource::shader::UNIFORM_BINDING_COMPONENTS; - auto removed = std::erase_if(it->children, - [&](const Element& component) - { - if (component.type != ElementType::COMPONENT) return false; - if (!isComponents) return true; - return component.index < 0 || component.index >= componentCount; - }); - if (removed > 0) isChanged = true; - - for (auto& component : it->children) - { - if (component.type != ElementType::COMPONENT || component.binding.empty()) continue; - auto binding = resource::shader::uniform_binding_get(component.binding); - if (binding == resource::shader::UNIFORM_BINDING_MANUAL || - binding == resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) - continue; - component.binding.clear(); - isChanged = true; - } - - ++it; - } - - return isChanged; - } - - Element* frame_region_match_get(Element& spritesheet, const Element& frame) - { - auto frameCrop = glm::ivec2(frame.crop); - auto frameSize = glm::ivec2(frame.size); - auto framePivot = glm::ivec2(frame.pivot); - for (auto& region : spritesheet.children) - if (region.type == ElementType::REGION && glm::ivec2(region.crop) == frameCrop && - glm::ivec2(region.size) == frameSize && glm::ivec2(region.pivot) == framePivot) - return ®ion; - return nullptr; - } - - int frame_count_get(const Element& item) - { - auto frameType = item.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME; - int count{}; - for (auto& frame : item.children) - if (frame.type == frameType) ++count; - return count; - } - - std::vector animation_labels_get(const Anm2& data) - { - std::vector labels{"None"}; - if (auto animations = data.element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - if (animation.type == ElementType::ANIMATION) labels.emplace_back(animation.name); - return labels; - } - - std::vector element_name_labels_get(const Element* container, ElementType type, bool isNone) + template + void storage_labels_set(Storage& storage, const Element* container, ElementType type, bool isNone, Label&& label_get) { std::vector labels{}; - if (isNone) labels.emplace_back(localize.get(BASIC_NONE)); - if (!container) return labels; - for (auto& element : container->children) - if (element.type == type) labels.emplace_back(element.name); - return labels; - } - - std::vector element_ids_get(const Element* container, ElementType type, bool isNone) - { std::vector ids{}; - if (isNone) ids.emplace_back(-1); - if (!container) return ids; - for (auto& element : container->children) - if (element.type == type) ids.emplace_back(element.id); - return ids; - } - - std::vector spritesheet_labels_get(const Anm2& data) - { - std::vector labels{}; - if (auto spritesheets = data.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) + if (isNone) + { + labels.emplace_back(localize.get(BASIC_NONE)); + ids.emplace_back(-1); + } + if (container) + for (auto& element : container->children) + if (element.type == type) { - auto pathString = path::to_utf8(spritesheet.path); - labels.emplace_back( - std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(spritesheet.id, pathString))); + labels.emplace_back(label_get(element)); + ids.emplace_back(element.id); } - return labels; + storage.labels_set(std::move(labels), std::move(ids)); } - std::vector spritesheet_ids_get(const Anm2& data) + std::string element_name_get(const Element& element) { return element.name; } + + template + void resource_load(int id, const std::filesystem::path& path, std::map& resources, + std::unordered_map& paths) { - std::vector ids{}; - if (auto spritesheets = data.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) ids.emplace_back(spritesheet.id); - return ids; + resources[id] = Resource(path::case_insensitive_find(path)); + paths[id] = path; } - std::vector sound_labels_get(const Anm2& data) + template + void resources_sync(Document& document, ElementType type, std::map& resources, + std::unordered_map& paths) { - std::vector labels{localize.get(BASIC_NONE)}; - if (auto sounds = data.element_get(ElementType::SOUNDS)) - for (auto& sound : sounds->children) - if (sound.type == ElementType::SOUND_ELEMENT) - { - auto pathString = path::to_utf8(sound.path); - labels.emplace_back(std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(sound.id, pathString))); - } - return labels; - } + std::set validIds{}; + util::WorkingDirectory workingDirectory(document.directory_get()); + if (auto container = document.anm2.element_get(ELEMENT_CONTAINERS[(int)type])) + for (auto& element : container->children) + { + if (element.type != type) continue; + validIds.insert(element.id); + auto path = paths.find(element.id); + if (!resources.contains(element.id) || path == paths.end() || path->second != element.path) + resource_load(element.id, element.path, resources, paths); + } - std::vector sound_ids_get(const Anm2& data) - { - std::vector ids{-1}; - if (auto sounds = data.element_get(ElementType::SOUNDS)) - for (auto& sound : sounds->children) - if (sound.type == ElementType::SOUND_ELEMENT) ids.emplace_back(sound.id); - return ids; + std::erase_if(resources, [&](const auto& pair) { return !validIds.contains(pair.first); }); + std::erase_if(paths, [&](const auto& pair) { return !validIds.contains(pair.first); }); } uint64_t spritesheet_hash_get(const Element& spritesheet, const resource::Texture* texture) { - auto hash_combine = [](std::size_t& seed, std::size_t value) - { seed ^= value + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2); }; - std::size_t seed{}; - hash_combine(seed, std::hash{}(texture ? texture->size.x : 0)); - hash_combine(seed, std::hash{}(texture ? texture->size.y : 0)); - hash_combine(seed, std::hash{}(texture ? texture->channels : 0)); - hash_combine(seed, std::hash{}(texture ? texture->filter : 0)); - hash_combine(seed, std::hash{}(path::to_utf8(spritesheet.path))); - - if (texture && !texture->pixels.empty()) - { - std::string_view bytes(reinterpret_cast(texture->pixels.data()), texture->pixels.size()); - hash_combine(seed, std::hash{}(bytes)); - } - else - hash_combine(seed, 0); + auto hash_combine = [&](std::size_t value) { seed ^= value + HASH_COMBINE_CONSTANT + (seed << 6) + (seed >> 2); }; + hash_combine(std::hash{}(texture ? texture->size.x : 0)); + hash_combine(std::hash{}(texture ? texture->size.y : 0)); + hash_combine(std::hash{}(texture ? texture->channels : 0)); + hash_combine(std::hash{}(texture ? texture->filter : 0)); + hash_combine(std::hash{}(path::to_utf8(spritesheet.path))); + auto isPixels = texture && !texture->pixels.empty(); + hash_combine(isPixels ? std::hash{}(std::string_view( + reinterpret_cast(texture->pixels.data()), texture->pixels.size())) + : 0); return static_cast(seed); } + bool is_reference_item_matched(const Reference& left, const Reference& right) + { + return left.animationIndex == right.animationIndex && left.itemType == right.itemType && + left.itemID == right.itemID && left.groupType == right.groupType && left.groupId == right.groupId; + } + + Reference item_reference_get(Reference reference) + { + reference.frameIndex = -1; + return reference; + } + + auto frame_reference_validator_make(const Anm2& anm2) + { + return [&anm2, frameCounts = std::map{}](const Reference& frameReference) mutable + { + if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; + auto itemReference = item_reference_get(frameReference); + if (!frameCounts.contains(itemReference)) + { + auto item = anm2.element_get(itemReference); + frameCounts[itemReference] = item ? track_frames_count_get(*item) : 0; + } + return frameReference.frameIndex < frameCounts[itemReference]; + }; + } + void restored_snapshot_sanitize(Document& document) { auto& reference = document.reference; auto& selection = document.frames.selection; auto& frameReferences = document.frames.references; - auto& itemReferences = document.items.references; auto& groupReferences = document.groupReferences; + auto& anm2 = document.anm2; - auto animationCount = animation_count_get(document.anm2); - if (animationCount <= 0) - { - reference = {}; - selection.clear(); - frameReferences.clear(); - itemReferences.clear(); - groupReferences.clear(); - document.frameTime = 0.0f; - return; - } - - if (reference.animationIndex < 0 || reference.animationIndex >= animationCount) - reference.animationIndex = std::clamp(reference.animationIndex, 0, animationCount - 1); - - auto referenceItem = reference; - referenceItem.frameIndex = -1; - auto item = document.anm2.element_get(referenceItem); - if (!item) - { - reference.itemType = (int)ItemType::ROOT; - reference.itemID = -1; - reference.groupType = (int)ItemType::NONE; - reference.groupId = -1; - referenceItem = reference; - referenceItem.frameIndex = -1; - item = document.anm2.element_get(referenceItem); - } - - if (!item) + auto selection_clear = [&]() { reference.frameIndex = -1; selection.clear(); frameReferences.clear(); groupReferences.clear(); document.frameTime = 0.0f; + }; + + auto animations = anm2.element_get(ElementType::ANIMATIONS); + auto animationCount = animations ? animations_count_get(*animations) : 0; + if (animationCount <= 0) + { + reference = {}; + selection_clear(); + document.items.references.clear(); return; } - for (auto it = itemReferences.begin(); it != itemReferences.end();) + reference.animationIndex = std::clamp(reference.animationIndex, 0, animationCount - 1); + auto item = anm2.element_get(item_reference_get(reference)); + if (!item) { - auto itemReference = *it; - itemReference.frameIndex = -1; - auto item = document.anm2.element_get(itemReference); - if (!item) - it = itemReferences.erase(it); - else - ++it; + reference = {reference.animationIndex, ROOT, -1, reference.frameIndex}; + item = anm2.element_get(item_reference_get(reference)); } + if (!item) return selection_clear(); - for (auto it = groupReferences.begin(); it != groupReferences.end();) - { - auto animation = document.anm2.element_get(ElementType::ANIMATION, it->animationIndex); - Element* container{}; - if (animation && it->itemType == LAYER) - container = child_first_get(*animation, ElementType::LAYER_ANIMATIONS); - else if (animation && it->itemType == NULL_) - container = child_first_get(*animation, ElementType::NULL_ANIMATIONS); - auto group = container ? child_id_get(*container, ElementType::GROUP, it->itemID) : nullptr; - if (!group) - it = groupReferences.erase(it); - else - ++it; - } - - for (auto it = frameReferences.begin(); it != frameReferences.end();) - { - auto itemReference = *it; - itemReference.frameIndex = -1; - auto item = document.anm2.element_get(itemReference); - auto frameCount = item ? frame_count_get(*item) : 0; - if (!item || it->frameIndex < 0 || it->frameIndex >= frameCount) - it = frameReferences.erase(it); - else - ++it; - } - - auto frameCount = frame_count_get(*item); - for (auto it = selection.begin(); it != selection.end();) - { - if (*it < 0 || *it >= frameCount) - it = selection.erase(it); - else - ++it; - } + std::erase_if(document.items.references, + [&](const Reference& itemReference) { return !anm2.element_get(item_reference_get(itemReference)); }); + std::erase_if(groupReferences, + [&](const Reference& groupReference) + { + auto animation = anm2.element_get(ElementType::ANIMATION, groupReference.animationIndex); + return !animation || + !animation_group_get(*animation, groupReference.itemType, groupReference.itemID); + }); + std::erase_if(frameReferences, [isValid = frame_reference_validator_make(anm2)]( + const Reference& frameReference) mutable { return !isValid(frameReference); }); + auto frameCount = track_frames_count_get(*item); + std::erase_if(selection, [&](int frameIndex) { return frameIndex < 0 || frameIndex >= frameCount; }); if (frameCount <= 0) { reference.frameIndex = -1; @@ -474,10 +273,7 @@ namespace anm2ed::document selection.clear(); for (const auto& frameReference : frameReferences) - if (frameReference.animationIndex == reference.animationIndex && frameReference.itemType == reference.itemType && - frameReference.itemID == reference.itemID && frameReference.groupType == reference.groupType && - frameReference.groupId == reference.groupId) - selection.insert(frameReference.frameIndex); + if (is_reference_item_matched(frameReference, reference)) selection.insert(frameReference.frameIndex); document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); } @@ -488,26 +284,12 @@ namespace anm2ed Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) { tabId = document::document_tab_id_next(); - - if (isNew) + if (!isNew) anm2 = Anm2(path, errorString); + if (isNew ? !save(path, errorString) : !anm2.isValid) { - anm2 = Anm2(); - if (!save(path, errorString)) - { - isValid = false; - this->path.clear(); - return; - } - } - else - { - anm2 = Anm2(path, errorString); - if (!anm2.isValid) - { - isValid = false; - this->path.clear(); - return; - } + isValid = false; + this->path.clear(); + return; } this->path = path; @@ -516,28 +298,7 @@ namespace anm2ed change(Document::ALL); } - Document::Document(Document&& other) noexcept - : path(std::move(other.path)), tabId(other.tabId), snapshots(std::move(other.snapshots)), - current(snapshots.current), playback(current.playback), animation(current.animation), event(current.event), - frames(current.frames), items(current.items), layer(current.layer), merge(current.merge), null(current.null), - region(current.region), shader(current.shader), sound(current.sound), spritesheet(current.spritesheet), - textures(current.textures), sounds(current.sounds), anm2(current.anm2), reference(current.reference), - groupReferences(current.groupReferences), frameTime(current.frameTime), message(current.message), - regionBySpritesheet(std::move(other.regionBySpritesheet)), - changeAllFramePropertiesRegionId(other.changeAllFramePropertiesRegionId), - changeAllFramePropertiesShaderId(other.changeAllFramePropertiesShaderId), previewZoom(other.previewZoom), - previewPan(other.previewPan), editorPan(other.editorPan), editorZoom(other.editorZoom), - overlayIndex(other.overlayIndex), overlayDocumentId(other.overlayDocumentId), hash(other.hash), - saveHash(other.saveHash), autosaveHash(other.autosaveHash), lastAutosaveTime(other.lastAutosaveTime), - isValid(other.isValid), isOpen(other.isOpen), isForceDirty(other.isForceDirty), - spritesheetHashes(std::move(other.spritesheetHashes)), - spritesheetSaveHashes(std::move(other.spritesheetSaveHashes)), texturePaths(std::move(other.texturePaths)), - soundPaths(std::move(other.soundPaths)), shaderVertexPaths(std::move(other.shaderVertexPaths)), - shaderFragmentPaths(std::move(other.shaderFragmentPaths)), shaders(std::move(other.shaders)), - isAnimationPreviewSet(other.isAnimationPreviewSet), isSpritesheetEditorSet(other.isSpritesheetEditorSet), - editTarget(other.editTarget) - { - } + Document::Document(Document&& other) noexcept : DocumentData(std::move(other)), editTarget(other.editTarget) {} Document& Document::operator=(Document&& other) noexcept { @@ -553,40 +314,27 @@ namespace anm2ed if (anm2.save(absolutePath, errorString, options)) { this->path = absolutePath; - toasts.push(std::vformat(localize.get(TOAST_SAVE_DOCUMENT), std::make_format_args(absolutePathUtf8))); - logger.info( - std::vformat(localize.get(TOAST_SAVE_DOCUMENT, anm2ed::ENGLISH), std::make_format_args(absolutePathUtf8))); + toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); clean(); return true; } - else if (errorString) - { - toasts.push(std::vformat(localize.get(TOAST_SAVE_DOCUMENT_FAILED), - std::make_format_args(absolutePathUtf8, *errorString))); - logger.error(std::vformat(localize.get(TOAST_SAVE_DOCUMENT_FAILED, anm2ed::ENGLISH), - std::make_format_args(absolutePathUtf8, *errorString))); - } - + if (errorString) toast_log(Level::ERROR, TOAST_SAVE_DOCUMENT_FAILED, absolutePathUtf8, *errorString); return false; } std::filesystem::path Document::autosave_path_get() { - auto fileNameUtf8 = path::to_utf8(filename_get()); - auto autosaveNameUtf8 = "." + fileNameUtf8 + ".autosave"; - return directory_get() / path::from_utf8(autosaveNameUtf8); + return directory_get() / + path::from_utf8("." + path::to_utf8(filename_get()) + std::string(document::AUTOSAVE_EXTENSION)); } std::filesystem::path Document::path_from_autosave_get(const std::filesystem::path& path) { auto fileName = path::to_utf8(path.filename()); - if (!fileName.empty() && fileName.front() == '.') fileName.erase(fileName.begin()); - constexpr std::string_view autosaveExtension = ".autosave"; - if (fileName.ends_with(autosaveExtension)) fileName.erase(fileName.size() - autosaveExtension.size()); - - auto restorePath = path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); - - return restorePath; + if (fileName.starts_with('.')) fileName.erase(fileName.begin()); + if (fileName.ends_with(document::AUTOSAVE_EXTENSION)) + fileName.erase(fileName.size() - document::AUTOSAVE_EXTENSION.size()); + return path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); } bool Document::autosave(std::string* errorString, Options options) @@ -597,39 +345,25 @@ namespace anm2ed { autosaveHash = hash; lastAutosaveTime = 0.0f; - toasts.push(localize.get(TOAST_AUTOSAVING)); - logger.info(localize.get(TOAST_AUTOSAVING, anm2ed::ENGLISH)); + toast_log(Level::INFO, TOAST_AUTOSAVING); logger.info(std::format("Autosaved document to: {}", autosavePathUtf8)); return true; } - else if (errorString) - { - toasts.push( - std::vformat(localize.get(TOAST_AUTOSAVE_FAILED), std::make_format_args(autosavePathUtf8, *errorString))); - logger.error(std::vformat(localize.get(TOAST_AUTOSAVE_FAILED, anm2ed::ENGLISH), - std::make_format_args(autosavePathUtf8, *errorString))); - } - + if (errorString) toast_log(Level::ERROR, TOAST_AUTOSAVE_FAILED, autosavePathUtf8, *errorString); return false; } - void Document::anm2_change(ChangeType type) { change(type); } - void Document::texture_change(int id) { - auto texture = texture_get(id); - if (!texture || !anm2.element_get(ElementType::SPRITESHEET, id)) return; - change(SPRITESHEETS); + if (texture_get(id) && anm2.element_get(ElementType::SPRITESHEET, id)) change(SPRITESHEETS); } bool Document::texture_reload(int id) { auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); if (!spritesheet) return false; - util::WorkingDirectory workingDirectory(directory_get()); - textures[id] = resource::Texture(path::case_insensitive_find(spritesheet->path)); - texturePaths[id] = spritesheet->path; + document::resource_load(id, spritesheet->path, textures, texturePaths); return true; } @@ -637,27 +371,26 @@ namespace anm2ed { auto sound = anm2.element_get(ElementType::SOUND_ELEMENT, id); if (!sound) return false; - util::WorkingDirectory workingDirectory(directory_get()); - sounds[id] = resource::Audio(path::case_insensitive_find(sound->path)); - soundPaths[id] = sound->path; + document::resource_load(id, sound->path, sounds, soundPaths); return true; } bool Document::shader_reload(int shaderId, std::string* status) { - auto shaderElement = document::shader_element_get(anm2, shaderId); - if (!shaderElement) + auto shader_erase = [&]() { - if (status) - { - auto labelString = std::string(localize.get(LABEL_FRAGMENT)); - *status += std::vformat(localize.get(LABEL_SHADER_PATH_EMPTY), std::make_format_args(labelString)) + "\n"; - } shaders.erase(shaderId); shaderVertexPaths.erase(shaderId); shaderFragmentPaths.erase(shaderId); return false; + }; + + auto shaderElement = anm2.element_get(ElementType::SHADER, shaderId); + if (!shaderElement) + { + document::shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); + return shader_erase(); } std::string vertexSource{}; @@ -666,13 +399,7 @@ namespace anm2ed resource::shader::TEXTURE_COMPATIBILITY_VERTEX); auto isFragmentLoaded = document::shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); - if (!isVertexLoaded || !isFragmentLoaded) - { - shaders.erase(shaderId); - shaderVertexPaths.erase(shaderId); - shaderFragmentPaths.erase(shaderId); - return false; - } + if (!isVertexLoaded || !isFragmentLoaded) return shader_erase(); auto vertex = resource::shader::gles_vertex_convert(vertexSource); auto fragment = resource::shader::gles_fragment_convert(fragmentSource); @@ -683,19 +410,13 @@ namespace anm2ed *status += document::shader_source_lines_get("Converted vertex shader", vertex); *status += document::shader_source_lines_get("Converted fragment shader", fragment); } - if (!result.isLinked || !result.id) - { - shaders.erase(shaderId); - shaderVertexPaths.erase(shaderId); - shaderFragmentPaths.erase(shaderId); - return false; - } + if (!result.isLinked || !result.id) return shader_erase(); resource::Shader runtime{}; runtime.id = result.id; runtime.uniforms = std::move(result.uniforms); - if (document::shader_uniform_configs_trim(*shaderElement, runtime)) hash_set(); - document::shader_uniform_configs_apply(*shaderElement, runtime); + if (resource::shader::uniform_configs_trim(*shaderElement, runtime.uniforms)) hash_set(); + resource::shader::uniform_configs_apply(*shaderElement, runtime.uniforms); shaders[shaderId] = std::move(runtime); shaderVertexPaths[shaderId] = shaderElement->vertex; shaderFragmentPaths[shaderId] = shaderElement->fragment; @@ -705,105 +426,37 @@ namespace anm2ed void Document::assets_sync(ChangeType type) { if (type == ALL || type == SPRITESHEETS || type == TEXTURES) - { - std::set validIds{}; - util::WorkingDirectory workingDirectory(directory_get()); - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - { - if (spritesheet.type != ElementType::SPRITESHEET) continue; - validIds.insert(spritesheet.id); - auto isReload = !textures.contains(spritesheet.id) || !texturePaths.contains(spritesheet.id) || - texturePaths.at(spritesheet.id) != spritesheet.path; - if (isReload) - { - textures[spritesheet.id] = resource::Texture(path::case_insensitive_find(spritesheet.path)); - texturePaths[spritesheet.id] = spritesheet.path; - } - } + document::resources_sync(*this, ElementType::SPRITESHEET, textures, texturePaths); + if (type == ALL || type == SOUNDS) document::resources_sync(*this, ElementType::SOUND_ELEMENT, sounds, soundPaths); + if (type != ALL && type != SHADERS) return; - for (auto it = textures.begin(); it != textures.end();) + std::set validShaderIds{}; + util::WorkingDirectory workingDirectory(directory_get()); + if (auto shaderElements = anm2.element_get(ElementType::SHADERS)) + for (auto& shaderElement : shaderElements->children) { - if (!validIds.contains(it->first)) + if (shaderElement.type != ElementType::SHADER) continue; + auto id = shaderElement.id; + validShaderIds.insert(id); + auto isReload = !shaders.contains(id) || !shaderVertexPaths.contains(id) || !shaderFragmentPaths.contains(id) || + shaderVertexPaths.at(id) != shaderElement.vertex || + shaderFragmentPaths.at(id) != shaderElement.fragment; + if (shaderElement.fragment.empty()) { - texturePaths.erase(it->first); - it = textures.erase(it); + shaders.erase(id); + shaderVertexPaths.erase(id); + shaderFragmentPaths.erase(id); } - else - ++it; + else if (isReload) + shader_reload(id); + else if (auto shader = shader_get(id)) + resource::shader::uniform_configs_apply(shaderElement, shader->uniforms); } - } - if (type == ALL || type == SHADERS) - { - std::set validShaderIds{}; - util::WorkingDirectory workingDirectory(directory_get()); - if (auto shaderItems = anm2.element_get(ElementType::SHADERS)) - for (auto& shaderElement : shaderItems->children) - { - if (shaderElement.type != ElementType::SHADER) continue; - - validShaderIds.insert(shaderElement.id); - if (shaderElement.fragment.empty()) - { - shaders.erase(shaderElement.id); - shaderVertexPaths.erase(shaderElement.id); - shaderFragmentPaths.erase(shaderElement.id); - continue; - } - - auto isShaderReload = !shaders.contains(shaderElement.id) || !shaderVertexPaths.contains(shaderElement.id) || - !shaderFragmentPaths.contains(shaderElement.id) || - shaderVertexPaths.at(shaderElement.id) != shaderElement.vertex || - shaderFragmentPaths.at(shaderElement.id) != shaderElement.fragment; - if (isShaderReload) - shader_reload(shaderElement.id); - else if (auto shader = shader_get(shaderElement.id)) - document::shader_uniform_configs_apply(shaderElement, *shader); - } - - for (auto it = shaders.begin(); it != shaders.end();) - { - if (!validShaderIds.contains(it->first)) - { - shaderVertexPaths.erase(it->first); - shaderFragmentPaths.erase(it->first); - it = shaders.erase(it); - } - else - ++it; - } - } - - if (type == ALL || type == SOUNDS) - { - std::set validIds{}; - util::WorkingDirectory workingDirectory(directory_get()); - if (auto soundItems = anm2.element_get(ElementType::SOUNDS)) - for (auto& sound : soundItems->children) - { - if (sound.type != ElementType::SOUND_ELEMENT) continue; - validIds.insert(sound.id); - auto isReload = - !sounds.contains(sound.id) || !soundPaths.contains(sound.id) || soundPaths.at(sound.id) != sound.path; - if (isReload) - { - sounds[sound.id] = resource::Audio(path::case_insensitive_find(sound.path)); - soundPaths[sound.id] = sound.path; - } - } - - for (auto it = sounds.begin(); it != sounds.end();) - { - if (!validIds.contains(it->first)) - { - soundPaths.erase(it->first); - it = sounds.erase(it); - } - else - ++it; - } - } + auto is_invalid = [&](const auto& pair) { return !validShaderIds.contains(pair.first); }; + std::erase_if(shaders, is_invalid); + std::erase_if(shaderVertexPaths, is_invalid); + std::erase_if(shaderFragmentPaths, is_invalid); } resource::Texture* Document::texture_get(int id) @@ -812,34 +465,14 @@ namespace anm2ed return it == textures.end() ? nullptr : &it->second; } - const resource::Texture* Document::texture_get(int id) const - { - auto it = textures.find(id); - return it == textures.end() ? nullptr : &it->second; - } - resource::Audio* Document::sound_get(int id) { auto it = sounds.find(id); return it == sounds.end() ? nullptr : &it->second; } - const resource::Audio* Document::sound_get(int id) const - { - auto it = sounds.find(id); - return it == sounds.end() ? nullptr : &it->second; - } - resource::Shader* Document::shader_get(int shaderId) { - if (shaderId == -1) return nullptr; - auto it = shaders.find(shaderId); - return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; - } - - const resource::Shader* Document::shader_get(int shaderId) const - { - if (shaderId == -1) return nullptr; auto it = shaders.find(shaderId); return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; } @@ -848,7 +481,7 @@ namespace anm2ed { auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); auto texture = texture_get(spritesheetId); - if (!spritesheet || !texture || !texture->is_valid() || texture->pixels.empty() || ids.empty()) return false; + if (!spritesheet || !texture || !texture->is_valid() || texture->pixels.empty()) return false; bool isChanged{}; for (auto id : ids) @@ -856,41 +489,28 @@ namespace anm2ed auto region = child_id_get(*spritesheet, ElementType::REGION, id); if (!region) continue; - auto minPoint = glm::ivec2(glm::min(region->crop, region->crop + region->size)); - auto maxPoint = glm::ivec2(glm::max(region->crop, region->crop + region->size)); - int minX = std::max(0, minPoint.x); - int minY = std::max(0, minPoint.y); - int maxX = std::min(texture->size.x, maxPoint.x); - int maxY = std::min(texture->size.y, maxPoint.y); - if (minX >= maxX || minY >= maxY) continue; + auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0)); + auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), texture->size); + auto contentMin = glm::ivec2(std::numeric_limits::max()); + auto contentMax = glm::ivec2(std::numeric_limits::min()); - int contentMinX = std::numeric_limits::max(); - int contentMinY = std::numeric_limits::max(); - int contentMaxX = std::numeric_limits::min(); - int contentMaxY = std::numeric_limits::min(); - - for (int y = minY; y < maxY; ++y) - { - for (int x = minX; x < maxX; ++x) + for (int y = minPoint.y; y < maxPoint.y; ++y) + for (int x = minPoint.x; x < maxPoint.x; ++x) { auto index = ((std::size_t)y * texture->size.x + x) * resource::texture::CHANNELS; if (index + resource::texture::CHANNELS > texture->pixels.size()) continue; - auto r = texture->pixels[index + 0]; - auto g = texture->pixels[index + 1]; - auto b = texture->pixels[index + 2]; - auto a = texture->pixels[index + 3]; - if (r == 0 && g == 0 && b == 0 && a == 0) continue; - contentMinX = std::min(contentMinX, x); - contentMinY = std::min(contentMinY, y); - contentMaxX = std::max(contentMaxX, x); - contentMaxY = std::max(contentMaxY, y); + if (std::all_of(texture->pixels.begin() + index, + texture->pixels.begin() + index + resource::texture::CHANNELS, + [](auto channel) { return channel == 0; })) + continue; + contentMin = glm::min(contentMin, glm::ivec2(x, y)); + contentMax = glm::max(contentMax, glm::ivec2(x, y)); } - } - if (contentMinX == std::numeric_limits::max()) continue; + if (contentMin.x == std::numeric_limits::max()) continue; - auto newCrop = glm::vec2(contentMinX, contentMinY); - auto newSize = glm::vec2(contentMaxX - contentMinX + 1, contentMaxY - contentMinY + 1); + auto newCrop = glm::vec2(contentMin); + auto newSize = glm::vec2(contentMax - contentMin + 1); if (region->crop == newCrop && region->size == newSize) continue; auto previousCrop = region->crop; @@ -908,366 +528,72 @@ namespace anm2ed return isChanged; } - bool Document::regions_generate_from_animations(const std::set& animationIndices, const std::string& format, - RegionFrameMapping mapping) - { - if (animationIndices.empty()) return false; - - std::unordered_map regionNumbers{}; - bool isChanged{}; - for (auto animationIndex : animationIndices) - { - auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); - if (!animation) continue; - - auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - - auto layer_animation_regions_generate = [&](auto&& self, Element& layerAnimation) -> void - { - if (layerAnimation.type == ElementType::GROUP) - { - for (auto& child : layerAnimation.children) - self(self, child); - return; - } - if (layerAnimation.type != ElementType::LAYER_ANIMATION) return; - - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); - auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!spritesheet) return; - - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME) continue; - - auto region = document::frame_region_match_get(*spritesheet, frame); - if (!region) - { - auto generated = element_make(ElementType::REGION); - generated.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - auto [regionNumberIt, _] = regionNumbers.try_emplace(layer->spritesheetId, 1); - auto& regionNumber = regionNumberIt->second; - generated.name = document::region_name_get(format, regionNumber++); - generated.crop = frame.crop; - generated.size = frame.size; - generated.pivot = frame.pivot; - generated.origin = Origin::CUSTOM; - spritesheet->children.push_back(generated); - region = &spritesheet->children.back(); - isChanged = true; - } - if (mapping == RegionFrameMapping::SET && frame.regionId != region->id) - { - frame.regionId = region->id; - isChanged = true; - } - } - }; - - for (auto& layerAnimation : layerAnimations->children) - layer_animation_regions_generate(layer_animation_regions_generate, layerAnimation); - } - - return isChanged; - } - - bool Document::regions_generate_from_frames(const std::set& frameReferences, const std::string& format, - RegionFrameMapping mapping) - { - std::unordered_map regionNumbers{}; - bool isChanged{}; - for (auto frameReference : frameReferences) - { - if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) continue; - - auto frame = anm2.element_get(frameReference); - if (!frame || frame->type != ElementType::FRAME || frame->regionId != -1) continue; - - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, frameReference.itemID); - auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!spritesheet) continue; - - auto region = document::frame_region_match_get(*spritesheet, *frame); - if (!region) - { - auto generated = element_make(ElementType::REGION); - generated.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - auto& regionNumber = regionNumbers[layer->spritesheetId]; - generated.name = document::region_name_get(format, regionNumber++); - generated.crop = frame->crop; - generated.size = frame->size; - generated.pivot = frame->pivot; - generated.origin = Origin::CUSTOM; - spritesheet->children.push_back(generated); - region = &spritesheet->children.back(); - isChanged = true; - } - if (mapping == RegionFrameMapping::SET && frame->regionId != region->id) - { - frame->regionId = region->id; - isChanged = true; - } - } - - return isChanged; - } - bool Document::spritesheet_pack(int id, int padding) { - struct RectI - { - int x{}; - int y{}; - int w{}; - int h{}; - }; - struct PackItem { int regionId{-1}; - int srcX{}; - int srcY{}; - int width{}; - int height{}; - int packWidth{}; - int packHeight{}; - }; - - class MaxRectsPacker - { - int width{}; - int height{}; - std::vector freeRects{}; - - static bool intersects(const RectI& a, const RectI& b) - { - return !(b.x >= a.x + a.w || b.x + b.w <= a.x || b.y >= a.y + a.h || b.y + b.h <= a.y); - } - - static bool contains(const RectI& a, const RectI& b) - { - return b.x >= a.x && b.y >= a.y && b.x + b.w <= a.x + a.w && b.y + b.h <= a.y + a.h; - } - - void split_free_rects(const RectI& used) - { - std::vector next{}; - next.reserve(freeRects.size() * 2); - for (auto& free : freeRects) - { - if (!intersects(free, used)) - { - next.push_back(free); - continue; - } - if (used.x > free.x) next.push_back({free.x, free.y, used.x - free.x, free.h}); - if (used.x + used.w < free.x + free.w) - next.push_back({used.x + used.w, free.y, free.x + free.w - (used.x + used.w), free.h}); - if (used.y > free.y) next.push_back({free.x, free.y, free.w, used.y - free.y}); - if (used.y + used.h < free.y + free.h) - next.push_back({free.x, used.y + used.h, free.w, free.y + free.h - (used.y + used.h)}); - } - freeRects = std::move(next); - } - - void prune_free_rects() - { - for (int i = 0; i < (int)freeRects.size(); ++i) - { - if (freeRects[i].w <= 0 || freeRects[i].h <= 0) - { - freeRects.erase(freeRects.begin() + i--); - continue; - } - for (int j = i + 1; j < (int)freeRects.size();) - { - if (contains(freeRects[i], freeRects[j])) - freeRects.erase(freeRects.begin() + j); - else if (contains(freeRects[j], freeRects[i])) - { - freeRects.erase(freeRects.begin() + i--); - break; - } - else - ++j; - } - } - } - - public: - MaxRectsPacker(int width, int height) : width(width), height(height), freeRects({{0, 0, width, height}}) {} - - bool insert(int width, int height, RectI& result) - { - int bestShort = std::numeric_limits::max(); - int bestLong = std::numeric_limits::max(); - RectI best{}; - bool isFound{}; - for (auto& free : freeRects) - { - if (width > free.w || height > free.h) continue; - int leftOverW = free.w - width; - int leftOverH = free.h - height; - int shortSide = std::min(leftOverW, leftOverH); - int longSide = std::max(leftOverW, leftOverH); - if (shortSide < bestShort || (shortSide == bestShort && longSide < bestLong)) - { - bestShort = shortSide; - bestLong = longSide; - best = {free.x, free.y, width, height}; - isFound = true; - } - } - if (!isFound) return false; - result = best; - split_free_rects(best); - prune_free_rects(); - return true; - } - }; - - auto pack_regions = [&](const std::vector& items, int& packedWidth, int& packedHeight, - std::unordered_map& packedRects) - { - if (items.empty()) return false; - - int maxWidth{}; - int maxHeight{}; - int sumWidth{}; - int sumHeight{}; - std::int64_t totalArea{}; - for (auto& item : items) - { - maxWidth = std::max(maxWidth, item.packWidth); - maxHeight = std::max(maxHeight, item.packHeight); - sumWidth += item.packWidth; - sumHeight += item.packHeight; - totalArea += (std::int64_t)item.packWidth * item.packHeight; - } - if (maxWidth <= 0 || maxHeight <= 0) return false; - - int bestSquareDelta = std::numeric_limits::max(); - int bestArea = std::numeric_limits::max(); - std::unordered_map bestRects{}; - int bestWidth{}; - int bestHeight{}; - int startWidth = maxWidth; - int endWidth = std::max(startWidth, sumWidth); - int step = std::max(1, (endWidth - startWidth) / 512); - - for (int candidateWidth = startWidth; candidateWidth <= endWidth; candidateWidth += step) - { - int candidateHeightMin = std::max(maxHeight, (int)std::ceil((double)totalArea / candidateWidth)); - bool isValid{}; - int usedWidth{}; - int usedHeight{}; - std::unordered_map candidateRects{}; - for (int candidateHeight = candidateHeightMin; candidateHeight <= sumHeight; ++candidateHeight) - { - MaxRectsPacker packer(candidateWidth, candidateHeight); - candidateRects.clear(); - isValid = true; - usedWidth = 0; - usedHeight = 0; - for (auto& item : items) - { - RectI rect{}; - if (!packer.insert(item.packWidth, item.packHeight, rect)) - { - isValid = false; - break; - } - candidateRects[item.regionId] = rect; - usedWidth = std::max(usedWidth, rect.x + rect.w); - usedHeight = std::max(usedHeight, rect.y + rect.h); - } - if (isValid) break; - } - if (!isValid) continue; - - int area = usedWidth * usedHeight; - int squareDelta = std::abs(usedWidth - usedHeight); - if (squareDelta < bestSquareDelta || (squareDelta == bestSquareDelta && area < bestArea)) - { - bestSquareDelta = squareDelta; - bestArea = area; - bestWidth = usedWidth; - bestHeight = usedHeight; - bestRects = std::move(candidateRects); - if (bestArea == totalArea && bestSquareDelta == 0) break; - } - } - - if (bestArea == std::numeric_limits::max()) return false; - packedWidth = bestWidth; - packedHeight = bestHeight; - packedRects = std::move(bestRects); - return true; + glm::ivec2 source{}; + glm::ivec2 size{}; }; auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); auto texture = texture_get(id); if (!spritesheet || !texture || !texture->is_valid() || texture->pixels.empty()) return false; - auto packingPadding = std::max(0, padding); + padding = std::max(0, padding); std::vector items{}; for (auto& region : spritesheet->children) { if (region.type != ElementType::REGION) continue; auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size)); auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size)); - auto size = glm::max(maxPoint - minPoint, glm::ivec2(1)); - items.push_back({region.id, minPoint.x, minPoint.y, size.x, size.y, size.x + packingPadding * 2, - size.y + packingPadding * 2}); + items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))}); } - if (items.empty()) return false; std::sort(items.begin(), items.end(), [](const PackItem& a, const PackItem& b) { - int areaA = a.width * a.height; - int areaB = b.width * b.height; - if (areaA != areaB) return areaA > areaB; - return a.regionId < b.regionId; + auto areaA = a.size.x * a.size.y; + auto areaB = b.size.x * b.size.y; + return areaA != areaB ? areaA > areaB : a.regionId < b.regionId; }); - int packedWidth{}; - int packedHeight{}; - std::unordered_map packedRects{}; - if (!pack_regions(items, packedWidth, packedHeight, packedRects)) return false; - if (packedWidth <= 0 || packedHeight <= 0) return false; - - std::vector packedPixels((std::size_t)packedWidth * packedHeight * resource::texture::CHANNELS, 0); + std::vector sizes{}; for (auto& item : items) + sizes.push_back(item.size + padding * 2); + + glm::ivec2 packedSize{}; + std::vector positions{}; + if (!util::pack::rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return false; + + std::vector packedPixels((std::size_t)packedSize.x * packedSize.y * resource::texture::CHANNELS, 0); + std::unordered_map crops{}; + for (int i = 0; i < (int)items.size(); ++i) { - if (!packedRects.contains(item.regionId)) continue; - auto destinationRect = packedRects.at(item.regionId); - for (int y = 0; y < item.height; ++y) - for (int x = 0; x < item.width; ++x) + auto& item = items[i]; + auto destination = positions[i] + padding; + crops[item.regionId] = destination; + for (int y = 0; y < item.size.y; ++y) + for (int x = 0; x < item.size.x; ++x) { - int sourceX = item.srcX + x; - int sourceY = item.srcY + y; - int destinationX = destinationRect.x + packingPadding + x; - int destinationY = destinationRect.y + packingPadding + y; - if (sourceX < 0 || sourceY < 0 || sourceX >= texture->size.x || sourceY >= texture->size.y) continue; - if (destinationX < 0 || destinationY < 0 || destinationX >= packedWidth || destinationY >= packedHeight) + auto source = item.source + glm::ivec2(x, y); + auto target = destination + glm::ivec2(x, y); + if (glm::any(glm::lessThan(source, glm::ivec2(0))) || + glm::any(glm::greaterThanEqual(source, texture->size)) || + glm::any(glm::greaterThanEqual(target, packedSize))) continue; - auto sourceIndex = ((std::size_t)sourceY * texture->size.x + sourceX) * resource::texture::CHANNELS; - auto destinationIndex = - ((std::size_t)destinationY * packedWidth + destinationX) * resource::texture::CHANNELS; - std::copy_n(texture->pixels.data() + sourceIndex, resource::texture::CHANNELS, - packedPixels.data() + destinationIndex); + std::copy_n(texture->pixels.data() + + ((std::size_t)source.y * texture->size.x + source.x) * resource::texture::CHANNELS, + resource::texture::CHANNELS, + packedPixels.data() + + ((std::size_t)target.y * packedSize.x + target.x) * resource::texture::CHANNELS); } } - textures[id] = resource::Texture(packedPixels.data(), {packedWidth, packedHeight}); + textures[id] = resource::Texture(packedPixels.data(), packedSize); for (auto& region : spritesheet->children) - if (region.type == ElementType::REGION && packedRects.contains(region.id)) - { - auto& rect = packedRects.at(region.id); - region.crop = {rect.x + packingPadding, rect.y + packingPadding}; - } + if (region.type == ElementType::REGION && crops.contains(region.id)) region.crop = crops.at(region.id); assets_sync(SPRITESHEETS); return true; @@ -1277,65 +603,51 @@ namespace anm2ed bool isMakePrimaryRegion, origin::Type regionOrigin) { if (ids.size() < 2) return false; - auto baseId = *ids.begin(); - auto base = anm2.element_get(ElementType::SPRITESHEET, baseId); - auto baseTexture = texture_get(baseId); - if (!base || !baseTexture || !baseTexture->is_valid()) return false; for (auto id : ids) if (!anm2.element_get(ElementType::SPRITESHEET, id) || !texture_get(id) || !texture_get(id)->is_valid()) return false; + auto baseId = *ids.begin(); + auto base = anm2.element_get(ElementType::SPRITESHEET, baseId); auto origin = regionOrigin == origin::ORIGIN_CENTER ? Origin::CENTER : Origin::TOP_LEFT; - auto baseTextureSize = baseTexture->size; - auto mergedTexture = *baseTexture; - std::unordered_map offsets{{baseId, {}}}; + auto mergedTexture = *texture_get(baseId); + std::unordered_map> regionIdMap{}; + auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) + { + auto source = anm2.element_get(ElementType::SPRITESHEET, sourceId); + auto region = element_make(ElementType::REGION); + region.id = element_child_next_id_get(*base, ElementType::REGION); + auto stem = path::to_utf8(source->path.stem()); + region.name = stem.empty() ? std::format("#{}", sourceId) : stem; + region.crop = crop; + region.size = size; + region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2(); + region.origin = origin; + base->children.push_back(region); + }; + + if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedTexture.size); for (auto id : ids) { if (id == baseId) continue; auto texture = texture_get(id); - offsets[id] = isAppendRight ? glm::ivec2(mergedTexture.size.x, 0) : glm::ivec2(0, mergedTexture.size.y); + auto offset = isAppendRight ? glm::ivec2(mergedTexture.size.x, 0) : glm::ivec2(0, mergedTexture.size.y); mergedTexture = resource::Texture::merge_append(mergedTexture, *texture, isAppendRight); - } - textures[baseId] = std::move(mergedTexture); + if (!isMakeRegions) continue; - std::unordered_map> regionIdMap{}; - if (isMakeRegions) - { - auto add_location_region = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) + location_region_add(id, offset, texture->size); + for (auto sourceRegion : anm2.element_get(ElementType::SPRITESHEET, id)->children) { - auto source = anm2.element_get(ElementType::SPRITESHEET, sourceId); - if (!source) return; - auto region = element_make(ElementType::REGION); - region.id = element_child_next_id_get(*base, ElementType::REGION); - auto stem = path::to_utf8(source->path.stem()); - region.name = stem.empty() ? std::format("#{}", sourceId) : stem; - region.crop = crop; - region.size = size; - region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2(); - region.origin = origin; - base->children.push_back(region); - }; - - if (isMakePrimaryRegion) add_location_region(baseId, {}, baseTextureSize); - for (auto id : ids) - { - if (id == baseId) continue; - auto source = anm2.element_get(ElementType::SPRITESHEET, id); - auto sourceTexture = texture_get(id); - auto sheetOffset = offsets.at(id); - add_location_region(id, sheetOffset, sourceTexture->size); - for (auto& sourceRegion : source->children) - { - if (sourceRegion.type != ElementType::REGION) continue; - auto destinationRegion = sourceRegion; - destinationRegion.id = element_child_next_id_get(*base, ElementType::REGION); - destinationRegion.crop += sheetOffset; - base->children.push_back(destinationRegion); - regionIdMap[id][sourceRegion.id] = destinationRegion.id; - } + if (sourceRegion.type != ElementType::REGION) continue; + auto sourceRegionId = sourceRegion.id; + sourceRegion.id = element_child_next_id_get(*base, ElementType::REGION); + sourceRegion.crop += offset; + base->children.push_back(sourceRegion); + regionIdMap[id][sourceRegionId] = sourceRegion.id; } } + textures[baseId] = std::move(mergedTexture); std::unordered_map layerSpritesheetBefore{}; if (auto layers = anm2.element_get(ElementType::LAYERS)) @@ -1346,44 +658,18 @@ namespace anm2ed layer.spritesheetId = baseId; } - if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - auto layer_animation_update = [&](auto&& self, Element& layerAnimation) -> void - { - if (layerAnimation.type == ElementType::GROUP) - { - for (auto& child : layerAnimation.children) - self(self, child); - return; - } - if (layerAnimation.type != ElementType::LAYER_ANIMATION || - !layerSpritesheetBefore.contains(layerAnimation.layerId)) - return; - auto sourceSpritesheetId = layerSpritesheetBefore.at(layerAnimation.layerId); - if (sourceSpritesheetId == baseId) return; - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME) continue; - if (frame.regionId != -1) - { - if (isMakeRegions && regionIdMap.contains(sourceSpritesheetId) && - regionIdMap.at(sourceSpritesheetId).contains(frame.regionId)) - frame.regionId = regionIdMap.at(sourceSpritesheetId).at(frame.regionId); - else - frame.regionId = -1; - } - } - }; - for (auto& layerAnimation : layerAnimations->children) - layer_animation_update(layer_animation_update, layerAnimation); - } + animations_tracks_each(anm2.root, ElementType::LAYER_ANIMATION, + [&](Element& track) + { + auto before = layerSpritesheetBefore.find(track.layerId); + if (before == layerSpritesheetBefore.end() || before->second == baseId) return; + auto& remap = regionIdMap[before->second]; + for (auto& frame : track.children) + if (frame.type == ElementType::FRAME && frame.regionId != -1) + frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1; + }); auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS); - if (!spritesheets) return false; for (auto id : ids) if (id != baseId) { @@ -1395,434 +681,6 @@ namespace anm2ed return true; } - void Document::scan_and_set_regions() - { - auto animations = anm2.element_get(ElementType::ANIMATIONS); - if (animations) - { - for (auto& animation : animations->children) - { - if (animation.type != ElementType::ANIMATION) continue; - auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); - if (!layerAnimations) continue; - auto layer_animation_update = [&](auto&& self, Element& layerAnimation) -> void - { - if (layerAnimation.type == ElementType::GROUP) - { - for (auto& child : layerAnimation.children) - self(self, child); - return; - } - if (layerAnimation.type != ElementType::LAYER_ANIMATION) return; - auto layer = anm2.element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); - auto spritesheet = layer ? anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; - if (!spritesheet) return; - for (auto& frame : layerAnimation.children) - { - if (frame.type != ElementType::FRAME || frame.regionId != -1) continue; - auto frameCrop = glm::ivec2(frame.crop); - auto frameSize = glm::ivec2(frame.size); - auto framePivot = glm::ivec2(frame.pivot); - for (const auto& region : spritesheet->children) - if (region.type == ElementType::REGION && glm::ivec2(region.crop) == frameCrop && - glm::ivec2(region.size) == frameSize && glm::ivec2(region.pivot) == framePivot) - { - frame.regionId = region.id; - break; - } - } - }; - for (auto& layerAnimation : layerAnimations->children) - layer_animation_update(layer_animation_update, layerAnimation); - } - } - } - - bool Document::file_merge(const std::filesystem::path& path, FileMergePreset preset) - { - Anm2 source(path); - if (!source.isValid) return false; - - bool isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW; - bool isReplaceMatching = preset == FILE_MERGE_PRESET_REPLACE_MATCHING; - - auto remap_path = [&](const std::filesystem::path& original) -> std::filesystem::path - { - if (directory_get().empty()) return original; - std::error_code ec{}; - std::filesystem::path absolute{}; - bool isAbsolute{}; - - if (!original.empty()) - { - if (original.is_absolute()) - { - absolute = original; - isAbsolute = true; - } - else - { - absolute = std::filesystem::weakly_canonical(path.parent_path() / original, ec); - if (ec) - { - ec.clear(); - absolute = path.parent_path() / original; - } - isAbsolute = true; - } - } - - if (!isAbsolute) return original; - auto relative = std::filesystem::relative(absolute, directory_get(), ec); - if (!ec) return relative; - return original.empty() ? absolute : original; - }; - - auto remap_id = [](const std::unordered_map& remap, int id) - { - auto it = remap.find(id); - return it == remap.end() ? -1 : it->second; - }; - - auto find_by_name = [](Element& container, ElementType type, const std::string& name) - { - for (auto& child : container.children) - if (child.type == type && child.name == name) return &child; - return (Element*)nullptr; - }; - - auto name_unique_get = [&](Element& container, ElementType type, const std::string& name) - { - if (!find_by_name(container, type, name)) return name; - for (int i = 2;; ++i) - { - auto candidate = std::format("{} {}", name, i); - if (!find_by_name(container, type, candidate)) return candidate; - } - }; - - auto named_element_merge = [&](Element& container, Element item, ElementType type) - { - if (isAppendAsNew) - { - item.id = element_child_next_id_get(container, type); - item.name = name_unique_get(container, type, item.name); - container.children.push_back(item); - return item.id; - } - - if (auto existing = find_by_name(container, type, item.name)) - { - item.id = existing->id; - *existing = item; - } - else - { - item.id = element_child_next_id_get(container, type); - container.children.push_back(item); - } - return item.id; - }; - - auto child_set = [](Element& container, Element child, ElementType type) - { - if (auto existing = child_first_get(container, type)) - *existing = std::move(child); - else - container.children.push_back(std::move(child)); - }; - - auto track_find = [](Element& container, const Element& source) - { - auto find = [](auto&& self, Element& parent, const Element& source) -> Element* - { - for (auto& track : parent.children) - { - if (track.type == ElementType::GROUP) - if (auto result = self(self, track, source)) return result; - if (track.type != source.type) continue; - if (track.type == ElementType::LAYER_ANIMATION && track.layerId == source.layerId) return &track; - if (track.type == ElementType::NULL_ANIMATION && track.nullId == source.nullId) return &track; - } - return (Element*)nullptr; - }; - return find(find, container, source); - }; - - auto track_container_get = [](Element& animation, ElementType type) - { - if (auto container = child_first_get(animation, type)) return container; - animation.children.push_back(element_make(type)); - return &animation.children.back(); - }; - - std::unordered_map spritesheetRemap{}; - std::unordered_map layerRemap{}; - std::unordered_map nullRemap{}; - std::unordered_map eventRemap{}; - std::unordered_map soundRemap{}; - - auto spritesheet_import = [&](int sourceId) - { - if (sourceId < 0) return -1; - if (spritesheetRemap.contains(sourceId)) return spritesheetRemap[sourceId]; - - auto sourceSpritesheets = source.element_get(ElementType::SPRITESHEETS); - auto destinationSpritesheets = anm2.element_get(ElementType::SPRITESHEETS); - auto spritesheet = - sourceSpritesheets ? child_id_get(*sourceSpritesheets, ElementType::SPRITESHEET, sourceId) : nullptr; - if (!spritesheet || !destinationSpritesheets) return -1; - - auto imported = *spritesheet; - imported.id = element_child_next_id_get(*destinationSpritesheets, ElementType::SPRITESHEET); - imported.path = remap_path(imported.path); - destinationSpritesheets->children.push_back(imported); - spritesheetRemap[sourceId] = imported.id; - return imported.id; - }; - - if (auto sourceSounds = source.element_get(ElementType::SOUNDS)) - if (auto destinationSounds = anm2.element_get(ElementType::SOUNDS)) - for (auto sound : sourceSounds->children) - { - if (sound.type != ElementType::SOUND_ELEMENT) continue; - auto sourceId = sound.id; - sound.path = remap_path(sound.path); - int destinationId{-1}; - if (!isAppendAsNew) - for (auto& existing : destinationSounds->children) - if (existing.type == ElementType::SOUND_ELEMENT && existing.path == sound.path) - { - destinationId = existing.id; - sound.id = destinationId; - existing = sound; - break; - } - if (destinationId == -1) - { - destinationId = element_child_next_id_get(*destinationSounds, ElementType::SOUND_ELEMENT); - sound.id = destinationId; - destinationSounds->children.push_back(sound); - } - soundRemap[sourceId] = destinationId; - } - - if (auto sourceLayers = source.element_get(ElementType::LAYERS)) - if (auto destinationLayers = anm2.element_get(ElementType::LAYERS)) - for (auto layer : sourceLayers->children) - { - if (layer.type != ElementType::LAYER_ELEMENT) continue; - auto sourceId = layer.id; - auto sourceSpritesheetId = layer.spritesheetId; - auto existing = - isAppendAsNew ? nullptr : find_by_name(*destinationLayers, ElementType::LAYER_ELEMENT, layer.name); - layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(sourceSpritesheetId); - layerRemap[sourceId] = named_element_merge(*destinationLayers, layer, ElementType::LAYER_ELEMENT); - } - - if (auto sourceNulls = source.element_get(ElementType::NULLS)) - if (auto destinationNulls = anm2.element_get(ElementType::NULLS)) - for (auto null : sourceNulls->children) - { - if (null.type != ElementType::NULL_ELEMENT) continue; - auto sourceId = null.id; - nullRemap[sourceId] = named_element_merge(*destinationNulls, null, ElementType::NULL_ELEMENT); - } - - if (auto sourceEvents = source.element_get(ElementType::EVENTS)) - if (auto destinationEvents = anm2.element_get(ElementType::EVENTS)) - for (auto event : sourceEvents->children) - { - if (event.type != ElementType::EVENT_ELEMENT) continue; - auto sourceId = event.id; - eventRemap[sourceId] = named_element_merge(*destinationEvents, event, ElementType::EVENT_ELEMENT); - } - - auto item_remap = [&](Element& item) - { - for (auto& frame : item.children) - { - if (frame.type != ElementType::FRAME && frame.type != ElementType::TRIGGER) continue; - for (auto& soundId : frame.soundIds) - soundId = remap_id(soundRemap, soundId); - frame.eventId = remap_id(eventRemap, frame.eventId); - } - }; - - auto track_tree_remap = [&](auto&& self, Element item, int itemType, Element& container, - int parentGroupId = -1) -> void - { - auto trackType = itemType == LAYER ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; - if (item.type == ElementType::GROUP) - { - auto group = element_make(ElementType::GROUP); - group.id = item.id == -1 ? element_child_next_id_get(container, ElementType::GROUP) : item.id; - group.name = item.name; - group.isExpanded = item.isExpanded; - group.isVisible = item.isVisible; - if (auto root = child_first_get(item, ElementType::ROOT_ANIMATION)) - group.children.push_back(*root); - else - { - auto defaultRoot = element_make(ElementType::ROOT_ANIMATION); - defaultRoot.children.push_back(element_make(ElementType::FRAME)); - group.children.push_back(defaultRoot); - } - container.children.push_back(group); - for (auto child : item.children) - self(self, child, itemType, container, group.id); - return; - } - - if (item.type != trackType) return; - if (itemType == LAYER) - item.layerId = remap_id(layerRemap, item.layerId); - else - item.nullId = remap_id(nullRemap, item.nullId); - if ((itemType == LAYER && item.layerId < 0) || (itemType == NULL_ && item.nullId < 0)) return; - if (parentGroupId != -1) item.groupId = parentGroupId; - item_remap(item); - container.children.push_back(item); - }; - - auto animation_build = [&](const Element& incoming) - { - auto animation = element_make(ElementType::ANIMATION); - animation.name = incoming.name; - animation.frameNum = incoming.frameNum; - animation.isLoop = incoming.isLoop; - - if (auto root = child_first_get(incoming, ElementType::ROOT_ANIMATION)) - { - auto item = *root; - item_remap(item); - animation.children.push_back(item); - } - - if (auto layerAnimations = child_first_get(incoming, ElementType::LAYER_ANIMATIONS)) - { - auto container = element_make(ElementType::LAYER_ANIMATIONS); - for (auto item : layerAnimations->children) - track_tree_remap(track_tree_remap, item, LAYER, container); - animation.children.push_back(container); - } - - if (auto nullAnimations = child_first_get(incoming, ElementType::NULL_ANIMATIONS)) - { - auto container = element_make(ElementType::NULL_ANIMATIONS); - for (auto item : nullAnimations->children) - track_tree_remap(track_tree_remap, item, NULL_, container); - animation.children.push_back(container); - } - - if (auto triggers = child_first_get(incoming, ElementType::TRIGGERS)) - { - auto item = *triggers; - item_remap(item); - animation.children.push_back(item); - } - - return animation; - }; - - auto track_merge = [&](Element& destinationContainer, const Element& sourceTrack) - { - if (auto destinationTrack = track_find(destinationContainer, sourceTrack)) - { - if (!sourceTrack.children.empty()) *destinationTrack = sourceTrack; - } - else - destinationContainer.children.push_back(sourceTrack); - }; - - auto track_container_merge = - [&](Element& destinationContainer, const Element& sourceContainer, ElementType trackType) - { - std::unordered_map groupRemap{}; - for (auto item : sourceContainer.children) - { - if (item.type != ElementType::GROUP) continue; - auto sourceGroupId = item.id; - item.id = element_child_next_id_get(destinationContainer, ElementType::GROUP); - std::erase_if(item.children, [](const Element& child) { return child.type != ElementType::ROOT_ANIMATION; }); - if (!child_first_get(item, ElementType::ROOT_ANIMATION)) - { - auto root = element_make(ElementType::ROOT_ANIMATION); - root.children.push_back(element_make(ElementType::FRAME)); - item.children.push_back(root); - } - destinationContainer.children.push_back(item); - groupRemap[sourceGroupId] = item.id; - } - - for (auto item : sourceContainer.children) - { - if (item.type != trackType) continue; - if (item.groupId != -1) item.groupId = groupRemap.contains(item.groupId) ? groupRemap.at(item.groupId) : -1; - track_merge(destinationContainer, item); - } - }; - - if (auto sourceAnimations = source.element_get(ElementType::ANIMATIONS)) - if (auto destinationAnimations = anm2.element_get(ElementType::ANIMATIONS)) - { - std::string defaultAnimationName{}; - for (const auto& incoming : sourceAnimations->children) - { - if (incoming.type != ElementType::ANIMATION) continue; - auto processed = animation_build(incoming); - auto destination = find_by_name(*destinationAnimations, ElementType::ANIMATION, processed.name); - if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; - if (!destination || isAppendAsNew) - { - if (isAppendAsNew) - { - processed.name = name_unique_get(*destinationAnimations, ElementType::ANIMATION, processed.name); - if (incoming.name == sourceAnimations->defaultAnimation) defaultAnimationName = processed.name; - } - destinationAnimations->children.push_back(processed); - continue; - } - - if (isReplaceMatching) - { - *destination = processed; - continue; - } - - destination->frameNum = std::max(destination->frameNum, processed.frameNum); - destination->isLoop = processed.isLoop; - if (auto root = child_first_get(processed, ElementType::ROOT_ANIMATION); - root && !root->children.empty()) - child_set(*destination, *root, ElementType::ROOT_ANIMATION); - if (auto triggers = child_first_get(processed, ElementType::TRIGGERS); - triggers && !triggers->children.empty()) - child_set(*destination, *triggers, ElementType::TRIGGERS); - - if (auto layerAnimations = child_first_get(processed, ElementType::LAYER_ANIMATIONS)) - { - auto destinationLayerAnimations = track_container_get(*destination, ElementType::LAYER_ANIMATIONS); - track_container_merge(*destinationLayerAnimations, *layerAnimations, ElementType::LAYER_ANIMATION); - } - - if (auto nullAnimations = child_first_get(processed, ElementType::NULL_ANIMATIONS)) - { - auto destinationNullAnimations = track_container_get(*destination, ElementType::NULL_ANIMATIONS); - track_container_merge(*destinationNullAnimations, *nullAnimations, ElementType::NULL_ANIMATION); - } - - destination->frameNum = std::max(destination->frameNum, animation_length_get(*destination)); - } - - if (destinationAnimations->defaultAnimation.empty() && !sourceAnimations->defaultAnimation.empty()) - destinationAnimations->defaultAnimation = - defaultAnimationName.empty() ? sourceAnimations->defaultAnimation : defaultAnimationName; - } - - assets_sync(ALL); - return true; - } - void Document::hash_set() { hash = anm2.hash(); } void Document::clean() @@ -1838,47 +696,25 @@ namespace anm2ed { spritesheetHashes.clear(); spritesheetSaveHashes.clear(); - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) - { - auto currentHash = document::spritesheet_hash_get(spritesheet, texture_get(spritesheet.id)); - spritesheetHashes[spritesheet.id] = currentHash; - spritesheetSaveHashes[spritesheet.id] = currentHash; - } + spritesheet_hashes_sync(); } void Document::spritesheet_hashes_sync() { std::set validIds{}; - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) validIds.insert(spritesheet.id); - - for (auto it = spritesheetHashes.begin(); it != spritesheetHashes.end();) - { - if (!validIds.contains(it->first)) - it = spritesheetHashes.erase(it); - else - ++it; - } - - for (auto it = spritesheetSaveHashes.begin(); it != spritesheetSaveHashes.end();) - { - if (!validIds.contains(it->first)) - it = spritesheetSaveHashes.erase(it); - else - ++it; - } - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) for (auto& spritesheet : spritesheets->children) if (spritesheet.type == ElementType::SPRITESHEET) { + validIds.insert(spritesheet.id); auto currentHash = document::spritesheet_hash_get(spritesheet, texture_get(spritesheet.id)); spritesheetHashes[spritesheet.id] = currentHash; - if (!spritesheetSaveHashes.contains(spritesheet.id)) spritesheetSaveHashes[spritesheet.id] = currentHash; + spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); } + + auto is_invalid = [&](const auto& pair) { return !validIds.contains(pair.first); }; + std::erase_if(spritesheetHashes, is_invalid); + std::erase_if(spritesheetSaveHashes, is_invalid); } void Document::change(ChangeType type) @@ -1888,48 +724,51 @@ namespace anm2ed auto events_set = [&]() { - auto events = anm2.element_get(ElementType::EVENTS); - event.labels_set(document::element_name_labels_get(events, ElementType::EVENT_ELEMENT, true), - document::element_ids_get(events, ElementType::EVENT_ELEMENT, true)); + document::storage_labels_set(event, anm2.element_get(ElementType::EVENTS), ElementType::EVENT_ELEMENT, true, + document::element_name_get); }; - auto animations_set = [&]() { animation.labels_set(document::animation_labels_get(anm2)); }; - auto spritesheets_set = [&]() { - spritesheet.labels_set(document::spritesheet_labels_get(anm2), document::spritesheet_ids_get(anm2)); + document::storage_labels_set( + spritesheet, anm2.element_get(ElementType::SPRITESHEETS), ElementType::SPRITESHEET, false, + [](const Element& element) + { + auto pathString = path::to_utf8(element.path); + return std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(element.id, pathString)); + }); spritesheet_hashes_sync(); }; - auto sounds_set = [&]() { sound.labels_set(document::sound_labels_get(anm2), document::sound_ids_get(anm2)); }; + auto sounds_set = [&]() + { + document::storage_labels_set(sound, anm2.element_get(ElementType::SOUNDS), ElementType::SOUND_ELEMENT, true, + [](const Element& element) + { + auto pathString = path::to_utf8(element.path); + return std::vformat(localize.get(FORMAT_SOUND), + std::make_format_args(element.id, pathString)); + }); + }; auto regions_set = [&]() { regionBySpritesheet.clear(); if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET) - { - Storage storage{}; - storage.labels_set(document::element_name_labels_get(&spritesheet, ElementType::REGION, true), - document::element_ids_get(&spritesheet, ElementType::REGION, true)); - regionBySpritesheet.emplace(spritesheet.id, std::move(storage)); - } + for (auto& element : spritesheets->children) + if (element.type == ElementType::SPRITESHEET) + document::storage_labels_set(regionBySpritesheet[element.id], &element, ElementType::REGION, true, + document::element_name_get); }; auto shaders_set = [&]() { - auto shaderItems = anm2.element_get(ElementType::SHADERS); - shader.labels_set(document::element_name_labels_get(shaderItems, ElementType::SHADER, true), - document::element_ids_get(shaderItems, ElementType::SHADER, true)); + document::storage_labels_set(shader, anm2.element_get(ElementType::SHADERS), ElementType::SHADER, true, + document::element_name_get); }; switch (type) { - case LAYERS: - break; - case NULLS: - break; case EVENTS: events_set(); break; @@ -1956,18 +795,18 @@ namespace anm2ed spritesheets_set(); regions_set(); shaders_set(); - animations_set(); sounds_set(); break; default: break; } - snapshots.commit(current); + snapshots.commit(); } bool Document::is_dirty() const { return hash != saveHash; } bool Document::is_autosave_dirty() const { return hash != autosaveHash; } + void Document::spritesheet_hash_update(int id) { auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); @@ -1978,12 +817,8 @@ namespace anm2ed void Document::spritesheet_hash_set_saved(int id) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); - if (!spritesheet) return; - assets_sync(TEXTURES); - auto currentHash = document::spritesheet_hash_get(*spritesheet, texture_get(id)); - spritesheetHashes[id] = currentHash; - spritesheetSaveHashes[id] = currentHash; + spritesheet_hash_update(id); + if (spritesheetHashes.contains(id)) spritesheetSaveHashes[id] = spritesheetHashes[id]; } bool Document::spritesheet_is_dirty(int id) @@ -1991,16 +826,16 @@ namespace anm2ed if (!anm2.element_get(ElementType::SPRITESHEET, id)) return false; if (!spritesheetHashes.contains(id)) spritesheet_hash_update(id); auto saveIt = spritesheetSaveHashes.find(id); - if (saveIt == spritesheetSaveHashes.end()) return false; - return spritesheetHashes.at(id) != saveIt->second; + return saveIt != spritesheetSaveHashes.end() && spritesheetHashes.at(id) != saveIt->second; } bool Document::spritesheet_any_dirty() { - if (auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS)) - for (auto& spritesheet : spritesheets->children) - if (spritesheet.type == ElementType::SPRITESHEET && spritesheet_is_dirty(spritesheet.id)) return true; - return false; + auto spritesheets = anm2.element_get(ElementType::SPRITESHEETS); + return spritesheets && + std::ranges::any_of( + spritesheets->children, [&](const Element& spritesheet) + { return spritesheet.type == ElementType::SPRITESHEET && spritesheet_is_dirty(spritesheet.id); }); } std::filesystem::path Document::directory_get() const { return path.parent_path(); } @@ -2014,31 +849,18 @@ namespace anm2ed bool Document::is_frame_reference_valid(Reference frameReference) const { - if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; - auto itemReference = frameReference; - itemReference.frameIndex = -1; - auto item = anm2.element_get(itemReference); - return item && track_frame_get(*item, frameReference.frameIndex); + return document::frame_reference_validator_make(anm2)(frameReference); } std::set Document::item_frame_references_get(Reference itemReference) const { std::set result{}; itemReference.frameIndex = -1; - if (itemReference.itemType == NONE) return result; - - auto item = anm2.element_get(itemReference); - if (!item) return result; - - auto frameType = itemReference.itemType == TRIGGER ? ElementType::TRIGGER : ElementType::FRAME; - int frameIndex{}; - for (auto& child : item->children) + auto item = itemReference.itemType == NONE ? nullptr : anm2.element_get(itemReference); + for (int frameIndex = 0; item && frameIndex < track_frames_count_get(*item); ++frameIndex) { - if (child.type != frameType) continue; - auto frameReference = itemReference; - frameReference.frameIndex = frameIndex; - result.insert(frameReference); - ++frameIndex; + itemReference.frameIndex = frameIndex; + result.insert(itemReference); } return result; } @@ -2047,18 +869,11 @@ namespace anm2ed { auto selectedItems = items.references; if (selectedItems.empty() && reference.itemType != NONE) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - selectedItems.insert(itemReference); - } + selectedItems.insert(document::item_reference_get(reference)); std::set result{}; for (auto itemReference : selectedItems) - { - auto itemFrames = item_frame_references_get(itemReference); - result.insert(itemFrames.begin(), itemFrames.end()); - } + result.merge(item_frame_references_get(itemReference)); return result; } @@ -2072,77 +887,40 @@ namespace anm2ed result.insert(frameReference); } - std::map frameCounts{}; - auto is_frame_reference_valid_cached = [&](Reference frameReference) - { - if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; - auto itemReference = frameReference; - itemReference.frameIndex = -1; - if (!frameCounts.contains(itemReference)) - { - auto item = anm2.element_get(itemReference); - frameCounts[itemReference] = item ? document::frame_count_get(*item) : 0; - } - return frameReference.frameIndex < frameCounts[itemReference]; - }; - + auto isValid = document::frame_reference_validator_make(anm2); + auto is_invalid = [&](const Reference& frameReference) { return !isValid(frameReference); }; bool isMultiFrameSelection = frames.references.size() > 1 || frames.selection.size() > 1; - std::erase_if(result, - [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); + std::erase_if(result, is_invalid); if (isMultiFrameSelection && result.size() <= 1) { auto itemFrames = selected_item_frame_references_get(); - std::erase_if(itemFrames, - [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); + std::erase_if(itemFrames, is_invalid); if (itemFrames.size() > result.size()) result = std::move(itemFrames); } - if (result.empty() && fallback == FrameReferenceFallback::CURRENT && is_frame_reference_valid_cached(reference)) - result.insert(reference); - + if (result.empty() && fallback == FrameReferenceFallback::CURRENT && isValid(reference)) result.insert(reference); return result; } void Document::frame_references_set(std::set frameReferences) { - std::map frameCounts{}; - auto is_frame_reference_valid_cached = [&](Reference frameReference) - { - if (frameReference.itemType == NONE || frameReference.frameIndex < 0) return false; - auto itemReference = frameReference; - itemReference.frameIndex = -1; - if (!frameCounts.contains(itemReference)) - { - auto item = anm2.element_get(itemReference); - frameCounts[itemReference] = item ? document::frame_count_get(*item) : 0; - } - return frameReference.frameIndex < frameCounts[itemReference]; - }; - - std::erase_if(frameReferences, - [&](const Reference& frameReference) { return !is_frame_reference_valid_cached(frameReference); }); + auto isValid = document::frame_reference_validator_make(anm2); + std::erase_if(frameReferences, [&](const Reference& frameReference) { return !isValid(frameReference); }); frames.references = std::move(frameReferences); frames.selection.clear(); items.references.clear(); - if (frames.references.empty()) return; - if (!frames.references.contains(reference) || !is_frame_reference_valid_cached(reference)) - reference = *frames.references.begin(); + if (!frames.references.contains(reference) || !isValid(reference)) reference = *frames.references.begin(); for (auto frameReference : frames.references) { - frameReference.frameIndex = -1; - items.references.insert(frameReference); - } - - for (auto frameReference : frames.references) - if (frameReference.animationIndex == reference.animationIndex && frameReference.itemType == reference.itemType && - frameReference.itemID == reference.itemID && frameReference.groupType == reference.groupType && - frameReference.groupId == reference.groupId && frameReference.frameIndex >= 0) + items.references.insert(document::item_reference_get(frameReference)); + if (document::is_reference_item_matched(frameReference, reference) && frameReference.frameIndex >= 0) frames.selection.insert(frameReference.frameIndex); + } } void Document::frame_references_clear() @@ -2156,16 +934,9 @@ namespace anm2ed std::set selectedReferences = items.references; if (selectedReferences.empty()) for (auto frameReference : frame_references_get(FrameReferenceFallback::NONE)) - { - frameReference.frameIndex = -1; - selectedReferences.insert(frameReference); - } + selectedReferences.insert(document::item_reference_get(frameReference)); if (selectedReferences.empty() && reference.itemType != NONE) - { - auto itemReference = reference; - itemReference.frameIndex = -1; - selectedReferences.insert(itemReference); - } + selectedReferences.insert(document::item_reference_get(reference)); std::vector result{}; for (auto itemReference : selectedReferences) @@ -2185,160 +956,80 @@ namespace anm2ed } Element* Document::frame_get() { return anm2.element_get(reference); } - - Element* Document::item_get() - { - auto itemReference = reference; - itemReference.frameIndex = -1; - return anm2.element_get(itemReference); - } + Element* Document::item_get() { return anm2.element_get(document::item_reference_get(reference)); } Element* Document::animation_get() { return anm2.element_get(ElementType::ANIMATION, reference.animationIndex); } Element* Document::spritesheet_get() { return anm2.element_get(ElementType::SPRITESHEET, spritesheet.reference); } - void Document::spritesheet_add(const std::filesystem::path& path) { spritesheets_add({path}); } - void Document::spritesheets_add(const std::vector& paths) { - struct LoadedSpritesheet - { - std::filesystem::path relativePath{}; - resource::Texture texture{}; - }; - auto items = anm2.element_get(ElementType::SPRITESHEETS); if (!items) return; auto directory = directory_get(); - std::vector loaded{}; + std::vector> loaded{}; for (auto& path : paths) { - auto pathCopy = path; - auto storagePath = path::backslash_handle(pathCopy); + auto storagePath = path::backslash_handle(path); std::optional workingDirectory{}; if (!storagePath.is_absolute()) workingDirectory.emplace(directory); - auto loadPath = path::case_insensitive_find(storagePath); - auto texture = resource::Texture(loadPath); + auto texture = resource::Texture(path::case_insensitive_find(storagePath)); if (!texture.is_valid()) { - auto pathUtf8 = path::to_utf8(pathCopy); - toasts.push(std::vformat(localize.get(TOAST_SPRITESHEET_INIT_FAILED), std::make_format_args(pathUtf8))); - logger.error(std::vformat(localize.get(TOAST_SPRITESHEET_INIT_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathUtf8))); + toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path::to_utf8(path)); continue; } - - loaded.push_back({.relativePath = path::backslash_replace(path::make_relative(storagePath, directory)), - .texture = std::move(texture)}); + loaded.emplace_back(path::backslash_replace(path::make_relative(storagePath, directory)), std::move(texture)); } if (loaded.empty()) return; - anm2_snapshot(localize.get(EDIT_ADD_SPRITESHEET)); + snapshots.anm2_push(localize.get(EDIT_ADD_SPRITESHEET)); std::set added{}; - for (auto& loadedSpritesheet : loaded) + for (auto& [relativePath, texture] : loaded) { - auto id = element_child_next_id_get(*items, ElementType::SPRITESHEET); - auto spritesheet = element_make(ElementType::SPRITESHEET); - spritesheet.id = id; - spritesheet.path = loadedSpritesheet.relativePath; - auto pathString = path::to_utf8(spritesheet.path); - items->children.push_back(spritesheet); - textures[id] = std::move(loadedSpritesheet.texture); - texturePaths[id] = spritesheet.path; - added.insert(id); - this->spritesheet.reference = id; - spritesheet_hash_set_saved(id); - toasts.push(std::vformat(localize.get(TOAST_SPRITESHEET_INITIALIZED), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_SPRITESHEET_INITIALIZED, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + auto& element = items->children.emplace_back(element_make(ElementType::SPRITESHEET)); + element.id = element_child_next_id_get(*items, ElementType::SPRITESHEET); + element.path = relativePath; + textures[element.id] = std::move(texture); + texturePaths[element.id] = element.path; + added.insert(element.id); + spritesheet.reference = element.id; + spritesheet_hash_set_saved(element.id); + toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path::to_utf8(element.path)); } - this->spritesheet.selection = added; + spritesheet.selection = added; change(Document::SPRITESHEETS); } - void Document::sound_add(const std::filesystem::path& path) { sounds_add({path}); } - void Document::sounds_add(const std::vector& paths) { auto items = anm2.element_get(ElementType::SOUNDS); - if (!items) return; - auto directory = directory_get(); + if (!items || std::ranges::all_of(paths, [](const auto& path) { return path.empty(); })) return; - std::vector validPaths{}; - for (auto& path : paths) - if (!path.empty()) validPaths.push_back(path); - if (validPaths.empty()) return; - - anm2_snapshot(localize.get(EDIT_ADD_SOUND)); + snapshots.anm2_push(localize.get(EDIT_ADD_SOUND)); std::set added{}; - for (auto& path : validPaths) + for (auto& path : paths) { - auto id = element_child_next_id_get(*items, ElementType::SOUND_ELEMENT); - auto soundElement = element_make(ElementType::SOUND_ELEMENT); - soundElement.id = id; - auto loadPath = path::backslash_handle(path); - auto relativePath = path::backslash_replace(path::make_relative(loadPath, directory)); - { - WorkingDirectory workingDirectory(directory_get()); - soundElement.path = relativePath; - sounds[id] = resource::Audio(path::case_insensitive_find(soundElement.path)); - soundPaths[id] = soundElement.path; - } - auto soundPath = path::to_utf8(soundElement.path); - items->children.push_back(soundElement); - added.insert(id); - sound.reference = id; - toasts.push(std::vformat(localize.get(TOAST_SOUND_INITIALIZED), std::make_format_args(id, soundPath))); - logger.info( - std::vformat(localize.get(TOAST_SOUND_INITIALIZED, anm2ed::ENGLISH), std::make_format_args(id, soundPath))); + if (path.empty()) continue; + auto& element = items->children.emplace_back(element_make(ElementType::SOUND_ELEMENT)); + element.id = element_child_next_id_get(*items, ElementType::SOUND_ELEMENT); + element.path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get())); + WorkingDirectory workingDirectory(directory_get()); + document::resource_load(element.id, element.path, sounds, soundPaths); + added.insert(element.id); + sound.reference = element.id; + toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path::to_utf8(element.path)); } sound.selection = added; change(Document::SOUNDS); } - void Document::anm2_snapshot(const std::string& message) - { - this->message = message; - snapshots.anm2_push(current, message); - } - - void Document::tracks_snapshot(const std::string& message, const std::set& trackReferences) - { - this->message = message; - snapshots.tracks_push(current, message, trackReferences); - } - - void Document::frames_snapshot(const std::string& message, const std::set& frameReferences) - { - this->message = message; - snapshots.frames_push(current, message, frameReferences); - } - - void Document::regions_snapshot(const std::string& message, int spritesheetId, const std::set& regionIds) - { - this->message = message; - snapshots.regions_push(current, message, spritesheetId, regionIds); - } - - void Document::textures_snapshot(const std::string& message) - { - this->message = message; - snapshots.textures_push(current, message); - } - - void Document::anm2_textures_snapshot(const std::string& message) - { - this->message = message; - snapshots.anm2_textures_push(current, message); - } - void Document::undo() { if (!snapshots.undo()) return; document::restored_snapshot_sanitize(*this); - toasts.push(std::vformat(localize.get(TOAST_UNDO), std::make_format_args(message))); - logger.info(std::vformat(localize.get(TOAST_UNDO, anm2ed::ENGLISH), std::make_format_args(message))); + toast_log(Level::INFO, TOAST_UNDO, message); change(Document::ALL); } @@ -2346,8 +1037,7 @@ namespace anm2ed { if (!snapshots.redo()) return; document::restored_snapshot_sanitize(*this); - toasts.push(std::vformat(localize.get(TOAST_REDO), std::make_format_args(message))); - logger.info(std::vformat(localize.get(TOAST_REDO, anm2ed::ENGLISH), std::make_format_args(message))); + toast_log(Level::INFO, TOAST_REDO, message); change(Document::ALL); } diff --git a/src/document.hpp b/src/document.hpp index eb766bb..1610580 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -20,7 +20,41 @@ namespace anm2ed class Manager; struct Command; - class Document + struct DocumentData + { + std::filesystem::path path{}; + uint64_t tabId{}; + Snapshots snapshots{}; + std::map regionBySpritesheet{}; + int changeAllFramePropertiesRegionId{-1}; + int changeAllFramePropertiesShaderId{-1}; + + float previewZoom{200}; + glm::vec2 previewPan{}; + glm::vec2 editorPan{}; + float editorZoom{200}; + int overlayIndex{-1}; + uint64_t overlayDocumentId{}; + + uint64_t hash{}; + uint64_t saveHash{}; + uint64_t autosaveHash{}; + double lastAutosaveTime{}; + bool isValid{true}; + bool isOpen{true}; + bool isForceDirty{false}; + std::unordered_map spritesheetHashes{}; + std::unordered_map spritesheetSaveHashes{}; + std::unordered_map texturePaths{}; + std::unordered_map soundPaths{}; + std::map shaderVertexPaths{}; + std::map shaderFragmentPaths{}; + std::map shaders{}; + bool isAnimationPreviewSet{false}; + bool isSpritesheetEditorSet{false}; + }; + + class Document : public DocumentData { public: enum ChangeType @@ -54,72 +88,13 @@ namespace anm2ed SPRITESHEET }; - enum class RegionFrameMapping - { - PRESERVE, - SET - }; - - enum FileMergePreset - { - FILE_MERGE_PRESET_MERGE_BY_NAME, - FILE_MERGE_PRESET_APPEND_AS_NEW, - FILE_MERGE_PRESET_REPLACE_MATCHING, - FILE_MERGE_PRESET_COUNT - }; - - std::filesystem::path path{}; - uint64_t tabId{}; - - Snapshots snapshots{}; Snapshot& current = snapshots.current; - - Playback& playback = current.playback; - Storage& animation = current.animation; - Storage& event = current.event; - Storage& frames = current.frames; - Storage& items = current.items; - Storage& layer = current.layer; - Storage& merge = current.merge; - Storage& null = current.null; - Storage& region = current.region; - Storage& shader = current.shader; - Storage& sound = current.sound; - Storage& spritesheet = current.spritesheet; - std::map& textures = current.textures; - std::map& sounds = current.sounds; +#define X(type, name) type& name = current.name; + SNAPSHOT_STEP_STATE_FIELDS + SNAPSHOT_STEP_RESOURCE_FIELDS +#undef X Anm2& anm2 = current.anm2; - Reference& reference = current.reference; - std::set& groupReferences = current.groupReferences; - float& frameTime = current.frameTime; std::string& message = current.message; - std::map regionBySpritesheet{}; - int changeAllFramePropertiesRegionId{-1}; - int changeAllFramePropertiesShaderId{-1}; - - float previewZoom{200}; - glm::vec2 previewPan{}; - glm::vec2 editorPan{}; - float editorZoom{200}; - int overlayIndex{-1}; - uint64_t overlayDocumentId{}; - - uint64_t hash{}; - uint64_t saveHash{}; - uint64_t autosaveHash{}; - double lastAutosaveTime{}; - bool isValid{true}; - bool isOpen{true}; - bool isForceDirty{false}; - std::unordered_map spritesheetHashes{}; - std::unordered_map spritesheetSaveHashes{}; - std::unordered_map texturePaths{}; - std::unordered_map soundPaths{}; - std::map shaderVertexPaths{}; - std::map shaderFragmentPaths{}; - std::map shaders{}; - bool isAnimationPreviewSet{false}; - bool isSpritesheetEditorSet{false}; EditTarget editTarget{EditTarget::NONE}; Document(const std::filesystem::path&, bool = false, std::string* = nullptr); @@ -128,25 +103,17 @@ namespace anm2ed Document(Document&&) noexcept; Document& operator=(Document&&) noexcept; bool save(const std::filesystem::path& = {}, std::string* = nullptr, Options = {}); - void anm2_change(ChangeType); void assets_sync(ChangeType = ALL); void texture_change(int); bool texture_reload(int); bool sound_reload(int); bool shader_reload(int, std::string* = nullptr); resource::Texture* texture_get(int); - const resource::Texture* texture_get(int) const; resource::Audio* sound_get(int); - const resource::Audio* sound_get(int) const; resource::Shader* shader_get(int); - const resource::Shader* shader_get(int) const; bool regions_trim(int, const std::set&); - bool regions_generate_from_animations(const std::set&, const std::string&, RegionFrameMapping); - bool regions_generate_from_frames(const std::set&, const std::string&, RegionFrameMapping); bool spritesheet_pack(int, int); bool spritesheets_merge(const std::set&, bool, bool, bool, origin::Type); - void scan_and_set_regions(); - bool file_merge(const std::filesystem::path&, FileMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME); void hash_set(); void clean(); void change(ChangeType); @@ -175,39 +142,16 @@ namespace anm2ed Element* spritesheet_get(); Element* animation_get(); - void spritesheet_add(const std::filesystem::path&); void spritesheets_add(const std::vector&); - void sound_add(const std::filesystem::path&); void sounds_add(const std::vector&); bool autosave(std::string* = nullptr, Options = {}); std::filesystem::path autosave_path_get(); std::filesystem::path path_from_autosave_get(const std::filesystem::path&); - void anm2_snapshot(const std::string& message); - void tracks_snapshot(const std::string& message, const std::set&); - void frames_snapshot(const std::string& message, const std::set&); - void regions_snapshot(const std::string& message, int, const std::set&); - void textures_snapshot(const std::string& message); - void anm2_textures_snapshot(const std::string& message); void undo(); void redo(); bool is_able_to_undo(); bool is_able_to_redo(); }; - -#define DOCUMENT_EDIT(document, message, changeType, body) \ - { \ - document.anm2_snapshot(message); \ - body; \ - document.change(changeType); \ - } - -#define DOCUMENT_EDIT_PTR(document, message, changeType, body) \ - { \ - document->anm2_snapshot(message); \ - body; \ - document->change(changeType); \ - } - } diff --git a/src/imgui/documents.cpp b/src/imgui/documents.cpp index 398cfbd..d27f861 100644 --- a/src/imgui/documents.cpp +++ b/src/imgui/documents.cpp @@ -27,18 +27,18 @@ namespace anm2ed::imgui uint64_t documentId{}; }; -#define ANM2_DRAG_DROP_MERGE_PRESETS \ +#define ANM2_DRAG_DROP_MERGE_PRESETS \ X(FILE_MERGE_PRESET_MERGE_BY_NAME, BASIC_MERGE, TOOLTIP_MERGE_PRESET_MERGE_BY_NAME) \ - X(FILE_MERGE_PRESET_APPEND_AS_NEW, BASIC_APPEND, TOOLTIP_MERGE_PRESET_APPEND_AS_NEW) \ + X(FILE_MERGE_PRESET_APPEND_AS_NEW, BASIC_APPEND, TOOLTIP_MERGE_PRESET_APPEND_AS_NEW) \ X(FILE_MERGE_PRESET_REPLACE_MATCHING, BASIC_REPLACE, TOOLTIP_MERGE_PRESET_REPLACE_MATCHING) - constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[Document::FILE_MERGE_PRESET_COUNT] = { + constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_LABELS[FILE_MERGE_PRESET_COUNT] = { #define X(preset, label, tooltip) label, ANM2_DRAG_DROP_MERGE_PRESETS #undef X }; - constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[Document::FILE_MERGE_PRESET_COUNT] = { + constexpr StringType ANM2_DRAG_DROP_MERGE_PRESET_TOOLTIPS[FILE_MERGE_PRESET_COUNT] = { #define X(preset, label, tooltip) tooltip, ANM2_DRAG_DROP_MERGE_PRESETS #undef X @@ -47,13 +47,13 @@ namespace anm2ed::imgui #undef ANM2_DRAG_DROP_MERGE_PRESETS void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, - Document::FileMergePreset preset) + FileMergePreset preset) { - manager.command_push({manager.selected, - [paths, preset](Manager&, Document& document) + manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) { - document.anm2_snapshot(localize.get(EDIT_MERGE_ANM2)); - for (auto& path : paths) document.file_merge(path, preset); + document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANM2)); + for (auto& path : paths) + document.anm2.file_merge(path, document.directory_get(), preset); document.change(Document::ALL); }}); } @@ -70,8 +70,8 @@ namespace anm2ed::imgui order.reserve(manager.documents.size()); for (auto documentId : pendingDocumentTabIds) { - auto it = std::ranges::find_if(manager.documents, [documentId](const Document& document) - { return document.tabId == documentId; }); + auto it = std::ranges::find_if(manager.documents, + [documentId](const Document& document) { return document.tabId == documentId; }); if (it == manager.documents.end()) { pendingDocumentTabIds.clear(); @@ -115,7 +115,8 @@ namespace anm2ed::imgui index_remap(manager.selected); index_remap(manager.pendingSelected); index_remap(closeDocumentIndex); - for (auto& index : manager.selectionHistory) index_remap(index); + for (auto& index : manager.selectionHistory) + index_remap(index); for (auto& command : manager.commands) if (!command.runManager) index_remap(command.documentIndex); std::erase(manager.selectionHistory, -1); @@ -151,8 +152,8 @@ namespace anm2ed::imgui if (document.lastAutosaveTime > time::SECOND_M) { auto options = settings.anm2_options_get(); - manager.command_push({i, [options](Manager& manager, Document& document) - { manager.autosave(document, options); }}); + manager.command_push( + {i, [options](Manager& manager, Document& document) { manager.autosave(document, options); }}); } } } @@ -324,17 +325,11 @@ namespace anm2ed::imgui if (texture->write_png(savePath)) { closeDocument.spritesheet_hash_set_saved(id); - toasts.push( - std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); } else { - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), - std::make_format_args(id, pathString))); - logger.error(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); } } } @@ -350,12 +345,11 @@ namespace anm2ed::imgui if (ImGui::Button(localize.get(BASIC_NO), widgetSize)) { auto index = closeDocumentIndex; - manager.command_push({.runManager = - [index](Manager& manager) - { - manager.autosave_file_clear(index); - manager.close(index); - }}); + manager.command_push({.runManager = [index](Manager& manager) + { + manager.autosave_file_clear(index); + manager.close(index); + }}); close(); } @@ -389,7 +383,7 @@ namespace anm2ed::imgui manager.anm2DragDropPaths.clear(); manager.anm2DragDropPopup.close(); manager.anm2DragDropMergePopup.close(); - manager.anm2DragDropMergePreset = Document::FILE_MERGE_PRESET_MERGE_BY_NAME; + manager.anm2DragDropMergePreset = FILE_MERGE_PRESET_MERGE_BY_NAME; }; if (manager.anm2DragDropPaths.empty()) @@ -402,10 +396,9 @@ namespace anm2ed::imgui ImGuiWindowFlags_NoResize)) { auto document = manager.get(); - manager.anm2DragDropMergePreset = - std::clamp(manager.anm2DragDropMergePreset, 0, Document::FILE_MERGE_PRESET_COUNT - 1); + manager.anm2DragDropMergePreset = std::clamp(manager.anm2DragDropMergePreset, 0, FILE_MERGE_PRESET_COUNT - 1); - for (int preset = 0; preset < Document::FILE_MERGE_PRESET_COUNT; ++preset) + for (int preset = 0; preset < FILE_MERGE_PRESET_COUNT; ++preset) { ImGui::PushID(preset); ImGui::RadioButton(localize.get(ANM2_DRAG_DROP_MERGE_PRESET_LABELS[preset]), @@ -420,7 +413,7 @@ namespace anm2ed::imgui if (ImGui::Button(localize.get(BASIC_MERGE), widgetSize)) { auto paths = manager.anm2DragDropPaths; - auto preset = (Document::FileMergePreset)manager.anm2DragDropMergePreset; + auto preset = (FileMergePreset)manager.anm2DragDropMergePreset; anm2_drag_drop_merge_queue(manager, paths, preset); drag_drop_reset(); } @@ -452,11 +445,11 @@ namespace anm2ed::imgui : localize.get(LABEL_DOCUMENTS_OPEN_NEW))) { auto paths = manager.anm2DragDropPaths; - manager.command_push({.runManager = - [paths](Manager& manager) - { - for (auto& path : paths) manager.open(path); - }}); + manager.command_push({.runManager = [paths](Manager& manager) + { + for (auto& path : paths) + manager.open(path); + }}); drag_drop_reset(); } diff --git a/src/imgui/popup/item_properties.cpp b/src/imgui/popup/item_properties.cpp index 6421aae..777351b 100644 --- a/src/imgui/popup/item_properties.cpp +++ b/src/imgui/popup/item_properties.cpp @@ -195,8 +195,7 @@ namespace anm2ed::imgui::popup auto queuedAddItemSpritesheetID = addItemSpritesheetID; auto queuedAddItemIsShowRect = addItemIsShowRect; - manager.command_push({manager.selected, - [=](Manager&, Document& document) + manager.command_push({manager.selected, [=](Manager&, Document& document) { Element item{}; item.id = queuedAddItemID; @@ -204,12 +203,12 @@ namespace anm2ed::imgui::popup item.spritesheetId = queuedAddItemSpritesheetID; item.isShowRect = queuedAddItemIsShowRect; - document.anm2_snapshot(localize.get(EDIT_ADD_ITEM)); - auto addId = document.anm2.item_add((ItemType)queuedType, queuedAnimationIndex, item, - queuedInsertBeforeID, - (destination::Type)queuedDestination); + document.snapshots.anm2_push(localize.get(EDIT_ADD_ITEM)); + auto addId = + document.anm2.item_add((ItemType)queuedType, queuedAnimationIndex, item, + queuedInsertBeforeID, (destination::Type)queuedDestination); - document.anm2_change(Document::ITEMS); + document.change(Document::ITEMS); if (addId != -1) { diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index 2bcce91..8973488 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -38,9 +38,7 @@ namespace anm2ed::imgui auto path = request.path; auto options = request.options; - manager.command_push({.runManager = - [=](Manager& manager) - { manager.save(index, path, options); }}); + manager.command_push({.runManager = [=](Manager& manager) { manager.save(index, path, options); }}); } bool Taskbar::save_request(Manager& manager, Settings& settings, int index, const std::filesystem::path& path, @@ -145,11 +143,11 @@ namespace anm2ed::imgui if (dialog.is_selected(Dialog::ANM2_OPEN)) { auto paths = dialog.paths; - manager.command_push({.runManager = - [paths](Manager& manager) - { - for (auto& path : paths) manager.open(path); - }}); + manager.command_push({.runManager = [paths](Manager& manager) + { + for (auto& path : paths) + manager.open(path); + }}); dialog.reset(); } @@ -172,15 +170,13 @@ namespace anm2ed::imgui if (ImGui::MenuItem(localize.get(LABEL_SCAN_AND_SET_REGIONS), nullptr, false, document && hasRegions)) { - manager.command_push({manager.selected, - [](Manager&, Document& document) + manager.command_push({manager.selected, [](Manager&, Document& document) { - document.anm2_snapshot(localize.get(EDIT_SCAN_AND_SET_REGIONS)); - document.scan_and_set_regions(); + document.snapshots.anm2_push(localize.get(EDIT_SCAN_AND_SET_REGIONS)); + document.anm2.regions_scan(); document.change(Document::FRAMES); }}); - toasts.push(localize.get(TOAST_SCAN_AND_SET_REGIONS)); - logger.info(localize.get(TOAST_SCAN_AND_SET_REGIONS, anm2ed::ENGLISH)); + toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_WIZARD_SCAN_AND_SET_REGIONS)); @@ -284,19 +280,15 @@ namespace anm2ed::imgui auto queuedAnimationIndices = animationIndices; auto queuedFormat = settings.generateRegionNameFormat; - auto queuedMapping = isGenerateRegionsMapFrames ? Document::RegionFrameMapping::SET - : Document::RegionFrameMapping::PRESERVE; - manager.command_push({manager.selected, - [=](Manager&, Document& document) - { - if (queuedAnimationIndices.empty()) return; - document.anm2_snapshot(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); - if (document.regions_generate_from_animations(queuedAnimationIndices, queuedFormat, - queuedMapping)) - document.anm2_change(queuedMapping == Document::RegionFrameMapping::SET - ? Document::ALL - : Document::SPRITESHEETS); - }}); + auto queuedMapping = isGenerateRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; + manager.command_push( + {manager.selected, [=](Manager&, Document& document) + { + if (queuedAnimationIndices.empty()) return; + document.snapshots.anm2_push(localize.get(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS)); + if (document.anm2.regions_generate(queuedAnimationIndices, {}, queuedFormat, queuedMapping)) + document.change(queuedMapping == RegionFrameMapping::SET ? Document::ALL : Document::SPRITESHEETS); + }}); generateRegionsPopup.close(); } diff --git a/src/imgui/toast.hpp b/src/imgui/toast.hpp index 31dbdb5..e8c4f4d 100644 --- a/src/imgui/toast.hpp +++ b/src/imgui/toast.hpp @@ -1,8 +1,12 @@ #pragma once +#include #include #include +#include "log.hpp" +#include "strings.hpp" + namespace anm2ed::imgui { class Toast @@ -26,3 +30,19 @@ namespace anm2ed::imgui } extern anm2ed::imgui::Toasts toasts; + +namespace anm2ed +{ + template void toast_log(Level level, StringType type, Args&&... args) + { + auto format = [&](Language language) -> std::string + { + if constexpr (sizeof...(Args) == 0) + return localize.get(type, language); + else + return std::vformat(localize.get(type, language), std::make_format_args(args...)); + }; + toasts.push(format(localize.language)); + logger.write(level, format(ENGLISH)); + } +} diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index cef7684..708f30c 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -306,16 +306,11 @@ namespace anm2ed::imgui { if (!renderTempFrames.empty()) { - toasts.push(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES), std::make_format_args(pathString))); - logger.info(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::INFO, TOAST_EXPORT_RENDERED_FRAMES, pathString); } else { - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES_FAILED), std::make_format_args(pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_FRAMES_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_FRAMES_FAILED, pathString); } } else if (type == render::SPRITESHEET) @@ -328,16 +323,14 @@ namespace anm2ed::imgui if (renderTempFrames.empty()) { - toasts.push(localize.get(TOAST_SPRITESHEET_NO_FRAMES)); - logger.warning(localize.get(TOAST_SPRITESHEET_NO_FRAMES, anm2ed::ENGLISH)); + toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); } else { auto firstFrame = Texture(renderTempFrames.front()); if (firstFrame.size.x <= 0 || firstFrame.size.y <= 0 || firstFrame.pixels.empty()) { - toasts.push(localize.get(TOAST_SPRITESHEET_EMPTY)); - logger.error(localize.get(TOAST_SPRITESHEET_EMPTY, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); } else { @@ -368,16 +361,11 @@ namespace anm2ed::imgui Texture spritesheetTexture(spritesheet.data(), spritesheetSize); if (spritesheetTexture.write_png(path)) { - toasts.push(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET), std::make_format_args(pathString))); - logger.info(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::INFO, TOAST_EXPORT_SPRITESHEET, pathString); } else { - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET_FAILED), std::make_format_args(pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_SPRITESHEET_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_SPRITESHEET_FAILED, pathString); } } } @@ -398,16 +386,11 @@ namespace anm2ed::imgui if (animation_render(ffmpegPath, path, renderTempFrames, audioStream, (render::Type)type, renderFrameRate)) { - toasts.push(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION), std::make_format_args(pathString))); - logger.info(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::INFO, TOAST_EXPORT_RENDERED_ANIMATION, pathString); } else { - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); } } @@ -791,10 +774,7 @@ namespace anm2ed::imgui } auto pathString = path::to_utf8(settings.renderPath); - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); manager.isRecording = false; manager.isRecordingStart = false; renderFrameIndex = 0; @@ -1240,10 +1220,7 @@ namespace anm2ed::imgui auto render_capture_fail = [&]() { auto pathString = path::to_utf8(settings.renderPath); - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED), std::make_format_args(pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); if (renderType != render::PNGS) render_temp_cleanup(renderTempDirectory, renderTempFrames); renderFrameSoundIDs.clear(); if (isRenderPreviewOverridden) @@ -1407,7 +1384,7 @@ namespace anm2ed::imgui { auto queuedFrameReferences = selectedFrameReferences; manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) - { document.frames_snapshot(localize.get(message), queuedFrameReferences); }}); + { document.snapshots.frames_push(localize.get(message), queuedFrameReferences); }}); }; auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { @@ -1450,7 +1427,7 @@ namespace anm2ed::imgui auto frames_changed = [&]() { manager.command_push( - {manager.selected, [](Manager&, Document& document) { document.anm2_change(Document::FRAMES); }}); + {manager.selected, [](Manager&, Document& document) { document.change(Document::FRAMES); }}); }; auto null_rect_change = [&](vec2 topLeft, vec2 rectSize) { diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 9bfa4cb..0bf772e 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -49,9 +49,9 @@ namespace anm2ed::imgui auto item = document.anm2.element_get(itemReference); if (!frame) return; - document.frames_snapshot(localize.get(message), {queuedReference}); + document.snapshots.frames_push(localize.get(message), {queuedReference}); behavior(document, *frame, item, queuedReference); - document.anm2_change(Document::FRAMES); + document.change(Document::FRAMES); }}); }; @@ -70,9 +70,9 @@ namespace anm2ed::imgui if (!frame) return; if (state == edit::START) - document.frames_snapshot(localize.get(message), {queuedReference}); + document.snapshots.frames_push(localize.get(message), {queuedReference}); behavior(document, *frame, item, queuedReference); - if (state == edit::END) document.anm2_change(Document::FRAMES); + if (state == edit::END) document.change(Document::FRAMES); }}); }; diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index 50e689d..643564f 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -124,57 +124,20 @@ namespace anm2ed::imgui void shader_uniform_config_save(Document& document, Element& shaderElement, const resource::shader::Uniform& uniform) { - auto config = shader_uniform_get(shaderElement, uniform.name); - if (!config) - { - config = &shaderElement.children.emplace_back(element_make(ElementType::UNIFORM)); - config->name = uniform.name; - } - - config->binding = std::string(resource::shader::uniform_binding_value_get(uniform.binding)); - config->value = resource::shader::uniform_value_string_get(uniform); - if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) - { - for (int index = 0; index < (int)uniform.components.size(); ++index) - { - auto component = shader_uniform_component_get(*config, index); - if (!component) - { - component = &config->children.emplace_back(element_make(ElementType::COMPONENT)); - component->index = index; - } - component->binding = - std::string(resource::shader::uniform_binding_value_get(uniform.components[index].binding)); - component->value = std::format("{:.6g}", uniform.components[index].value); - } - } - else - std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; }); + resource::shader::uniform_config_save(shaderElement, uniform); document.change(Document::SHADERS); } - int shader_uniform_component_count_get(resource::shader::UniformValueType type) - { - if (type == resource::shader::UNIFORM_VALUE_VEC2) return 2; - if (type == resource::shader::UNIFORM_VALUE_VEC3) return 3; - if (type == resource::shader::UNIFORM_VALUE_VEC4) return 4; - return 0; - } - void shader_uniform_components_from_value_set(resource::shader::Uniform& uniform) { - uniform.components[0].value = uniform.value.x; - uniform.components[1].value = uniform.value.y; - uniform.components[2].value = uniform.value.z; - uniform.components[3].value = uniform.value.w; + for (int i = 0; i < (int)uniform.components.size(); ++i) + uniform.components[i].value = uniform.value[i]; } void shader_uniform_value_from_components_set(resource::shader::Uniform& uniform) { - uniform.value.x = uniform.components[0].value; - uniform.value.y = uniform.components[1].value; - uniform.value.z = uniform.components[2].value; - uniform.value.w = uniform.components[3].value; + for (int i = 0; i < (int)uniform.components.size(); ++i) + uniform.value[i] = uniform.components[i].value; } bool shader_uniform_value_update(resource::shader::Uniform& uniform) @@ -227,7 +190,7 @@ namespace anm2ed::imgui { bool isChanged{}; constexpr const char* labels[] = {"X", "Y", "Z", "W"}; - auto componentCount = shader_uniform_component_count_get(uniform.valueType); + auto componentCount = resource::shader::UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; for (int index = 0; index < componentCount; ++index) { @@ -328,12 +291,7 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { auto document = manager.get(); - if (!document) - { - ImGui::End(); - return; - } - auto shaders = document->anm2.element_get(ElementType::SHADERS); + auto shaders = document ? document->anm2.element_get(ElementType::SHADERS) : nullptr; if (!shaders) { ImGui::End(); @@ -354,12 +312,12 @@ namespace anm2ed::imgui shader.id = element_child_next_id_get(*shaders, ElementType::SHADER); shader.name = localize.get(TEXT_NEW_SHADER); - document.anm2_snapshot(localize.get(EDIT_ADD_SHADER)); + document.snapshots.anm2_push(localize.get(EDIT_ADD_SHADER)); shaders->children.push_back(shader); document.shader.selection = {shader.id}; document.shader.reference = shader.id; newElementId = shader.id; - document.anm2_change(Document::SHADERS); + document.change(Document::SHADERS); }}); }; @@ -372,7 +330,7 @@ namespace anm2ed::imgui auto unused = document.anm2.element_unused(ElementType::SHADER); if (unused.empty()) return; - document.anm2_snapshot(localize.get(EDIT_REMOVE_UNUSED_SHADERS)); + document.snapshots.anm2_push(localize.get(EDIT_REMOVE_UNUSED_SHADERS)); for (auto id : unused) { element_child_id_erase(*shaders, ElementType::SHADER, id); @@ -380,7 +338,7 @@ namespace anm2ed::imgui if (document.shader.reference == id) document.shader.reference = -1; if (popupShaderId == id) propertiesPopup.close(); } - document.anm2_change(Document::SHADERS); + document.change(Document::SHADERS); }}); }; diff --git a/src/imgui/window/spritesheet_editor.cpp b/src/imgui/window/spritesheet_editor.cpp index 814bd80..bc50926 100644 --- a/src/imgui/window/spritesheet_editor.cpp +++ b/src/imgui/window/spritesheet_editor.cpp @@ -238,7 +238,8 @@ namespace anm2ed::imgui auto spritesheetModel = math::quad_model_get(viewTexture->size); auto spritesheetTransform = transform * spritesheetModel; - if (baseTexture && baseTexture->is_valid()) texture_render(shaderTexture, baseTexture->id, spritesheetTransform); + if (baseTexture && baseTexture->is_valid()) + texture_render(shaderTexture, baseTexture->id, spritesheetTransform); if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); @@ -431,9 +432,8 @@ namespace anm2ed::imgui { auto message = std::string(localize.get(messageType)); auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, - [message, queuedFrameReferences](Manager&, Document& document) - { document.frames_snapshot(message, queuedFrameReferences); }}); + manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) + { document.snapshots.frames_push(message, queuedFrameReferences); }}); }; auto region_snapshot_push = [&](StringType messageType, const std::set& regionIds) { @@ -442,42 +442,41 @@ namespace anm2ed::imgui auto queuedRegionIds = regionIds; manager.command_push({manager.selected, [message, queuedSpritesheet, queuedRegionIds](Manager&, Document& document) - { document.regions_snapshot(message, queuedSpritesheet, queuedRegionIds); }}); + { document.snapshots.regions_push(message, queuedSpritesheet, queuedRegionIds); }}); }; auto texture_snapshot_push = [&](StringType messageType) { auto message = std::string(localize.get(messageType)); - manager.command_push( - {manager.selected, [message](Manager&, Document& document) { document.textures_snapshot(message); }}); + manager.command_push({manager.selected, [message](Manager&, Document& document) + { document.snapshots.textures_push(message); }}); }; auto document_change_push = [&](Document::ChangeType changeType) { manager.command_push( - {manager.selected, [changeType](Manager&, Document& document) { document.anm2_change(changeType); }}); + {manager.selected, [changeType](Manager&, Document& document) { document.change(changeType); }}); }; auto frame_change_apply_to = [&](const std::set& frameReferences, FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { auto queuedFrameReferences = frameReferences; - manager.command_push( - {manager.selected, [=](Manager&, Document& document) - { - std::map> groupedFrames{}; - for (auto frameReference : queuedFrameReferences) - { - auto itemReference = frameReference; - itemReference.frameIndex = -1; - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + manager.command_push({manager.selected, [=](Manager&, Document& document) + { + std::map> groupedFrames{}; + for (auto frameReference : queuedFrameReferences) + { + auto itemReference = frameReference; + itemReference.frameIndex = -1; + groupedFrames[itemReference].insert(frameReference.frameIndex); + } - for (auto& [itemReference, itemFrames] : groupedFrames) - { - auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference); - if (!item) continue; - frames_change(*item, frameChange, itemType, changeType, itemFrames); - } - }}); + for (auto& [itemReference, itemFrames] : groupedFrames) + { + auto itemType = static_cast(itemReference.itemType); + auto item = document.anm2.element_get(itemReference); + if (!item) continue; + frames_change(*item, frameChange, itemType, changeType, itemFrames); + } + }}); }; auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { frame_change_apply_to(selectedFrameReferences, frameChange, changeType); }; @@ -486,29 +485,28 @@ namespace anm2ed::imgui { auto queuedReference = editReference; auto queuedFrameReferences = frameReferences; - manager.command_push( - {manager.selected, [=](Manager&, Document& document) - { - if (queuedReference.frameIndex < 0) return; - auto frame = document.anm2.element_get(queuedReference); - if (!frame) return; + manager.command_push({manager.selected, [=](Manager&, Document& document) + { + if (queuedReference.frameIndex < 0) return; + auto frame = document.anm2.element_get(queuedReference); + if (!frame) return; - std::map> groupedFrames{}; - for (auto frameReference : queuedFrameReferences) - { - auto itemReference = frameReference; - itemReference.frameIndex = -1; - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + std::map> groupedFrames{}; + for (auto frameReference : queuedFrameReferences) + { + auto itemReference = frameReference; + itemReference.frameIndex = -1; + groupedFrames[itemReference].insert(frameReference.frameIndex); + } - for (auto& [itemReference, itemFrames] : groupedFrames) - { - auto itemType = static_cast(itemReference.itemType); - auto item = document.anm2.element_get(itemReference); - if (!item) continue; - frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames); - } - }}); + for (auto& [itemReference, itemFrames] : groupedFrames) + { + auto itemType = static_cast(itemReference.itemType); + auto item = document.anm2.element_get(itemReference); + if (!item) continue; + frames_change(*item, frameChangeGet(*frame), itemType, changeType, itemFrames); + } + }}); }; auto frame_crop_normalize_apply_to = [&](const std::set& frameReferences, bool isSnap, ivec2 snapGridSize, ivec2 snapGridOffset) @@ -639,8 +637,7 @@ namespace anm2ed::imgui { auto queuedSpritesheet = referenceSpritesheet; manager.command_push( - {manager.selected, [=](Manager&, Document& document) - { document.texture_change(queuedSpritesheet); }}); + {manager.selected, [=](Manager&, Document& document) { document.texture_change(queuedSpritesheet); }}); }; auto region_selection_set = [&](int id) @@ -808,7 +805,8 @@ namespace anm2ed::imgui if (isEnd) document_change_push(Document::FRAMES); break; case tool::CROP: - if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && !regionSelection.empty()) + if ((isRegionEditTarget || isRegionInUse || selectedFrameToolReferences.empty()) && + !regionSelection.empty()) { if (!spritesheet || regionSelection.empty()) break; if (isBegin) region_snapshot_push(EDIT_REGION_CROP, regionSelection); @@ -1022,8 +1020,9 @@ namespace anm2ed::imgui actions_undo_redo_add(actions, manager, document); actions.separator(); actions.add(ACTION_CENTER_VIEW, []() { return true; }, center_view); - actions.add(ACTION_FIT_VIEW, [&]() - { return (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid()); }, fit_view); + actions.add( + ACTION_FIT_VIEW, + [&]() { return (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid()); }, fit_view); actions.separator(); actions.add(ACTION_ZOOM_IN, []() { return true; }, zoom_in); actions.add(ACTION_ZOOM_OUT, []() { return true; }, zoom_out); diff --git a/src/imgui/window/timeline/commands.cpp b/src/imgui/window/timeline/commands.cpp index cb87467..d586cf1 100644 --- a/src/imgui/window/timeline/commands.cpp +++ b/src/imgui/window/timeline/commands.cpp @@ -83,9 +83,7 @@ namespace anm2ed::imgui return -1; }; track_container_get = [&](int type) - { - return animation ? child_first_get(*animation, container_type_get(type)) : nullptr; - }; + { return animation ? child_first_get(*animation, container_type_get(type)) : nullptr; }; track_group_get = [&](int type, int groupId) { auto container = track_container_get(type); @@ -98,9 +96,7 @@ namespace anm2ed::imgui return !group || group->isVisible; }; row_group_get = [&](const TimelineItemRow& row) -> Element* - { - return row.isGroup ? track_group_get(row.type, row.id) : nullptr; - }; + { return row.isGroup ? track_group_get(row.type, row.id) : nullptr; }; group_items_count_get = [&](int type, int groupId) { auto container = track_container_get(type); @@ -114,8 +110,8 @@ namespace anm2ed::imgui command_animation_get = [](Document& document, int animationIndex) { return document.anm2.element_get(ElementType::ANIMATION, animationIndex); }; - command_item_get = [](Document& document, int animationIndex, int type, int id, int groupType = NONE, - int groupId = -1) + command_item_get = + [](Document& document, int animationIndex, int type, int id, int groupType = NONE, int groupId = -1) { auto animation = document.anm2.element_get(ElementType::ANIMATION, animationIndex); return animation ? animation_item_get(*animation, static_cast(type), id, groupType, groupId) : nullptr; @@ -134,8 +130,7 @@ namespace anm2ed::imgui { return document.anm2.element_get(ElementType::LAYER_ELEMENT, id); }; command_spritesheet_get = [](Document& document, int id) { return document.anm2.element_get(ElementType::SPRITESHEET, id); }; - command_info_get = [](Document& document) - { return element_first_get(document.anm2.root, ElementType::INFO); }; + command_info_get = [](Document& document) { return element_first_get(document.anm2.root, ElementType::INFO); }; item_reference_get = [&](int type, int id, int groupType = NONE, int groupId = -1) { return Reference{reference.animationIndex, type, id, -1, groupType, groupId}; }; item_reference_from_frame_get = [](Reference frameReference) @@ -211,8 +206,8 @@ namespace anm2ed::imgui targetDocument.frame_references_set(std::move(selection)); frames_selection_sync_for(targetDocument); }; - frame_selection_range_set_for = [&](Document& targetDocument, Reference firstReference, - Reference lastReference, bool isAdditive) -> bool + frame_selection_range_set_for = [&](Document& targetDocument, Reference firstReference, Reference lastReference, + bool isAdditive) -> bool { group_selection_reset_for(targetDocument); targetDocument.editTarget = Document::EditTarget::FRAME; @@ -243,8 +238,7 @@ namespace anm2ed::imgui frames_selection_sync_for(targetDocument); return true; }; - all_frame_references_for_items_get = [&]() - { return document.selected_item_frame_references_get(); }; + all_frame_references_for_items_get = [&]() { return document.selected_item_frame_references_get(); }; is_frame_copy_item = [](const Reference& itemReference) { return itemReference.itemType == ROOT || itemReference.itemType == LAYER || itemReference.itemType == NULL_; }; copy_frame_references_get = [&]() @@ -334,8 +328,8 @@ namespace anm2ed::imgui }; command_push = [&](auto run) { - manager.command_push({manager.selected, - [run](Manager& manager, Document& document) mutable { run(manager, document); }}); + manager.command_push( + {manager.selected, [run](Manager& manager, Document& document) mutable { run(manager, document); }}); }; track_references_from_frame_references_get = [](std::set frameReferences) { @@ -351,56 +345,51 @@ namespace anm2ed::imgui { auto message = std::string(localize.get(messageType)); auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, - [message, queuedTrackReferences](Manager&, Document& document) - { document.tracks_snapshot(message, queuedTrackReferences); }}); + manager.command_push({manager.selected, [message, queuedTrackReferences](Manager&, Document& document) + { document.snapshots.tracks_push(message, queuedTrackReferences); }}); }; frames_snapshot_command_push = [&](StringType messageType, const std::set& frameReferences) { auto message = std::string(localize.get(messageType)); auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, - [message, queuedFrameReferences](Manager&, Document& document) - { document.frames_snapshot(message, queuedFrameReferences); }}); + manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) + { document.snapshots.frames_push(message, queuedFrameReferences); }}); }; frames_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& frameReferences, auto run) + const std::set& frameReferences, auto run) { auto message = std::string(localize.get(messageType)); auto queuedFrameReferences = frameReferences; - manager.command_push({manager.selected, - [=, this](Manager& manager, Document& document) mutable + manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable { (void)changeType; - document.frames_snapshot(message, queuedFrameReferences); + document.snapshots.frames_push(message, queuedFrameReferences); run(manager, document); - document.anm2_change(changeType); + document.change(changeType); }}); }; tracks_edit_command_push = [&](StringType messageType, Document::ChangeType changeType, - const std::set& trackReferences, auto run) + const std::set& trackReferences, auto run) { auto message = std::string(localize.get(messageType)); auto queuedTrackReferences = trackReferences; - manager.command_push({manager.selected, - [=, this](Manager& manager, Document& document) mutable + manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable { (void)changeType; - document.tracks_snapshot(message, queuedTrackReferences); + document.snapshots.tracks_push(message, queuedTrackReferences); run(manager, document); - document.anm2_change(changeType); + document.change(changeType); }}); }; edit_command_push = [&](StringType messageType, Document::ChangeType changeType, auto run) { auto message = std::string(localize.get(messageType)); - manager.command_push({manager.selected, - [=, this](Manager& manager, Document& document) mutable + manager.command_push({manager.selected, [=, this](Manager& manager, Document& document) mutable { (void)changeType; - document.anm2_snapshot(message); + document.snapshots.anm2_push(message); run(manager, document); - document.anm2_change(changeType); + document.change(changeType); }}); }; type_color_base_vec = [&](int type) @@ -435,15 +424,13 @@ namespace anm2ed::imgui frameBorderColor = isLightTheme ? FRAME_BORDER_COLOR_LIGHT : FRAME_BORDER_COLOR_DARK; frameBorderColorReferenced = isLightTheme ? FRAME_BORDER_COLOR_REFERENCED_LIGHT : FRAME_BORDER_COLOR_REFERENCED_DARK; - frameMultipleOverlayColor = - isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; + frameMultipleOverlayColor = isLightTheme ? FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT : FRAME_MULTIPLE_OVERLAY_COLOR_DARK; textMultipleColor = isLightTheme ? TEXT_MULTIPLE_COLOR_LIGHT : TEXT_MULTIPLE_COLOR_DARK; playheadLineColor = isLightTheme ? PLAYHEAD_LINE_COLOR_LIGHT : PLAYHEAD_LINE_COLOR_DARK; playheadIconTint = isLightTheme ? PLAYHEAD_ICON_TINT_LIGHT : iconTintDefault; timelineBackgroundColor = isLightTheme ? TIMELINE_BACKGROUND_COLOR_LIGHT : ImGui::GetStyleColorVec4(ImGuiCol_Header); - timelinePlayheadRectColor = - isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; + timelinePlayheadRectColor = isLightTheme ? TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT : TIMELINE_PLAYHEAD_RECT_COLOR_DARK; timelineTickColor = isLightTheme ? TIMELINE_TICK_COLOR_LIGHT : frameBorderColor; itemTextColor = isLightTheme ? ITEM_TEXT_COLOR_LIGHT : ITEM_TEXT_COLOR_DARK; @@ -456,10 +443,7 @@ namespace anm2ed::imgui ImGui::GetColorU32(tint)); }; - frames_selection_set_reference = [&]() - { - frames_selection_set_reference_for(document); - }; + frames_selection_set_reference = [&]() { frames_selection_set_reference_for(document); }; playback_stop = [&]() { @@ -472,57 +456,56 @@ namespace anm2ed::imgui { auto targetReference = reference; auto targetFrameTime = document.frameTime; - if (!animation || !command_item_reference_get(document, targetReference)) - return; + if (!animation || !command_item_reference_get(document, targetReference)) return; tracks_edit_command_push(EDIT_INSERT_FRAME, Document::FRAMES, {targetReference}, [=, this](Manager&, Document& document) mutable { - auto animation = command_animation_get(document, targetReference.animationIndex); - auto item = command_item_reference_get(document, targetReference); - if (!animation || !item) return; + auto animation = command_animation_get(document, targetReference.animationIndex); + auto item = command_item_reference_get(document, targetReference); + if (!animation || !item) return; - auto newReference = targetReference; + auto newReference = targetReference; - if (targetReference.itemType == TRIGGER) - { - for (auto& trigger : item->children) - if (targetFrameTime == trigger.atFrame) return; + if (targetReference.itemType == TRIGGER) + { + for (auto& trigger : item->children) + if (targetFrameTime == trigger.atFrame) return; - auto addFrame = element_make(ElementType::TRIGGER); - addFrame.atFrame = targetFrameTime; - item->children.push_back(addFrame); - frames_sort_by_at_frame(*item); - newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); - } - else - { - auto frame = command_frame_get(document, targetReference); - auto framesCount = item_frames_count(item); - if (frame) - { - auto addFrame = *frame; - auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, addFrame); - newReference.frameIndex = insertIndex; - } - else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) - { - item->children.emplace_back(*lastFrame); - newReference.frameIndex = framesCount; - } - else - { - item->children.emplace_back(element_make(ElementType::FRAME)); - newReference.frameIndex = 0; - } - } + auto addFrame = element_make(ElementType::TRIGGER); + addFrame.atFrame = targetFrameTime; + item->children.push_back(addFrame); + frames_sort_by_at_frame(*item); + newReference.frameIndex = frame_index_from_at_frame_get(*item, addFrame.atFrame); + } + else + { + auto frame = command_frame_get(document, targetReference); + auto framesCount = item_frames_count(item); + if (frame) + { + auto addFrame = *frame; + auto insertIndex = std::clamp(targetReference.frameIndex + 1, 0, framesCount); + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, addFrame); + newReference.frameIndex = insertIndex; + } + else if (auto lastFrame = track_frame_get(*item, framesCount - 1)) + { + item->children.emplace_back(*lastFrame); + newReference.frameIndex = framesCount; + } + else + { + item->children.emplace_back(element_make(ElementType::FRAME)); + newReference.frameIndex = 0; + } + } - document.reference = newReference; - frames_selection_set_reference_for(document); - if (newReference.itemType != TRIGGER) - document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); + document.reference = newReference; + frames_selection_set_reference_for(document); + if (newReference.itemType != TRIGGER) + document.frameTime = frame_time_from_index_get(*item, newReference.frameIndex); }); }; @@ -572,81 +555,79 @@ namespace anm2ed::imgui frames_duplicate = [&]() { auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); if (selectedFrames.empty()) return; auto trackReferences = track_references_from_frame_references_get(selectedFrames); tracks_edit_command_push(EDIT_DUPLICATE_FRAMES, Document::FRAMES, trackReferences, [=, this](Manager&, Document& document) mutable { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + std::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{}; + std::set duplicatedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; - std::vector validIndices{}; - std::vector duplicatedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - duplicatedFrames.push_back(*frame); - } - if (validIndices.empty()) continue; + std::vector validIndices{}; + std::vector duplicatedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + duplicatedFrames.push_back(*frame); + } + if (validIndices.empty()) continue; - auto insertIndex = validIndices.back() + 1; - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(duplicatedFrames.begin()), - std::make_move_iterator(duplicatedFrames.end())); + auto insertIndex = validIndices.back() + 1; + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, + std::make_move_iterator(duplicatedFrames.begin()), + std::make_move_iterator(duplicatedFrames.end())); - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - duplicatedSelection.insert(targetReference); - auto sourceReference = itemReference; - sourceReference.frameIndex = validIndices[offset]; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + duplicatedSelection.insert(targetReference); + auto sourceReference = itemReference; + sourceReference.frameIndex = validIndices[offset]; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } - if (duplicatedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); - document.frame_references_set(std::move(duplicatedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; + if (duplicatedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *duplicatedSelection.begin(); + document.frame_references_set(std::move(duplicatedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; }); }; is_frames_reverse_available = [&](std::set selectedFrames) { std::map counts{}; - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); for (auto frameReference : selectedFrames) { auto itemReference = item_reference_from_frame_get(frameReference); @@ -658,81 +639,80 @@ namespace anm2ed::imgui frames_reverse = [&]() { auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); if (!is_frames_reverse_available(selectedFrames)) return; auto trackReferences = track_references_from_frame_references_get(selectedFrames); tracks_edit_command_push(EDIT_REVERSE_FRAMES, Document::FRAMES, trackReferences, [=, this](Manager&, Document& document) mutable { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + std::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{}; + std::set reversedSelection{}; + auto newReference = document.reference; + bool isReferenceSet{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item || indices.size() < 2) continue; + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item || indices.size() < 2) continue; - std::vector validIndices{}; - std::vector reversedFrames{}; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame) continue; - validIndices.push_back(i); - reversedFrames.push_back(std::move(*frame)); - } - if (validIndices.size() < 2) continue; + std::vector validIndices{}; + std::vector reversedFrames{}; + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame) continue; + validIndices.push_back(i); + reversedFrames.push_back(std::move(*frame)); + } + if (validIndices.size() < 2) continue; - auto insertIndex = validIndices.front(); - for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*item, *it); - if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); - } + auto insertIndex = validIndices.front(); + for (auto it = validIndices.rbegin(); it != validIndices.rend(); ++it) + { + auto childIndex = item_frame_child_index_get(*item, *it); + if (childIndex != -1) item->children.erase(item->children.begin() + childIndex); + } - std::ranges::reverse(reversedFrames); - auto childIndex = item_frame_insert_index_get(*item, insertIndex); - item->children.insert(item->children.begin() + childIndex, - std::make_move_iterator(reversedFrames.begin()), - std::make_move_iterator(reversedFrames.end())); + std::ranges::reverse(reversedFrames); + auto childIndex = item_frame_insert_index_get(*item, insertIndex); + item->children.insert(item->children.begin() + childIndex, + std::make_move_iterator(reversedFrames.begin()), + std::make_move_iterator(reversedFrames.end())); - for (int offset = 0; offset < (int)validIndices.size(); ++offset) - { - auto targetReference = itemReference; - targetReference.frameIndex = insertIndex + offset; - reversedSelection.insert(targetReference); - auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; - auto sourceReference = itemReference; - sourceReference.frameIndex = sourceIndex; - if (sourceReference == document.reference) - { - newReference = targetReference; - isReferenceSet = true; - } - } - } + for (int offset = 0; offset < (int)validIndices.size(); ++offset) + { + auto targetReference = itemReference; + targetReference.frameIndex = insertIndex + offset; + reversedSelection.insert(targetReference); + auto sourceIndex = validIndices[(int)validIndices.size() - 1 - offset]; + auto sourceReference = itemReference; + sourceReference.frameIndex = sourceIndex; + if (sourceReference == document.reference) + { + newReference = targetReference; + isReferenceSet = true; + } + } + } - if (reversedSelection.empty()) return; - document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); - document.frame_references_set(std::move(reversedSelection)); - if (auto item = command_item_reference_get(document, document.reference)) - document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; + if (reversedSelection.empty()) return; + document.reference = isReferenceSet ? newReference : *reversedSelection.begin(); + document.frame_references_set(std::move(reversedSelection)); + if (auto item = command_item_reference_get(document, document.reference)) + document.frameTime = frame_time_from_index_get(*item, document.reference.frameIndex); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; }); }; @@ -742,78 +722,74 @@ namespace anm2ed::imgui auto bakeInterval = settings.bakeInterval; auto isRoundScale = settings.bakeIsRoundScale; auto isRoundRotation = settings.bakeIsRoundRotation; - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); if (selectedFrames.empty()) return; auto trackReferences = track_references_from_frame_references_get(selectedFrames); tracks_edit_command_push(EDIT_BAKE_FRAMES, Document::FRAMES, trackReferences, [=, this](Manager&, Document& document) mutable { - std::map> groupedFrames{}; - for (auto frameReference : selectedFrames) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + std::map> groupedFrames{}; + for (auto frameReference : selectedFrames) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } - std::set bakedSelection{}; - for (auto& [itemReference, indices] : groupedFrames) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; + std::set bakedSelection{}; + for (auto& [itemReference, indices] : groupedFrames) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; - int insertedBefore = 0; - for (auto originalIndex : indices) - { - auto i = originalIndex + insertedBefore; - auto frame = track_frame_get(*item, i); - if (!frame) continue; + int insertedBefore = 0; + for (auto originalIndex : indices) + { + auto i = originalIndex + insertedBefore; + auto frame = track_frame_get(*item, i); + if (!frame) continue; - auto originalDuration = frame->duration; - frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); + auto originalDuration = frame->duration; + frame_bake(*item, i, bakeInterval, isRoundScale, isRoundRotation); - auto bakedCount = originalDuration <= FRAME_DURATION_MIN - ? 1 - : (int)std::ceil((float)originalDuration / bakeInterval); - for (int offset = 0; offset < bakedCount; ++offset) - { - auto frameReference = itemReference; - frameReference.frameIndex = i + offset; - bakedSelection.insert(frameReference); - } + auto bakedCount = originalDuration <= FRAME_DURATION_MIN + ? 1 + : (int)std::ceil((float)originalDuration / bakeInterval); + for (int offset = 0; offset < bakedCount; ++offset) + { + auto frameReference = itemReference; + frameReference.frameIndex = i + offset; + bakedSelection.insert(frameReference); + } - insertedBefore += bakedCount - 1; - } - } + insertedBefore += bakedCount - 1; + } + } - document.frame_references_set(std::move(bakedSelection)); - if (!document.frames.references.empty()) - { - frames_selection_sync_for(document); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - } - else - frames_selection_reset_for(document); + document.frame_references_set(std::move(bakedSelection)); + if (!document.frames.references.empty()) + { + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + } + else + frames_selection_reset_for(document); }); }; selected_root_frame_references_get = [&]() { auto selectedFrames = frame_references_for_current_get(); - std::erase_if(selectedFrames, - [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); + std::erase_if(selectedFrames, [](const Reference& frameReference) { return frameReference.itemType != ROOT; }); return selectedFrames; }; - item_references_for_bake_into_other_frames_get = [](const Document& targetDocument, - const Element& targetAnimation, - BakeIntoOtherFramesTarget target, bool isLayers, - bool isNulls) + item_references_for_bake_into_other_frames_get = [](const Document& targetDocument, const Element& targetAnimation, + BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls) { std::set result{}; auto animationIndex = targetDocument.reference.animationIndex; @@ -865,8 +841,8 @@ namespace anm2ed::imgui return !targetItems.empty(); }; - frame_root_transform_apply = [](Element& frame, const Element& rootFrame, bool isRoundScale, - bool isRoundRotation, bool isUseRootPivot) + frame_root_transform_apply = + [](Element& frame, const Element& rootFrame, bool isRoundScale, bool isRoundRotation, bool isUseRootPivot) { auto rootScale = math::percent_to_unit(rootFrame.scale); auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); @@ -875,8 +851,7 @@ namespace anm2ed::imgui auto cos = std::cos(radians); auto sin = std::sin(radians); - frame.position = - rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); + frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos); frame.scale *= rootScale; frame.rotation += rootFrame.rotation; frame.tint *= rootFrame.tint; @@ -902,139 +877,139 @@ namespace anm2ed::imgui document, *animation, target, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); auto trackReferences = track_references_from_frame_references_get(selectedRootFrames); trackReferences.insert(targetItems.begin(), targetItems.end()); - tracks_edit_command_push(EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, document.reference.animationIndex); - if (!animation) return; - auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); - for (auto rootReference : selectedRootFrames) - if (!is_same_item(rootReference, rootItemReference)) return; - auto root = command_item_reference_get(document, rootItemReference); - if (!root) return; + tracks_edit_command_push( + EDIT_BAKE_INTO_OTHER_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, document.reference.animationIndex); + if (!animation) return; + auto rootItemReference = item_reference_from_frame_get(*selectedRootFrames.begin()); + for (auto rootReference : selectedRootFrames) + if (!is_same_item(rootReference, rootItemReference)) return; + auto root = command_item_reference_get(document, rootItemReference); + if (!root) return; - std::vector spans{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); - spans.push_back({start, start + rootFrame->duration}); - } - if (spans.empty()) return; + std::vector spans{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + auto start = (int)frame_time_from_index_get(*root, rootReference.frameIndex); + spans.push_back({start, start + rootFrame->duration}); + } + if (spans.empty()) return; - auto targetItems = item_references_for_bake_into_other_frames_get( - document, *animation, target, isLayers, isNulls); - if (targetItems.empty()) return; + auto targetItems = + item_references_for_bake_into_other_frames_get(document, *animation, target, isLayers, isNulls); + if (targetItems.empty()) return; - for (auto itemReference : targetItems) - { - auto item = command_item_reference_get(document, itemReference); - if (!item) continue; + for (auto itemReference : targetItems) + { + auto item = command_item_reference_get(document, itemReference); + if (!item) continue; - if (isMatchRootInterpolation) - { - std::vector bakeIndices{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - bakeIndices.push_back(frameIndex); - break; - } - ++frameIndex; - } - for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) - frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); - } + if (isMatchRootInterpolation) + { + std::vector bakeIndices{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); + for (auto span : spans) + if (frameStart >= span.start && frameStart < span.end) + { + bakeIndices.push_back(frameIndex); + break; + } + ++frameIndex; + } + for (auto it = bakeIndices.rbegin(); it != bakeIndices.rend(); ++it) + frame_bake(*item, *it, FRAME_DURATION_MIN, isRoundScale, isRoundRotation); + } - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); - bool isInsideSpan{}; - for (auto span : spans) - if (frameStart >= span.start && frameStart < span.end) - { - isInsideSpan = true; - break; - } - if (!isInsideSpan) - { - ++frameIndex; - continue; - } - auto rootFrame = frame_generate(*root, (float)frameStart); - frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, - isUseRootPivot); - ++frameIndex; - } - } + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = (int)frame_time_from_index_get(*item, frameIndex); + bool isInsideSpan{}; + for (auto span : spans) + if (frameStart >= span.start && frameStart < span.end) + { + isInsideSpan = true; + break; + } + if (!isInsideSpan) + { + ++frameIndex; + continue; + } + auto rootFrame = frame_generate(*root, (float)frameStart); + frame_root_transform_apply(frame, rootFrame, isRoundScale, isRoundRotation, isUseRootPivot); + ++frameIndex; + } + } - std::set selectedRootFrameIndices{}; - for (auto rootReference : selectedRootFrames) - { - auto rootFrame = command_frame_get(document, rootReference); - if (!rootFrame) continue; - selectedRootFrameIndices.insert(rootReference.frameIndex); - } - if (selectedRootFrameIndices.empty()) return; + std::set selectedRootFrameIndices{}; + for (auto rootReference : selectedRootFrames) + { + auto rootFrame = command_frame_get(document, rootReference); + if (!rootFrame) continue; + selectedRootFrameIndices.insert(rootReference.frameIndex); + } + if (selectedRootFrameIndices.empty()) return; - std::vector rootFrames{}; - std::set defaultRootSelection{}; - int frameIndex{}; - int rewrittenFrameIndex{}; - int defaultDuration{}; - auto default_root_frame_push = [&]() - { - if (defaultDuration <= 0) return; - auto frame = element_make(ElementType::FRAME); - frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); - auto defaultRootReference = rootItemReference; - defaultRootReference.frameIndex = rewrittenFrameIndex; - defaultRootSelection.insert(defaultRootReference); - rootFrames.push_back(frame); - ++rewrittenFrameIndex; - defaultDuration = 0; - }; + std::vector rootFrames{}; + std::set defaultRootSelection{}; + int frameIndex{}; + int rewrittenFrameIndex{}; + int defaultDuration{}; + auto default_root_frame_push = [&]() + { + if (defaultDuration <= 0) return; + auto frame = element_make(ElementType::FRAME); + frame.duration = glm::max(defaultDuration, FRAME_DURATION_MIN); + auto defaultRootReference = rootItemReference; + defaultRootReference.frameIndex = rewrittenFrameIndex; + defaultRootSelection.insert(defaultRootReference); + rootFrames.push_back(frame); + ++rewrittenFrameIndex; + defaultDuration = 0; + }; - for (const auto& frame : root->children) - { - if (frame.type != ElementType::FRAME) - { - default_root_frame_push(); - rootFrames.push_back(frame); - continue; - } + 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(); + 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; - }); + root->children = std::move(rootFrames); + document.frame_references_set(std::move(defaultRootSelection)); + frames_selection_sync_for(document); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + }); }; frame_split = [&]() @@ -1045,41 +1020,41 @@ namespace anm2ed::imgui auto splitTime = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); if (targetReference.itemType == TRIGGER) return; - tracks_edit_command_push(EDIT_SPLIT_FRAME, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) mutable - { - if (targetReference.itemType == TRIGGER) return; + tracks_edit_command_push( + EDIT_SPLIT_FRAME, Document::FRAMES, {targetReference}, + [=, this](Manager&, Document& document) mutable + { + if (targetReference.itemType == TRIGGER) return; - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); + auto item = command_item_reference_get(document, targetReference); + auto frame = command_frame_get(document, targetReference); - if (!item || !frame) return; + if (!item || !frame) return; - auto originalDuration = frame->duration; - if (originalDuration <= 1) return; + auto originalDuration = frame->duration; + if (originalDuration <= 1) return; - auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); - int frameStart = (int)std::round(frameStartTime); - int firstDuration = splitTime - frameStart + 1; + auto frameStartTime = frame_time_from_index_get(*item, targetReference.frameIndex); + int frameStart = (int)std::round(frameStartTime); + int firstDuration = splitTime - frameStart + 1; - if (firstDuration <= 0 || firstDuration >= originalDuration) return; + if (firstDuration <= 0 || firstDuration >= originalDuration) return; - int secondDuration = originalDuration - firstDuration; - auto splitFrame = *frame; - splitFrame.duration = secondDuration; + int secondDuration = originalDuration - firstDuration; + auto splitFrame = *frame; + splitFrame.duration = secondDuration; - auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); - if (frame->interpolation != Interpolation::NONE && nextFrame) - frame_mix(splitFrame, *nextFrame, - interpolation_factor(frame->interpolation, - (float)firstDuration / (float)originalDuration)); + auto nextFrame = track_frame_get(*item, targetReference.frameIndex + 1); + if (frame->interpolation != Interpolation::NONE && nextFrame) + frame_mix(splitFrame, *nextFrame, + interpolation_factor(frame->interpolation, (float)firstDuration / (float)originalDuration)); - frame->duration = firstDuration; - auto insertIndex = item_frame_insert_index_get(*item, targetReference.frameIndex + 1); - item->children.insert(item->children.begin() + insertIndex, splitFrame); - document.reference = targetReference; - frames_selection_set_reference_for(document); - }); + frame->duration = firstDuration; + auto insertIndex = item_frame_insert_index_get(*item, targetReference.frameIndex + 1); + item->children.insert(item->children.begin() + insertIndex, splitFrame); + document.reference = targetReference; + frames_selection_set_reference_for(document); + }); }; reference_clear = [&]() @@ -1111,13 +1086,9 @@ namespace anm2ed::imgui .depth = depth}); }; auto group_row_push = [&](const Element& group, int type, int index) - { - rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); - }; + { rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); }; auto group_root_row_push = [&](const Element& group, int type) - { - rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); - }; + { rows.push_back({.type = ROOT, .id = -1, .rootGroupType = type, .rootGroupId = group.id, .depth = 1}); }; auto group_ids_get = [](const Element& container) { std::set result{}; @@ -1129,66 +1100,66 @@ namespace anm2ed::imgui rows.push_back({.type = ROOT}); if (auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) + { + auto groupIds = group_ids_get(*layerAnimations); + auto layer_track_push = [&](int groupId, int depth) { - auto groupIds = group_ids_get(*layerAnimations); - auto layer_track_push = [&](int groupId, int depth) + for (int j = (int)layerAnimations->children.size() - 1; j >= 0; --j) { - for (int j = (int)layerAnimations->children.size() - 1; j >= 0; --j) - { - auto& item = layerAnimations->children[j]; - if (item.type != ElementType::LAYER_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, LAYER, j, depth); - } - }; - - for (int i = (int)layerAnimations->children.size() - 1; i >= 0; --i) - { - auto& item = layerAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, LAYER, i); - if (item.isExpanded) - { - group_root_row_push(item, LAYER); - layer_track_push(item.id, 1); - } - } - else if (item.type == ElementType::LAYER_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, LAYER, i); + auto& item = layerAnimations->children[j]; + if (item.type != ElementType::LAYER_ANIMATION || item.groupId != groupId) continue; + if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, LAYER, j, depth); } + }; + + for (int i = (int)layerAnimations->children.size() - 1; i >= 0; --i) + { + auto& item = layerAnimations->children[i]; + if (item.type == ElementType::GROUP) + { + group_row_push(item, LAYER, i); + if (item.isExpanded) + { + group_root_row_push(item, LAYER); + layer_track_push(item.id, 1); + } + } + else if (item.type == ElementType::LAYER_ANIMATION && !groupIds.contains(item.groupId) && + (settings.timelineIsShowUnused || !item.children.empty())) + track_row_push(item, LAYER, i); } + } if (auto nullAnimations = child_first_get(*animation, ElementType::NULL_ANIMATIONS)) + { + auto groupIds = group_ids_get(*nullAnimations); + auto null_track_push = [&](int groupId, int depth) { - auto groupIds = group_ids_get(*nullAnimations); - auto null_track_push = [&](int groupId, int depth) + for (int j = 0; j < (int)nullAnimations->children.size(); ++j) { - for (int j = 0; j < (int)nullAnimations->children.size(); ++j) - { - auto& item = nullAnimations->children[j]; - if (item.type != ElementType::NULL_ANIMATION || item.groupId != groupId) continue; - if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, NULL_, j, depth); - } - }; - - for (int i = 0; i < (int)nullAnimations->children.size(); ++i) - { - auto& item = nullAnimations->children[i]; - if (item.type == ElementType::GROUP) - { - group_row_push(item, NULL_, i); - if (item.isExpanded) - { - group_root_row_push(item, NULL_); - null_track_push(item.id, 1); - } - } - else if (item.type == ElementType::NULL_ANIMATION && !groupIds.contains(item.groupId) && - (settings.timelineIsShowUnused || !item.children.empty())) - track_row_push(item, NULL_, i); + auto& item = nullAnimations->children[j]; + if (item.type != ElementType::NULL_ANIMATION || item.groupId != groupId) continue; + if (settings.timelineIsShowUnused || !item.children.empty()) track_row_push(item, NULL_, j, depth); } + }; + + for (int i = 0; i < (int)nullAnimations->children.size(); ++i) + { + auto& item = nullAnimations->children[i]; + if (item.type == ElementType::GROUP) + { + group_row_push(item, NULL_, i); + if (item.isExpanded) + { + group_root_row_push(item, NULL_); + null_track_push(item.id, 1); + } + } + else if (item.type == ElementType::NULL_ANIMATION && !groupIds.contains(item.groupId) && + (settings.timelineIsShowUnused || !item.children.empty())) + track_row_push(item, NULL_, i); } + } rows.push_back({.type = TRIGGER}); return rows; @@ -1200,8 +1171,7 @@ namespace anm2ed::imgui for (const auto& row : timeline_item_rows_get()) { if (row.isGroup) continue; - itemReferences.push_back( - {reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); + itemReferences.push_back({reference.animationIndex, row.type, row.id, -1, row.rootGroupType, row.rootGroupId}); } return itemReferences; }; @@ -1211,8 +1181,8 @@ namespace anm2ed::imgui row_reference_get = [&](const TimelineItemRow& row) { - return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, row.index, - row.rootGroupType, row.rootGroupId, row.isGroup}; + return TimelineRowReference{manager.selected, reference.animationIndex, row.type, row.id, + row.index, row.rootGroupType, row.rootGroupId, row.isGroup}; }; row_item_reference_get = [](const TimelineRowReference& row) @@ -1230,9 +1200,7 @@ namespace anm2ed::imgui }; is_group_selected = [&](const TimelineItemRow& row) - { - return document.groupReferences.contains(group_reference_get(row)); - }; + { return document.groupReferences.contains(group_reference_get(row)); }; is_row_selected = [&](const TimelineItemRow& row) { @@ -1335,9 +1303,8 @@ namespace anm2ed::imgui auto itemReferences = timeline_item_references_get(); if (itemReferences.empty()) return; - auto it = std::find_if( - itemReferences.begin(), itemReferences.end(), [&](const Reference& itemReference) - { return is_same_item(itemReference, reference); }); + auto it = std::find_if(itemReferences.begin(), itemReferences.end(), + [&](const Reference& itemReference) { return is_same_item(itemReference, reference); }); int index = direction > 0 ? 0 : (int)itemReferences.size() - 1; if (it != itemReferences.end()) index = (int)std::distance(itemReferences.begin(), it) + direction; @@ -1494,8 +1461,8 @@ namespace anm2ed::imgui }); }; - rows_move_to_row = [&](std::vector draggedRows, TimelineItemRow targetRow, - bool isDropAfter, bool isDropIntoGroup = false) + rows_move_to_row = [&](std::vector draggedRows, TimelineItemRow targetRow, bool isDropAfter, + bool isDropIntoGroup = false) { if (draggedRows.empty()) return; auto targetType = draggedRows.front().type; @@ -1509,128 +1476,125 @@ namespace anm2ed::imgui return; auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_MOVE_ITEMS, Document::ITEMS, - [=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - auto container = child_first_get(*animation, container_type_get(targetType)); - if (!container) return; - auto targetTrackType = track_type_get(targetType); + edit_command_push( + EDIT_MOVE_ITEMS, Document::ITEMS, + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + auto container = child_first_get(*animation, container_type_get(targetType)); + if (!container) return; + auto targetTrackType = track_type_get(targetType); - std::set draggedIds{}; - std::set draggedGroupIds{}; - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - draggedGroupIds.insert(draggedRow.id); - else - draggedIds.insert(draggedRow.id); - } + std::set draggedIds{}; + std::set draggedGroupIds{}; + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + draggedGroupIds.insert(draggedRow.id); + else + draggedIds.insert(draggedRow.id); + } - if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; + if (targetRow.groupId != -1 && draggedGroupIds.contains(targetRow.groupId)) return; - std::vector movedItems{}; - for (const auto& item : container->children) - { - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || - draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) movedItems.push_back(item); - } - if (movedItems.empty()) return; + std::vector movedItems{}; + for (const auto& item : container->children) + { + auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); + auto isDraggedTrack = + item.type == targetTrackType && + (draggedIds.contains(track_id_get(item, targetType)) || draggedGroupIds.contains(item.groupId)); + if (isDraggedGroup || isDraggedTrack) movedItems.push_back(item); + } + if (movedItems.empty()) return; - if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; + if (targetRow.isGroup && draggedGroupIds.contains(targetRow.id)) return; - auto row_index_get = [&](const TimelineItemRow& row) - { - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; - if (!row.isGroup && row.type == targetType && item.type == targetTrackType && - track_id_get(item, targetType) == row.id) - return i; - } - return -1; - }; - auto group_end_index_get = [&](int groupId) - { - int result = -1; - for (int i = 0; i < (int)container->children.size(); ++i) - { - auto& item = container->children[i]; - if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); - if (item.type == targetTrackType && item.groupId == groupId) - result = std::max(result, i); - } - return result; - }; + auto row_index_get = [&](const TimelineItemRow& row) + { + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (row.isGroup && item.type == ElementType::GROUP && item.id == row.id) return i; + if (!row.isGroup && row.type == targetType && item.type == targetTrackType && + track_id_get(item, targetType) == row.id) + return i; + } + return -1; + }; + auto group_end_index_get = [&](int groupId) + { + int result = -1; + for (int i = 0; i < (int)container->children.size(); ++i) + { + auto& item = container->children[i]; + if (item.type == ElementType::GROUP && item.id == groupId) result = std::max(result, i); + if (item.type == targetTrackType && item.groupId == groupId) result = std::max(result, i); + } + return result; + }; - int targetIndex = (int)container->children.size(); - if (targetRow.isGroup || targetRow.type == targetType) - { - auto rowIndex = row_index_get(targetRow); - if (rowIndex == -1) return; - if (targetRow.isGroup) - { - auto groupEndIndex = group_end_index_get(targetRow.id); - if (targetType == LAYER) - targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; - else - targetIndex = rowIndex + isDropAfter; - } - else - targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); - } + int targetIndex = (int)container->children.size(); + if (targetRow.isGroup || targetRow.type == targetType) + { + auto rowIndex = row_index_get(targetRow); + if (rowIndex == -1) return; + if (targetRow.isGroup) + { + auto groupEndIndex = group_end_index_get(targetRow.id); + if (targetType == LAYER) + targetIndex = isDropAfter ? rowIndex : groupEndIndex + 1; + else + targetIndex = rowIndex + isDropAfter; + } + else + targetIndex = rowIndex + (targetType == LAYER ? !isDropAfter : isDropAfter); + } - int removedBeforeTarget = 0; - for (int i = (int)container->children.size() - 1; i >= 0; --i) - { - auto& item = container->children[i]; - auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); - auto isDraggedTrack = item.type == targetTrackType && - (draggedIds.contains(track_id_get(item, targetType)) || - draggedGroupIds.contains(item.groupId)); - if (isDraggedGroup || isDraggedTrack) - { - if (i < targetIndex) ++removedBeforeTarget; - container->children.erase(container->children.begin() + i); - } - } + int removedBeforeTarget = 0; + for (int i = (int)container->children.size() - 1; i >= 0; --i) + { + auto& item = container->children[i]; + auto isDraggedGroup = item.type == ElementType::GROUP && draggedGroupIds.contains(item.id); + auto isDraggedTrack = + item.type == targetTrackType && + (draggedIds.contains(track_id_get(item, targetType)) || draggedGroupIds.contains(item.groupId)); + if (isDraggedGroup || isDraggedTrack) + { + if (i < targetIndex) ++removedBeforeTarget; + container->children.erase(container->children.begin() + i); + } + } - auto targetGroupId = -1; - if (targetRow.isGroup && isDropIntoGroup) - targetGroupId = targetRow.id; - else if (targetRow.type == targetType) - targetGroupId = targetRow.groupId; + auto targetGroupId = -1; + if (targetRow.isGroup && isDropIntoGroup) + targetGroupId = targetRow.id; + else if (targetRow.type == targetType) + targetGroupId = targetRow.groupId; - for (auto& item : movedItems) - if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) - item.groupId = targetGroupId; + for (auto& item : movedItems) + if (item.type == targetTrackType && !draggedGroupIds.contains(item.groupId)) item.groupId = targetGroupId; - targetIndex -= removedBeforeTarget; - targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); - container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), - movedItems.end()); + targetIndex -= removedBeforeTarget; + targetIndex = std::clamp(targetIndex, 0, (int)container->children.size()); + container->children.insert(container->children.begin() + targetIndex, movedItems.begin(), movedItems.end()); - document.items.references.clear(); - document.groupReferences.clear(); - for (const auto& draggedRow : draggedRows) - { - if (draggedRow.isGroup) - document.groupReferences.insert( - {draggedRow.animationIndex, draggedRow.type, draggedRow.id}); - else - document.items.references.insert(row_item_reference_get(draggedRow)); - } - if (!document.items.references.empty()) - document.reference = *document.items.references.begin(); - else - document.reference = {animationIndex}; - frames_selection_reset_for(document); - }); + document.items.references.clear(); + document.groupReferences.clear(); + for (const auto& draggedRow : draggedRows) + { + if (draggedRow.isGroup) + document.groupReferences.insert({draggedRow.animationIndex, draggedRow.type, draggedRow.id}); + else + document.items.references.insert(row_item_reference_get(draggedRow)); + } + if (!document.items.references.empty()) + document.reference = *document.items.references.begin(); + else + document.reference = {animationIndex}; + frames_selection_reset_for(document); + }); }; fit_animation_length = [&]() @@ -1653,8 +1617,8 @@ namespace anm2ed::imgui std::string clipboardString{}; for (auto frameReference : selectedFrames) { - auto item = item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, - frameReference.groupId); + auto item = + item_get(frameReference.itemType, frameReference.itemID, frameReference.groupType, frameReference.groupId); auto frame = item ? track_frame_get(*item, frameReference.frameIndex) : nullptr; if (!frame) continue; auto parentType = TYPE_TRACKS[frameReference.itemType]; @@ -1690,84 +1654,80 @@ namespace anm2ed::imgui if (clipboardString.empty()) return; auto targetHoveredTime = hoveredTime; auto message = std::string(localize.get(EDIT_PASTE_FRAMES)); - command_push([=, this](Manager&, Document& document) mutable - { - auto animation = command_animation_get(document, targetReference.animationIndex); - if (!animation) return; - if (auto item = command_item_reference_get(document, targetReference)) - { - document.tracks_snapshot(message, {targetReference}); - std::set indices{}; - std::string errorString{}; - int insertIndex = (int)item->children.size(); - std::set selectedIndices{}; - for (auto frameReference : selectedFrames) - if (is_same_item(frameReference, targetReference)) - selectedIndices.insert(frameReference.frameIndex); + command_push( + [=, this](Manager&, Document& document) mutable + { + auto animation = command_animation_get(document, targetReference.animationIndex); + if (!animation) return; + if (auto item = command_item_reference_get(document, targetReference)) + { + document.snapshots.tracks_push(message, {targetReference}); + std::set indices{}; + std::string errorString{}; + int insertIndex = (int)item->children.size(); + std::set selectedIndices{}; + for (auto frameReference : selectedFrames) + if (is_same_item(frameReference, targetReference)) selectedIndices.insert(frameReference.frameIndex); - if (!selectedIndices.empty()) - insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); - else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) - insertIndex = targetReference.frameIndex + 1; + if (!selectedIndices.empty()) + insertIndex = std::min((int)item->children.size(), *selectedIndices.rbegin() + 1); + else if (targetReference.frameIndex >= 0 && targetReference.frameIndex < (int)item->children.size()) + insertIndex = targetReference.frameIndex + 1; - auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; - if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) - { - if (targetReference.itemType != LAYER) - { - for (auto i : indices) - if (auto frame = track_frame_get(*item, i); frame) - { - frame->regionId = -1; - frame->crop = {}; - frame->size = {}; - frame->pivot = {}; - } - } - else if (targetReference.itemID != -1) - { - auto layer = command_layer_get(document, targetReference.itemID); - auto spritesheet = layer ? command_spritesheet_get(document, layer->spritesheetId) : nullptr; + auto start = targetReference.itemType == TRIGGER ? targetHoveredTime : insertIndex; + if (frames_deserialize(*item, clipboardString, start, indices, &errorString)) + { + if (targetReference.itemType != LAYER) + { + for (auto i : indices) + if (auto frame = track_frame_get(*item, i); frame) + { + frame->regionId = -1; + frame->crop = {}; + frame->size = {}; + frame->pivot = {}; + } + } + else if (targetReference.itemID != -1) + { + auto layer = command_layer_get(document, targetReference.itemID); + auto spritesheet = layer ? command_spritesheet_get(document, layer->spritesheetId) : nullptr; - for (auto i : indices) - { - auto frame = track_frame_get(*item, i); - if (!frame || frame->regionId == -1) continue; - auto region = - spritesheet ? child_id_get(*spritesheet, ElementType::REGION, frame->regionId) - : nullptr; - if (!region) frame->regionId = -1; - } - } + for (auto i : indices) + { + auto frame = track_frame_get(*item, i); + if (!frame || frame->regionId == -1) continue; + auto region = + spritesheet ? child_id_get(*spritesheet, ElementType::REGION, frame->regionId) : nullptr; + if (!region) frame->regionId = -1; + } + } - std::set pastedSelection{}; - for (auto i : indices) - { - auto pastedReference = targetReference; - pastedReference.frameIndex = i; - pastedSelection.insert(pastedReference); - } - document.reference = targetReference; - document.reference.frameIndex = *indices.begin(); - document.frame_references_set(std::move(pastedSelection)); - document.anm2_change(Document::FRAMES); - } - else - { - document.snapshots.pendingStep.reset(); - toasts.push( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); - logger.error(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, - anm2ed::ENGLISH), - errorString)); - } - } - else - { - toasts.push(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION)); - logger.warning(localize.get(TOAST_DESERIALIZE_FRAMES_NO_SELECTION, anm2ed::ENGLISH)); - } - }); + std::set pastedSelection{}; + for (auto i : indices) + { + auto pastedReference = targetReference; + pastedReference.frameIndex = i; + pastedSelection.insert(pastedReference); + } + document.reference = targetReference; + document.reference.frameIndex = *indices.begin(); + document.frame_references_set(std::move(pastedSelection)); + document.change(Document::FRAMES); + } + else + { + document.snapshots.pendingStep.reset(); + toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), errorString)); + logger.error( + std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), errorString)); + } + } + else + { + toast_log(Level::WARNING, TOAST_DESERIALIZE_FRAMES_NO_SELECTION); + } + }); }; context_menu = [&]() @@ -1795,28 +1755,29 @@ namespace anm2ed::imgui if (!spritesheet_get(spritesheetID)) return; auto settingsPtr = &settings; - command_push([=, this](Manager& manager, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame || frame->regionId != -1) return; - auto layer = command_layer_get(document, targetReference.itemID); - if (!layer) return; + command_push( + [=, this](Manager& manager, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame || frame->regionId != -1) return; + auto layer = command_layer_get(document, targetReference.itemID); + if (!layer) return; - auto spritesheetID = layer->spritesheetId; - if (!command_spritesheet_get(document, spritesheetID)) return; + auto spritesheetID = layer->spritesheetId; + if (!command_spritesheet_get(document, spritesheetID)) return; - auto region = element_make(ElementType::REGION); - region.crop = frame->crop; - region.size = frame->size; - region.pivot = frame->pivot; - region.origin = Origin::CUSTOM; + auto region = element_make(ElementType::REGION); + region.crop = frame->crop; + region.size = frame->size; + region.pivot = frame->pivot; + region.origin = Origin::CUSTOM; - document.spritesheet.reference = spritesheetID; - settingsPtr->windowIsRegions = true; - manager.makeRegionSpritesheetId = spritesheetID; - manager.makeRegion = region; - manager.isMakeRegionRequested = true; - }); + document.spritesheet.reference = spritesheetID; + settingsPtr->windowIsRegions = true; + manager.makeRegionSpritesheetId = spritesheetID; + manager.makeRegion = region; + manager.isMakeRegionRequested = true; + }); }; auto make_many_regions = [&]() @@ -1895,7 +1856,8 @@ namespace anm2ed::imgui actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, .shortcut = -1, .isEnabled = [=, this]() { return isMakeManyRegions || isMakeRegion; }, - .run = [&]() + .run = + [&]() { if (isMakeManyRegions) make_many_regions(); @@ -1977,10 +1939,8 @@ namespace anm2ed::imgui { auto animation = command_animation_get(document, targetAnimationIndex); auto container = - animation ? child_first_get(*animation, container_type_get(targetType)) - : nullptr; - auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) - : nullptr; + animation ? child_first_get(*animation, container_type_get(targetType)) : nullptr; + auto group = container ? child_id_get(*container, ElementType::GROUP, targetId) : nullptr; if (!group) return; group->name = targetName; }); @@ -2018,7 +1978,7 @@ namespace anm2ed::imgui selectedGroup = row_group_get(selectedGroupRow); } auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row) - { return row.type == LAYER || row.type == NULL_; }); + { return row.type == LAYER || row.type == NULL_; }); auto item_cut = [&]() { if (copyFrames.empty() || !isRemoveAvailable) return; @@ -2033,14 +1993,15 @@ namespace anm2ed::imgui Actions actions{}; actions_undo_redo_add(actions, manager, document); actions.separator(); - actions.add(ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, - [&]() - { - if (selectedGroup) - group_properties_open(selectedGroupRow, *selectedGroup); - else - item_base_properties_open(type, id); - }); + actions.add( + ACTION_PROPERTIES, [&]() { return selectedGroup || (item && (type == LAYER || type == NULL_)); }, + [&]() + { + if (selectedGroup) + group_properties_open(selectedGroupRow, *selectedGroup); + else + item_base_properties_open(type, id); + }); actions.add(ACTION_ADD, [&]() { return animation; }, [&]() { itemProperties.open(); }); actions.add(ACTION_REMOVE, [=, this]() { return isRemoveAvailable; }, [&]() { item_remove(); }); actions.add(ACTION_GROUP, [=, this]() { return !selectedGroupableItems.empty(); }, [&]() { item_group(); }); @@ -2056,7 +2017,5 @@ namespace anm2ed::imgui ImGui::PopStyleVar(2); }; - - } } diff --git a/src/imgui/window/timeline/frames.cpp b/src/imgui/window/timeline/frames.cpp index b637b73..8425f86 100644 --- a/src/imgui/window/timeline/frames.cpp +++ b/src/imgui/window/timeline/frames.cpp @@ -3,1133 +3,1130 @@ namespace anm2ed::imgui { void TimelineContext::frame_move_drag_clear() -{ - frameMoveDrag = {}; - frameSelectionLocked.clear(); - frameMoveDropType = NONE; - frameMoveDropItemID = -1; - frameMoveDropGroupType = NONE; - frameMoveDropGroupId = -1; - frameMoveDropIndex = -1; - isFrameMoveDropTarget = false; - } + { + frameMoveDrag = {}; + frameSelectionLocked.clear(); + frameMoveDropType = NONE; + frameMoveDropItemID = -1; + frameMoveDropGroupType = NONE; + frameMoveDropGroupId = -1; + frameMoveDropIndex = -1; + isFrameMoveDropTarget = false; + } - void TimelineContext::frames_move_to(int targetType, int targetID, int targetGroupType, int targetGroupId, int insertIndex) -{ - if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) return; - if (targetType == TRIGGER) return; + void TimelineContext::frames_move_to(int targetType, int targetID, int targetGroupType, int targetGroupId, + int insertIndex) + { + if (!frameMoveDrag.isActive || !animation || frameMoveDrag.animationIndex != reference.animationIndex) return; + if (targetType == TRIGGER) return; - auto drag = frameMoveDrag; - std::erase_if(drag.references, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); - if (drag.references.empty() && drag.frameIndex >= 0) - drag.references.push_back( - {drag.animationIndex, drag.type, drag.itemID, drag.frameIndex, drag.groupType, drag.groupId}); - std::erase_if(drag.references, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); - if (drag.references.empty()) return; + auto drag = frameMoveDrag; + std::erase_if(drag.references, [](const Reference& frameReference) + { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); + if (drag.references.empty() && drag.frameIndex >= 0) + drag.references.push_back( + {drag.animationIndex, drag.type, drag.itemID, drag.frameIndex, drag.groupType, drag.groupId}); + std::erase_if(drag.references, [](const Reference& frameReference) + { return frameReference.itemType == TRIGGER || frameReference.frameIndex < 0; }); + if (drag.references.empty()) return; - auto trackReferences = track_references_from_frame_references_get( - std::set(drag.references.begin(), drag.references.end())); - trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); - tracks_edit_command_push(EDIT_MOVE_FRAMES, Document::FRAMES, trackReferences, - [=, this](Manager&, Document& document) mutable - { - auto targetItem = - command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, - targetGroupId); - if (!targetItem) return; + auto trackReferences = + track_references_from_frame_references_get(std::set(drag.references.begin(), drag.references.end())); + trackReferences.insert({drag.animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId}); + tracks_edit_command_push( + EDIT_MOVE_FRAMES, Document::FRAMES, trackReferences, + [=, this](Manager&, Document& document) mutable + { + auto targetItem = + command_item_get(document, drag.animationIndex, targetType, targetID, targetGroupType, targetGroupId); + if (!targetItem) return; - std::map> groupedFrames{}; - for (auto frameReference : drag.references) - { - auto itemReference = item_reference_from_frame_get(frameReference); - groupedFrames[itemReference].insert(frameReference.frameIndex); - } + std::map> groupedFrames{}; + for (auto frameReference : drag.references) + { + auto itemReference = item_reference_from_frame_get(frameReference); + groupedFrames[itemReference].insert(frameReference.frameIndex); + } - int removedBeforeTarget = 0; - std::vector movedFrames; - for (auto& [itemReference, indices] : groupedFrames) - { - auto sourceItem = command_item_reference_get(document, itemReference); - if (!sourceItem) continue; + int removedBeforeTarget = 0; + std::vector movedFrames; + for (auto& [itemReference, indices] : groupedFrames) + { + auto sourceItem = command_item_reference_get(document, itemReference); + if (!sourceItem) continue; - for (auto i : indices) - { - auto childIndex = item_frame_child_index_get(*sourceItem, i); - if (childIndex == -1) continue; - movedFrames.push_back(std::move(sourceItem->children[childIndex])); - if (itemReference.itemType == targetType && itemReference.itemID == targetID && - itemReference.groupType == targetGroupType && itemReference.groupId == targetGroupId && - i < insertIndex) - ++removedBeforeTarget; - } + for (auto i : indices) + { + auto childIndex = item_frame_child_index_get(*sourceItem, i); + if (childIndex == -1) continue; + movedFrames.push_back(std::move(sourceItem->children[childIndex])); + if (itemReference.itemType == targetType && itemReference.itemID == targetID && + itemReference.groupType == targetGroupType && itemReference.groupId == targetGroupId && + i < insertIndex) + ++removedBeforeTarget; + } - for (auto it = indices.rbegin(); it != indices.rend(); ++it) - { - auto childIndex = item_frame_child_index_get(*sourceItem, *it); - if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); - } - } + for (auto it = indices.rbegin(); it != indices.rend(); ++it) + { + auto childIndex = item_frame_child_index_get(*sourceItem, *it); + if (childIndex != -1) sourceItem->children.erase(sourceItem->children.begin() + childIndex); + } + } - if (movedFrames.empty()) return; + if (movedFrames.empty()) return; - int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); - desired -= removedBeforeTarget; - desired = std::clamp(desired, 0, item_frames_count(targetItem)); + int desired = std::clamp(insertIndex, 0, item_frames_count(targetItem)); + desired -= removedBeforeTarget; + desired = std::clamp(desired, 0, item_frames_count(targetItem)); - auto insertPosResult = desired; - auto insertedCount = (int)movedFrames.size(); - auto childIndex = item_frame_insert_index_get(*targetItem, insertPosResult); - targetItem->children.insert(targetItem->children.begin() + childIndex, - std::make_move_iterator(movedFrames.begin()), - std::make_move_iterator(movedFrames.end())); + auto insertPosResult = desired; + auto insertedCount = (int)movedFrames.size(); + auto childIndex = item_frame_insert_index_get(*targetItem, insertPosResult); + targetItem->children.insert(targetItem->children.begin() + childIndex, + std::make_move_iterator(movedFrames.begin()), + std::make_move_iterator(movedFrames.end())); - if (insertedCount <= 0) return; + if (insertedCount <= 0) return; - std::set movedSelection{}; - for (int offset = 0; offset < insertedCount; ++offset) - movedSelection.insert({drag.animationIndex, targetType, targetID, insertPosResult + offset, - targetGroupType, targetGroupId}); + std::set movedSelection{}; + for (int offset = 0; offset < insertedCount; ++offset) + movedSelection.insert( + {drag.animationIndex, targetType, targetID, insertPosResult + offset, targetGroupType, targetGroupId}); - document.reference = {drag.animationIndex, targetType, targetID, insertPosResult, - targetGroupType, targetGroupId}; - document.frame_references_set(std::move(movedSelection)); - document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); - frameSelectionSnapshot.assign(document.frames.selection.begin(), - document.frames.selection.end()); - frameSelectionSnapshotReference = document.reference; - frameSelectionLocked.clear(); - isFrameSelectionLocked = false; - frameFocusIndex = document.reference.frameIndex; - frameFocusRequested = true; - if (targetType == LAYER) - if (auto layer = command_layer_get(document, targetID)) - document.spritesheet.reference = layer->spritesheetId; - }); - } + document.reference = {drag.animationIndex, targetType, targetID, + insertPosResult, targetGroupType, targetGroupId}; + document.frame_references_set(std::move(movedSelection)); + document.frameTime = frame_time_from_index_get(*targetItem, document.reference.frameIndex); + frameSelectionSnapshot.assign(document.frames.selection.begin(), document.frames.selection.end()); + frameSelectionSnapshotReference = document.reference; + frameSelectionLocked.clear(); + isFrameSelectionLocked = false; + frameFocusIndex = document.reference.frameIndex; + frameFocusRequested = true; + if (targetType == LAYER) + if (auto layer = command_layer_get(document, targetID)) + document.spritesheet.reference = layer->spritesheetId; + }); + } ImVec2 TimelineContext::frame_box_content_point_get() -{ - auto mousePos = ImGui::GetIO().MousePos; - return ImVec2(mousePos.x + scroll.x - frameBoxClipMin.x, mousePos.y + scroll.y - frameBoxClipMin.y); - } + { + auto mousePos = ImGui::GetIO().MousePos; + return ImVec2(mousePos.x + scroll.x - frameBoxClipMin.x, mousePos.y + scroll.y - frameBoxClipMin.y); + } ImVec2 TimelineContext::frame_box_screen_point_get(ImVec2 point) -{ return ImVec2(point.x - scroll.x + frameBoxClipMin.x, point.y - scroll.y + frameBoxClipMin.y); } + { + return ImVec2(point.x - scroll.x + frameBoxClipMin.x, point.y - scroll.y + frameBoxClipMin.y); + } bool TimelineContext::is_frame_box_overlapping(ImVec2 leftMin, ImVec2 leftMax, ImVec2 rightMin, ImVec2 rightMax) -{ - return leftMin.x <= rightMax.x && leftMax.x >= rightMin.x && leftMin.y <= rightMax.y && - leftMax.y >= rightMin.y; - } + { + return leftMin.x <= rightMax.x && leftMax.x >= rightMin.x && leftMin.y <= rightMax.y && leftMax.y >= rightMin.y; + } void TimelineContext::frame_overlay_draw(ImDrawList* drawList, ImVec2 clipMin, ImVec2 clipMax) -{ - if (isFrameBoxSelecting && isFrameBoxClipSet) + { + if (isFrameBoxSelecting && isFrameBoxClipSet) + { + auto boxContentMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxContentMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto boxMin = frame_box_screen_point_get(boxContentMin); + auto boxMax = frame_box_screen_point_get(boxContentMax); + auto boxClipMin = clipMin; + if (isPlayheadLineSet) boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); + drawList->PushClipRect(boxClipMin, clipMax, true); + drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); + drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); + drawList->PopClipRect(); + } + + if (isPlayheadLineSet) + { + auto lineTopY = std::max(clipMin.y, playheadLineTopY); + if (clipMax.y > lineTopY) { - auto boxContentMin = - ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxContentMax = - ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto boxMin = frame_box_screen_point_get(boxContentMin); - auto boxMax = frame_box_screen_point_get(boxContentMax); - auto boxClipMin = clipMin; - if (isPlayheadLineSet) boxClipMin.y = std::max(boxClipMin.y, playheadLineTopY); - drawList->PushClipRect(boxClipMin, clipMax, true); - drawList->AddRectFilled(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTargetBg)); - drawList->AddRect(boxMin, boxMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget)); + auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); + auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); + drawList->PushClipRect(clipMin, clipMax, true); + drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), + ImGui::GetColorU32(playheadLineColor)); drawList->PopClipRect(); } + } + } - if (isPlayheadLineSet) + void TimelineContext::frame_child(const TimelineItemRow& row, int& index, float width) + { + auto type = row.type; + auto id = row.id; + auto row_reference_make = [&](int frameIndex = -1) + { return Reference{reference.animationIndex, type, id, frameIndex, row.rootGroupType, row.rootGroupId}; }; + auto childSize = ImVec2(width, rowFrameChildHeight); + if (row.isGroup) + { + auto group = row_group_get(row); + if (!group) return; + + ImGui::PushID(index); + ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); + ImGui::EndChild(); + index++; + ImGui::PopID(); + return; + } + + auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); + if (type != NONE && !item) return; + + auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; + if (item && type == ROOT && row.rootGroupId != -1) + isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); + auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; + if (isOnlyShowLayers && type != LAYER) isVisible = false; + + auto colorVec = type_color_base_vec(type); + auto colorActiveVec = type_color_active_vec(type); + auto colorHoveredVec = type_color_hovered_vec(type); + auto color = to_imvec4(colorVec); + auto colorActive = to_imvec4(colorActiveVec); + auto colorHovered = to_imvec4(colorHoveredVec); + auto colorHidden = to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER); + auto colorActiveHidden = to_imvec4(colorActiveVec * COLOR_HIDDEN_MULTIPLIER); + auto colorHoveredHidden = to_imvec4(colorHoveredVec * COLOR_HIDDEN_MULTIPLIER); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::PopStyleVar(2); + + ImGui::PushID(index); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); + bool isDefaultChild = type == NONE; + if (isLightTheme && isDefaultChild) ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); + + bool isFramesChildVisible = ImGui::BeginChild("##Frames Child", childSize, ImGuiChildFlags_Borders); + auto drawList = ImGui::GetWindowDrawList(); + auto clipMax = drawList->GetClipRectMax(); + auto length = animation ? animation->frameNum : 0; + auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); + 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); + auto frameMax = std::min(FRAME_NUM_MAX, (int)std::ceil((scroll.x + clipMax.x) / frameSize.x) + 1); + + if (isFrameBoxSelecting && isFrameBoxClipSet && type != NONE && animation && item) + { + auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); + auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); + auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; + auto rowMaxY = rowMinY + childSize.y; + float selectionFrameTime{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + for (const auto& frame : item->children) { - auto lineTopY = std::max(clipMin.y, playheadLineTopY); - if (clipMax.y > lineTopY) - { - auto linePos = ImVec2(playheadLineCenterX - (PLAYHEAD_LINE_THICKNESS * 0.5f), lineTopY); - auto lineSize = ImVec2(PLAYHEAD_LINE_THICKNESS * 0.5f, clipMax.y - lineTopY); - drawList->PushClipRect(clipMin, clipMax, true); - drawList->AddRectFilled(linePos, ImVec2(linePos.x + lineSize.x, linePos.y + lineSize.y), - ImGui::GetColorU32(playheadLineColor)); - drawList->PopClipRect(); - } + if (frame.type != frameType) continue; + auto frameReference = row_reference_make(frameIndex); + auto frameStart = type == TRIGGER ? frame.atFrame : selectionFrameTime; + auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; + auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); + auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); + if (is_frame_box_overlapping(frameContentMin, frameContentMax, boxMin, boxMax)) + frameBoxSelection.insert(frameReference); + if (type != TRIGGER) selectionFrameTime += frame.duration; + ++frameIndex; } } - void TimelineContext::frame_child(const TimelineItemRow& row, int& index, float width) -{ - auto type = row.type; - auto id = row.id; - auto row_reference_make = [&](int frameIndex = -1) - { return Reference{reference.animationIndex, type, id, frameIndex, row.rootGroupType, row.rootGroupId}; }; - auto childSize = ImVec2(width, rowFrameChildHeight); - if (row.isGroup) + if (isFramesChildVisible) + { + if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && + ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) { - auto group = row_group_get(row); - if (!group) return; - - ImGui::PushID(index); - ImGui::BeginChild("##Frames Group Child", childSize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar); - ImGui::EndChild(); - index++; - ImGui::PopID(); - return; + if (!frames.references.empty() || !frames.selection.empty()) + { + reference.frameIndex = -1; + frames_selection_reset_for(document); + } + else if (reference.itemType != NONE || reference.itemID != -1) + reference_clear(); } - auto item = item_get(type, id, row.rootGroupType, row.rootGroupId); - if (type != NONE && !item) return; - - auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false; - if (item && type == ROOT && row.rootGroupId != -1) - isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId); - auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - if (isOnlyShowLayers && type != LAYER) isVisible = false; - - auto colorVec = type_color_base_vec(type); - auto colorActiveVec = type_color_active_vec(type); - auto colorHoveredVec = type_color_hovered_vec(type); - auto color = to_imvec4(colorVec); - auto colorActive = to_imvec4(colorActiveVec); - auto colorHovered = to_imvec4(colorHoveredVec); - auto colorHidden = to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER); - auto colorActiveHidden = to_imvec4(colorActiveVec * COLOR_HIDDEN_MULTIPLIER); - auto colorHoveredHidden = to_imvec4(colorHoveredVec * COLOR_HIDDEN_MULTIPLIER); - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::PopStyleVar(2); - - ImGui::PushID(index); - - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2()); - bool isDefaultChild = type == NONE; - if (isLightTheme && isDefaultChild) ImGui::PushStyleColor(ImGuiCol_ChildBg, TIMELINE_CHILD_BG_COLOR_LIGHT); - - bool isFramesChildVisible = ImGui::BeginChild("##Frames Child", childSize, ImGuiChildFlags_Borders); - auto drawList = ImGui::GetWindowDrawList(); - auto clipMax = drawList->GetClipRectMax(); - auto length = animation ? animation->frameNum : 0; - auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); - 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)) + if (type == NONE) { - auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x; - frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x)); + if (length > 0) + { + if (isLightTheme) + { + auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); + drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); + float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); + drawList->AddRectFilled(cursorScreenPos, + ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(timelinePlayheadRectColor)); + } + else + { + drawList->AddRectFilled(cursorScreenPos, + ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), + ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); + } + } + + for (int i = frameMin; i < frameMax; i++) + { + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + + drawList->AddRect(frameScreenPos, ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); + + drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), + ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); + + if (i % FRAME_MULTIPLE == 0) + { + auto string = std::to_string(i); + auto textSize = ImGui::CalcTextSize(string.c_str()); + auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, + frameScreenPos.y + (frameSize.y - textSize.y) / 2); + + drawList->AddRectFilled(frameScreenPos, + ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), + ImGui::GetColorU32(frameMultipleOverlayColor)); + + drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); + } + } + + if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + playback_stop(); + isDragging = true; + } + + auto childPos = ImGui::GetWindowPos(); + auto mousePos = ImGui::GetIO().MousePos; + auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); + hoveredTime = floorf(localMousePos.x / frameSize.x); + + if (isDragging) + { + playback.time = hoveredTime; + playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + document.frameTime = playback.time; + } + + if (!playback.isPlaying) playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; + + if (length > 0) + { + ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); + ImGui::Image(resources.icons[icon::PLAYHEAD].id, frameSize); + auto playheadMin = ImGui::GetItemRectMin(); + auto playheadMax = ImGui::GetItemRectMax(); + playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; + playheadLineTopY = playheadMax.y; + isPlayheadLineSet = true; + overlay_icon(resources.icons[icon::PLAYHEAD].id, playheadIconTint, true); + } } - 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); - auto frameMax = std::min(FRAME_NUM_MAX, (int)std::ceil((scroll.x + clipMax.x) / frameSize.x) + 1); - - if (isFrameBoxSelecting && isFrameBoxClipSet && type != NONE && animation && item) + else if (animation) { - auto boxMin = ImVec2(std::min(frameBoxStart.x, frameBoxEnd.x), std::min(frameBoxStart.y, frameBoxEnd.y)); - auto boxMax = ImVec2(std::max(frameBoxStart.x, frameBoxEnd.x), std::max(frameBoxStart.y, frameBoxEnd.y)); - auto rowMinY = cursorScreenPos.y + scroll.y - frameBoxClipMin.y; - auto rowMaxY = rowMinY + childSize.y; - float selectionFrameTime{}; + float frameTime{}; + + for (int i = frameMin; i < frameMax; i++) + { + auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); + auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); + + drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); + + if (i % FRAME_MULTIPLE == 0) + drawList->AddRectFilled(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameMultipleOverlayColor)); + } + + if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && + ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && + ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) + { + isFrameBoxPending = true; + isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); + frameBoxStart = frame_box_content_point_get(); + frameBoxEnd = frameBoxStart; + frameBoxSelection.clear(); + } + + bool isFrameMovePreview = false; + ImVec2 frameMovePreviewMin{}; + ImVec2 frameMovePreviewMax{}; + bool isFrameMoveHoveredFrame = false; + ImVec2 frameMoveHoveredFrameMin{}; + ImVec2 frameMoveHoveredFrameMax{}; + + if (frameMoveDrag.isActive && type != TRIGGER) + { + auto mousePos = ImGui::GetIO().MousePos; + auto rowMin = cursorScreenPos; + auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); + if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) + { + auto mouseX = mousePos.x - cursorScreenPos.x; + auto targetTime = glm::max(0.0f, mouseX / frameSize.x); + int dropIndex = item_frames_count(item); + float dropFrameTime{}; + float frameTime{}; + auto frameType = item_frame_type_get(*item); + int frameIndex{}; + + for (const auto& frame : item->children) + { + if (frame.type != frameType) continue; + auto frameStart = frameTime; + auto frameEnd = frameStart + frame.duration; + if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) + { + isFrameMoveHoveredFrame = true; + frameMoveHoveredFrameMin = ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); + frameMoveHoveredFrameMax = + ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); + } + + auto midpoint = frameStart + ((float)frame.duration * 0.5f); + if (targetTime < midpoint) + { + dropIndex = frameIndex; + dropFrameTime = frameStart; + break; + } + + frameTime = frameEnd; + dropFrameTime = frameTime; + ++frameIndex; + } + + frameMoveDropType = type; + frameMoveDropItemID = id; + frameMoveDropGroupType = row.rootGroupType; + frameMoveDropGroupId = row.rootGroupId; + frameMoveDropIndex = dropIndex; + isFrameMoveDropTarget = true; + + auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; + auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); + frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); + frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); + isFrameMovePreview = true; + } + } + auto frameType = item_frame_type_get(*item); int frameIndex{}; - for (const auto& frame : item->children) + for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) { + auto& frame = item->children[childIndex]; if (frame.type != frameType) continue; + ImGui::PushID(childIndex); + auto frameReference = row_reference_make(frameIndex); - auto frameStart = type == TRIGGER ? frame.atFrame : selectionFrameTime; + auto isFrameVisible = isVisible && frame.isVisible; + auto isReferenced = reference == frameReference; + auto isSelected = frames.references.contains(frameReference) || + (frames.references.empty() && frames.selection.contains(frameIndex) && + reference.itemType == type && reference.itemID == id && + reference.groupType == row.rootGroupType && reference.groupId == row.rootGroupId); + + if (type == TRIGGER) frameTime = frame.atFrame; + + auto buttonSize = type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); + auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; - auto frameContentMin = ImVec2(frameStart * frameSize.x, rowMinY); - auto frameContentMax = ImVec2(frameEnd * frameSize.x, rowMaxY); - if (is_frame_box_overlapping(frameContentMin, frameContentMax, boxMin, boxMax)) - frameBoxSelection.insert(frameReference); - if (type != TRIGGER) selectionFrameTime += frame.duration; - ++frameIndex; - } - } - - if (isFramesChildVisible) - { - if (ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) && - ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) - { - if (!frames.references.empty() || !frames.selection.empty()) + if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) { - reference.frameIndex = -1; - frames_selection_reset_for(document); + if (type != TRIGGER) frameTime += frame.duration; + ImGui::PopID(); + ++frameIndex; + continue; } - else if (reference.itemType != NONE || reference.itemID != -1) - reference_clear(); - } + auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); - if (type == NONE) - { - if (length > 0) + if (frameFocusRequested && frameFocusIndex == frameIndex && reference == frameReference) + frameFocusRequested = false; + + ImGui::SetCursorPos(buttonPos); + + auto buttonScreenPos = ImGui::GetCursorScreenPos(); + auto fillColor = + isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) : (isFrameVisible ? color : colorHidden); + drawList->AddRectFilled(buttonScreenPos, + ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), + ImGui::GetColorU32(fillColor), FRAME_ROUNDING); + + ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); + ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); + ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); + + ImGui::SetNextItemAllowOverlap(); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); + ImGui::SetNextItemSelectionUserData(frameIndex); + bool isDifferentItem = !is_same_item(reference, frameReference); + if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) { - if (isLightTheme) - { - auto totalMax = ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y); - drawList->AddRectFilled(cursorScreenPos, totalMax, ImGui::GetColorU32(timelineBackgroundColor)); - float animationWidth = std::min(framesSize.x, frameSize.x * (float)length); - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + animationWidth, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(timelinePlayheadRectColor)); - } - else - { - drawList->AddRectFilled(cursorScreenPos, - ImVec2(cursorScreenPos.x + framesSize.x, cursorScreenPos.y + framesSize.y), - ImGui::GetColorU32(ImGui::GetStyleColorVec4(ImGuiCol_Header))); - } - } - - for (int i = frameMin; i < frameMax; i++) - { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - - drawList->AddRect(frameScreenPos, ImVec2(frameScreenPos.x + border, frameScreenPos.y + borderLineLength), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5f); - - drawList->AddRect(ImVec2(frameScreenPos.x, frameScreenPos.y + frameSize.y - borderLineLength), - ImVec2(frameScreenPos.x + border, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(timelineTickColor), 0, 0, 0.5); - - if (i % FRAME_MULTIPLE == 0) - { - auto string = std::to_string(i); - auto textSize = ImGui::CalcTextSize(string.c_str()); - auto textPos = ImVec2(frameScreenPos.x + (frameSize.x - textSize.x) / 2, - frameScreenPos.y + (frameSize.y - textSize.y) / 2); - - drawList->AddRectFilled(frameScreenPos, - ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y), - ImGui::GetColorU32(frameMultipleOverlayColor)); - - drawList->AddText(textPos, ImGui::GetColorU32(textMultipleColor), string.c_str()); - } - } - - if (ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left)) - { - playback_stop(); - isDragging = true; - } - - auto childPos = ImGui::GetWindowPos(); - auto mousePos = ImGui::GetIO().MousePos; - auto localMousePos = ImVec2(mousePos.x - childPos.x, mousePos.y - childPos.y); - hoveredTime = floorf(localMousePos.x / frameSize.x); - - if (isDragging) - { - playback.time = hoveredTime; - playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - document.frameTime = playback.time; - } - - if (!playback.isPlaying) playback.clamp(settings.playbackIsClamp ? length : FRAME_NUM_MAX); - - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) isDragging = false; - - if (length > 0) - { - ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); - ImGui::Image(resources.icons[icon::PLAYHEAD].id, frameSize); - auto playheadMin = ImGui::GetItemRectMin(); - auto playheadMax = ImGui::GetItemRectMax(); - playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; - playheadLineTopY = playheadMax.y; - isPlayheadLineSet = true; - overlay_icon(resources.icons[icon::PLAYHEAD].id, playheadIconTint, true); - } - } - else if (animation) - { - float frameTime{}; - - for (int i = frameMin; i < frameMax; i++) - { - auto frameScreenPos = ImVec2(cursorScreenPos.x + frameSize.x * (float)i, cursorScreenPos.y); - auto frameRectMax = ImVec2(frameScreenPos.x + frameSize.x, frameScreenPos.y + frameSize.y); - - drawList->AddRect(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameBorderColor)); - - if (i % FRAME_MULTIPLE == 0) - drawList->AddRectFilled(frameScreenPos, frameRectMax, ImGui::GetColorU32(frameMultipleOverlayColor)); - } - - if (!frameMoveDrag.isActive && !ImGui::IsKeyDown(ImGuiMod_Shift) && - ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) && - ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsAnyItemHovered()) - { - isFrameBoxPending = true; - isFrameBoxAdditive = ImGui::IsKeyDown(ImGuiMod_Ctrl); - frameBoxStart = frame_box_content_point_get(); - frameBoxEnd = frameBoxStart; - frameBoxSelection.clear(); - } - - bool isFrameMovePreview = false; - ImVec2 frameMovePreviewMin{}; - ImVec2 frameMovePreviewMax{}; - bool isFrameMoveHoveredFrame = false; - ImVec2 frameMoveHoveredFrameMin{}; - ImVec2 frameMoveHoveredFrameMax{}; - - if (frameMoveDrag.isActive && type != TRIGGER) - { - auto mousePos = ImGui::GetIO().MousePos; - auto rowMin = cursorScreenPos; - auto rowMax = ImVec2(cursorScreenPos.x + width, cursorScreenPos.y + frameSize.y); - if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y) - { - auto mouseX = mousePos.x - cursorScreenPos.x; - auto targetTime = glm::max(0.0f, mouseX / frameSize.x); - int dropIndex = item_frames_count(item); - float dropFrameTime{}; - float frameTime{}; - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - - for (const auto& frame : item->children) - { - if (frame.type != frameType) continue; - auto frameStart = frameTime; - auto frameEnd = frameStart + frame.duration; - if (!isFrameMoveHoveredFrame && targetTime >= frameStart && targetTime < frameEnd) - { - isFrameMoveHoveredFrame = true; - frameMoveHoveredFrameMin = ImVec2(cursorScreenPos.x + frameStart * frameSize.x, cursorScreenPos.y); - frameMoveHoveredFrameMax = - ImVec2(cursorScreenPos.x + frameEnd * frameSize.x, cursorScreenPos.y + frameSize.y); - } - - auto midpoint = frameStart + ((float)frame.duration * 0.5f); - if (targetTime < midpoint) - { - dropIndex = frameIndex; - dropFrameTime = frameStart; - break; - } - - frameTime = frameEnd; - dropFrameTime = frameTime; - ++frameIndex; - } - - frameMoveDropType = type; - frameMoveDropItemID = id; - frameMoveDropGroupType = row.rootGroupType; - frameMoveDropGroupId = row.rootGroupId; - frameMoveDropIndex = dropIndex; - isFrameMoveDropTarget = true; - - auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x; - auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x); - frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y); - frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y); - isFrameMovePreview = true; - } - } - - auto frameType = item_frame_type_get(*item); - int frameIndex{}; - for (int childIndex = 0; childIndex < (int)item->children.size(); ++childIndex) - { - auto& frame = item->children[childIndex]; - if (frame.type != frameType) continue; - ImGui::PushID(childIndex); - - auto frameReference = row_reference_make(frameIndex); - auto isFrameVisible = isVisible && frame.isVisible; - auto isReferenced = reference == frameReference; - auto isSelected = frames.references.contains(frameReference) || - (frames.references.empty() && frames.selection.contains(frameIndex) && - reference.itemType == type && reference.itemID == id && - reference.groupType == row.rootGroupType && reference.groupId == row.rootGroupId); - - if (type == TRIGGER) frameTime = frame.atFrame; - - auto buttonSize = type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y)); - auto frameStart = type == TRIGGER ? frame.atFrame : frameTime; - auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration; - if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax) - { - if (type != TRIGGER) frameTime += frame.duration; - ImGui::PopID(); - ++frameIndex; - continue; - } - auto buttonPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y); - - if (frameFocusRequested && frameFocusIndex == frameIndex && reference == frameReference) - frameFocusRequested = false; - - ImGui::SetCursorPos(buttonPos); - - auto buttonScreenPos = ImGui::GetCursorScreenPos(); - auto fillColor = isSelected ? (isFrameVisible ? colorActive : colorActiveHidden) - : (isFrameVisible ? color : colorHidden); - drawList->AddRectFilled(buttonScreenPos, - ImVec2(buttonScreenPos.x + buttonSize.x, buttonScreenPos.y + buttonSize.y), - ImGui::GetColorU32(fillColor), FRAME_ROUNDING); - - ImGui::PushStyleColor(ImGuiCol_Header, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderActive, isFrameVisible ? colorActive : colorActiveHidden); - ImGui::PushStyleColor(ImGuiCol_HeaderHovered, isFrameVisible ? colorHovered : colorHoveredHidden); - ImGui::PushStyleColor(ImGuiCol_NavCursor, isFrameVisible ? colorHovered : colorHoveredHidden); - - ImGui::SetNextItemAllowOverlap(); - ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, FRAME_ROUNDING); - ImGui::SetNextItemSelectionUserData(frameIndex); - bool isDifferentItem = !is_same_item(reference, frameReference); - if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) - { - if (type == LAYER) - if (auto layer = layer_get(id)) document.spritesheet.reference = layer->spritesheetId; - - if (type != TRIGGER) - { - if (ImGui::IsKeyDown(ImGuiMod_Alt)) - { - auto targetReference = frameReference; - frames_edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, {targetReference}, - [=, this](Manager&, Document& document) - { - auto frame = command_frame_get(document, targetReference); - if (!frame) return; - frame->interpolation = frame->interpolation == Interpolation::NONE - ? Interpolation::LINEAR - : Interpolation::NONE; - }); - } - - document.frameTime = frameTime; - } - - auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); - auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); - if (isShiftDown) - { - auto isHadAnchor = isFrameSelectionAnchorSet; - auto anchorReference = isHadAnchor ? frameSelectionAnchor : frameReference; - auto isRangeSelected = - frame_selection_range_set_for(document, anchorReference, frameReference, isCtrlDown); - if (!isRangeSelected) frame_selection_set_for(document, frameReference); - if (!isHadAnchor || !isRangeSelected) frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - else if (isCtrlDown) - { - frame_selection_toggle_for(document, frameReference); - frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - else - { - frame_selection_set_for(document, frameReference); - frameSelectionAnchor = frameReference; - isFrameSelectionAnchorSet = true; - } - reference = frameReference; - isReferenced = true; - region.reference = -1; - region.selection.clear(); - if (isDifferentItem) frames_selection_sync_for(document); - } - ImGui::PopStyleVar(); - - ImGui::PopStyleColor(4); - - if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) - { - if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) - { - if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) - { - isDraggedFrameActive = true; - draggedFrameReference = frameReference; - draggedFrameType = type; - draggedFrameIndex = frameIndex; - draggedFrameStart = hoveredTime; - if (type != TRIGGER) draggedFrameStartDuration = frame.duration; - draggedFrameStartDurations.clear(); - if (type != TRIGGER) - { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, [](const Reference& selectedReference) - { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; - for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) - draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); - } - } - draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; - draggedFrameWidth = frameSize.x; - } - } - } + if (type == LAYER) + if (auto layer = layer_get(id)) document.spritesheet.reference = layer->spritesheetId; if (type != TRIGGER) { - if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && - ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + if (ImGui::IsKeyDown(ImGuiMod_Alt)) { - auto selectedReferences = frame_references_for_current_get(); - if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; - std::erase_if(selectedReferences, [](const Reference& selectedReference) - { return selectedReference.itemType == TRIGGER; }); - if (selectedReferences.empty()) selectedReferences = {frameReference}; - int dragDuration = 0; - for (auto selectedReference : selectedReferences) - { - auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, - selectedReference.groupType, selectedReference.groupId); - auto selectedFrame = - selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; - if (selectedFrame) dragDuration += selectedFrame->duration; - } - dragDuration = glm::max(1, dragDuration); - - frameMoveDrag = { - .type = type, - .itemID = id, - .animationIndex = reference.animationIndex, - .groupType = row.rootGroupType, - .groupId = row.rootGroupId, - .frameIndex = frameIndex, - .duration = dragDuration, - .indices = {}, - .references = {selectedReferences.begin(), selectedReferences.end()}, - .isActive = true, - }; + auto targetReference = frameReference; + frames_edit_command_push(EDIT_FRAME_INTERPOLATION, Document::FRAMES, {targetReference}, + [=, this](Manager&, Document& document) + { + auto frame = command_frame_get(document, targetReference); + if (!frame) return; + frame->interpolation = frame->interpolation == Interpolation::NONE + ? Interpolation::LINEAR + : Interpolation::NONE; + }); } + + document.frameTime = frameTime; } - auto rectMin = ImGui::GetItemRectMin(); - auto rectMax = ImGui::GetItemRectMax(); - auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; - auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; - drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); - - auto icon = icon::UNINTERPOLATED; - if (type == TRIGGER) - icon = icon::TRIGGER; + auto isCtrlDown = ImGui::IsKeyDown(ImGuiMod_Ctrl); + auto isShiftDown = ImGui::IsKeyDown(ImGuiMod_Shift); + if (isShiftDown) + { + auto isHadAnchor = isFrameSelectionAnchorSet; + auto anchorReference = isHadAnchor ? frameSelectionAnchor : frameReference; + auto isRangeSelected = + frame_selection_range_set_for(document, anchorReference, frameReference, isCtrlDown); + if (!isRangeSelected) frame_selection_set_for(document, frameReference); + if (!isHadAnchor || !isRangeSelected) frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } + else if (isCtrlDown) + { + frame_selection_toggle_for(document, frameReference); + frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } else { - switch (frame.interpolation) + frame_selection_set_for(document, frameReference); + frameSelectionAnchor = frameReference; + isFrameSelectionAnchorSet = true; + } + reference = frameReference; + isReferenced = true; + region.reference = -1; + region.selection.clear(); + if (isDifferentItem) frames_selection_sync_for(document); + } + ImGui::PopStyleVar(); + + ImGui::PopStyleColor(4); + + if (!isDraggedFrameActive && ImGui::IsItemHovered() && ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (ImGui::IsMouseDown(ImGuiMouseButton_Left)) + { + if (type == TRIGGER || ImGui::IsKeyDown(ImGuiMod_Ctrl)) { - case Interpolation::NONE: - icon = icon::UNINTERPOLATED; - break; - case Interpolation::LINEAR: - icon = icon::INTERPOLATED; - break; - case Interpolation::EASE_IN: - icon = icon::EASE_IN; - break; - case Interpolation::EASE_OUT: - icon = icon::EASE_OUT; - break; - case Interpolation::EASE_IN_OUT: - icon = icon::EASE_IN_OUT; - break; - default: - icon = icon::UNINTERPOLATED; - break; + isDraggedFrameActive = true; + draggedFrameReference = frameReference; + draggedFrameType = type; + draggedFrameIndex = frameIndex; + draggedFrameStart = hoveredTime; + if (type != TRIGGER) draggedFrameStartDuration = frame.duration; + draggedFrameStartDurations.clear(); + if (type != TRIGGER) + { + auto selectedReferences = frame_references_for_current_get(); + if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + std::erase_if(selectedReferences, [](const Reference& selectedReference) + { return selectedReference.itemType == TRIGGER; }); + if (selectedReferences.empty()) selectedReferences = {frameReference}; + for (auto selectedReference : selectedReferences) + { + auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, + selectedReference.groupType, selectedReference.groupId); + auto selectedFrame = + selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; + if (selectedFrame) + draggedFrameStartDurations.push_back({selectedReference, selectedFrame->duration}); + } + } + draggedFrameStartMouseX = ImGui::GetIO().MousePos.x; + draggedFrameWidth = frameSize.x; } } - auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), - cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); - ImGui::SetCursorPos(iconPos); - ImGui::Image(resources.icons[icon].id, icon_size_get()); - overlay_icon(resources.icons[icon].id, iconTintDefault, false); - - if (type != TRIGGER) frameTime += frame.duration; - - ImGui::PopID(); - ++frameIndex; } - if (isFrameMovePreview) + if (type != TRIGGER) { - drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, - ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); - drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), - FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); + if (!isDraggedFrameActive && !frameMoveDrag.isActive && ImGui::IsItemActive() && + ImGui::IsMouseDragging(ImGuiMouseButton_Left)) + { + auto selectedReferences = frame_references_for_current_get(); + if (!selectedReferences.contains(frameReference)) selectedReferences = {frameReference}; + std::erase_if(selectedReferences, + [](const Reference& selectedReference) { return selectedReference.itemType == TRIGGER; }); + if (selectedReferences.empty()) selectedReferences = {frameReference}; + int dragDuration = 0; + for (auto selectedReference : selectedReferences) + { + auto selectedItem = item_get(selectedReference.itemType, selectedReference.itemID, + selectedReference.groupType, selectedReference.groupId); + auto selectedFrame = + selectedItem ? track_frame_get(*selectedItem, selectedReference.frameIndex) : nullptr; + if (selectedFrame) dragDuration += selectedFrame->duration; + } + dragDuration = glm::max(1, dragDuration); + + frameMoveDrag = { + .type = type, + .itemID = id, + .animationIndex = reference.animationIndex, + .groupType = row.rootGroupType, + .groupId = row.rootGroupId, + .frameIndex = frameIndex, + .duration = dragDuration, + .indices = {}, + .references = {selectedReferences.begin(), selectedReferences.end()}, + .isActive = true, + }; + } } - if (isFrameMoveHoveredFrame) - drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, - ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, - ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); + auto rectMin = ImGui::GetItemRectMin(); + auto rectMax = ImGui::GetItemRectMax(); + auto borderColor = isReferenced ? frameBorderColorReferenced : frameBorderColor; + auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; + drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); - if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && - (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && - !ImGui::IsAnyItemHovered()) - row_selection_set(row); - - if (isFrameSelectionLocked) - { - std::set lockedSelection{}; - for (int idx : frameSelectionLocked) - lockedSelection.insert(row_reference_make(idx)); - document.frame_references_set(std::move(lockedSelection)); - isFrameSelectionLocked = false; - frameSelectionLocked.clear(); - } - if (reference.itemType == type && reference.itemID == id && reference.groupType == row.rootGroupType && - reference.groupId == row.rootGroupId) - { - frameSelectionSnapshot.assign(frames.selection.begin(), frames.selection.end()); - frameSelectionSnapshotReference = reference; - } - } - - } - - if (isDraggedFrameActive) - { - ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); - auto durationDelta = draggedFrameWidth > 0.0f - ? static_cast((ImGui::GetIO().MousePos.x - draggedFrameStartMouseX) / - draggedFrameWidth) - : hoveredTime - draggedFrameStart; - auto isDraggedFrameChanged = - draggedFrameType == TRIGGER ? hoveredTime != draggedFrameStart : durationDelta != 0; - - if (!isDraggedFrameSnapshot && isDraggedFrameChanged) - { - isDraggedFrameSnapshot = true; - if (draggedFrameType == TRIGGER) - tracks_snapshot_command_push(EDIT_TRIGGER_AT_FRAME, {item_reference_from_frame_get(draggedFrameReference)}); + auto icon = icon::UNINTERPOLATED; + if (type == TRIGGER) + icon = icon::TRIGGER; else { - std::set draggedFrameReferences{}; - if (draggedFrameStartDurations.empty()) - draggedFrameReferences.insert(draggedFrameReference); - else - for (auto& frameDuration : draggedFrameStartDurations) - draggedFrameReferences.insert(frameDuration.reference); - frames_snapshot_command_push(EDIT_FRAME_DURATION, draggedFrameReferences); + switch (frame.interpolation) + { + case Interpolation::NONE: + icon = icon::UNINTERPOLATED; + break; + case Interpolation::LINEAR: + icon = icon::INTERPOLATED; + break; + case Interpolation::EASE_IN: + icon = icon::EASE_IN; + break; + case Interpolation::EASE_OUT: + icon = icon::EASE_OUT; + break; + case Interpolation::EASE_IN_OUT: + icon = icon::EASE_IN_OUT; + break; + default: + icon = icon::UNINTERPOLATED; + break; + } } + auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), + cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); + ImGui::SetCursorPos(iconPos); + ImGui::Image(resources.icons[icon].id, icon_size_get()); + overlay_icon(resources.icons[icon].id, iconTintDefault, false); + + if (type != TRIGGER) frameTime += frame.duration; + + ImGui::PopID(); + ++frameIndex; } - if (isDraggedFrameSnapshot) + if (isFrameMovePreview) { - auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - auto targetIndex = draggedFrameIndex; - auto targetStartDuration = draggedFrameStartDuration; - auto targetStartDurations = draggedFrameStartDurations; - auto targetHoveredTime = hoveredTime; - auto targetDurationDelta = durationDelta; - auto isPlaybackClamp = settings.playbackIsClamp; - auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; - command_push([=, this](Manager&, Document& document) - { - auto item = command_item_reference_get(document, targetReference); - auto frame = command_frame_get(document, targetReference); - if (!item || !frame) return; - - if (targetType == TRIGGER) - { - frame->atFrame = - glm::clamp(targetHoveredTime, 0, - isPlaybackClamp ? animationLength - 1 : FRAME_NUM_MAX - 1); - - for (auto [i, trigger] : std::views::enumerate(item->children)) - { - if ((int)i == targetIndex) continue; - if (trigger.atFrame == frame->atFrame) frame->atFrame--; - } - } - else - { - if (targetStartDurations.empty()) - { - frame->duration = glm::clamp(targetStartDuration + targetDurationDelta, - FRAME_DURATION_MIN, FRAME_DURATION_MAX); - return; - } - - for (auto frameDuration : targetStartDurations) - { - auto targetFrame = command_frame_get(document, frameDuration.reference); - if (!targetFrame) continue; - targetFrame->duration = glm::clamp(frameDuration.duration + targetDurationDelta, - FRAME_DURATION_MIN, FRAME_DURATION_MAX); - } - } - }); + drawList->AddRectFilled(frameMovePreviewMin, frameMovePreviewMax, + ImGui::GetColorU32(ImGuiCol_DragDropTargetBg), FRAME_ROUNDING); + drawList->AddRect(frameMovePreviewMin, frameMovePreviewMax, ImGui::GetColorU32(ImGuiCol_DragDropTarget), + FRAME_ROUNDING, 0, ImGui::GetStyle().DragDropTargetBorderSize); } - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + if (isFrameMoveHoveredFrame) + drawList->AddRect(frameMoveHoveredFrameMin, frameMoveHoveredFrameMax, + ImGui::GetColorU32(ImGuiCol_DragDropTarget), FRAME_ROUNDING, 0, + ImGui::GetStyle().DragDropTargetBorderSize * 1.5f); + + if (!isFrameBoxSelecting && !frameMoveDrag.isActive && !isDraggedFrameActive && ImGui::IsWindowHovered() && + (ImGui::IsMouseReleased(ImGuiMouseButton_Left) || ImGui::IsMouseReleased(ImGuiMouseButton_Right)) && + !ImGui::IsAnyItemHovered()) + row_selection_set(row); + + if (isFrameSelectionLocked) { - auto targetReference = draggedFrameReference; - auto targetType = draggedFrameType; - command_push([=, this](Manager&, Document& document) - { - auto item = command_item_reference_get(document, targetReference); - if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); - document.anm2_change(Document::FRAMES); - }); - isDraggedFrameActive = false; - draggedFrameReference = {}; - draggedFrameType = NONE; - draggedFrameIndex = -1; - draggedFrameStart = -1; - draggedFrameStartDuration = -1; - draggedFrameStartDurations.clear(); - draggedFrameStartMouseX = 0.0f; - draggedFrameWidth = 0.0f; - isDraggedFrameSnapshot = false; + std::set lockedSelection{}; + for (int idx : frameSelectionLocked) + lockedSelection.insert(row_reference_make(idx)); + document.frame_references_set(std::move(lockedSelection)); + isFrameSelectionLocked = false; frameSelectionLocked.clear(); } + if (reference.itemType == type && reference.itemID == id && reference.groupType == row.rootGroupType && + reference.groupId == row.rootGroupId) + { + frameSelectionSnapshot.assign(frames.selection.begin(), frames.selection.end()); + frameSelectionSnapshotReference = reference; + } + } + } + + if (isDraggedFrameActive) + { + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + auto durationDelta = + draggedFrameWidth > 0.0f + ? static_cast((ImGui::GetIO().MousePos.x - draggedFrameStartMouseX) / draggedFrameWidth) + : hoveredTime - draggedFrameStart; + auto isDraggedFrameChanged = draggedFrameType == TRIGGER ? hoveredTime != draggedFrameStart : durationDelta != 0; + + if (!isDraggedFrameSnapshot && isDraggedFrameChanged) + { + isDraggedFrameSnapshot = true; + if (draggedFrameType == TRIGGER) + tracks_snapshot_command_push(EDIT_TRIGGER_AT_FRAME, {item_reference_from_frame_get(draggedFrameReference)}); + else + { + std::set draggedFrameReferences{}; + if (draggedFrameStartDurations.empty()) + draggedFrameReferences.insert(draggedFrameReference); + else + for (auto& frameDuration : draggedFrameStartDurations) + draggedFrameReferences.insert(frameDuration.reference); + frames_snapshot_command_push(EDIT_FRAME_DURATION, draggedFrameReferences); + } } - context_menu(); + if (isDraggedFrameSnapshot) + { + auto targetReference = draggedFrameReference; + auto targetType = draggedFrameType; + auto targetIndex = draggedFrameIndex; + auto targetStartDuration = draggedFrameStartDuration; + auto targetStartDurations = draggedFrameStartDurations; + auto targetHoveredTime = hoveredTime; + auto targetDurationDelta = durationDelta; + auto isPlaybackClamp = settings.playbackIsClamp; + auto animationLength = animation ? animation->frameNum : FRAME_NUM_MAX; + command_push( + [=, this](Manager&, Document& document) + { + auto item = command_item_reference_get(document, targetReference); + auto frame = command_frame_get(document, targetReference); + if (!item || !frame) return; - ImGui::EndChild(); - if (isLightTheme && isDefaultChild) ImGui::PopStyleColor(); - ImGui::PopStyleVar(); + if (targetType == TRIGGER) + { + frame->atFrame = + glm::clamp(targetHoveredTime, 0, isPlaybackClamp ? animationLength - 1 : FRAME_NUM_MAX - 1); - index++; - ImGui::PopID(); + for (auto [i, trigger] : std::views::enumerate(item->children)) + { + if ((int)i == targetIndex) continue; + if (trigger.atFrame == frame->atFrame) frame->atFrame--; + } + } + else + { + if (targetStartDurations.empty()) + { + frame->duration = + glm::clamp(targetStartDuration + targetDurationDelta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + return; + } + + for (auto frameDuration : targetStartDurations) + { + auto targetFrame = command_frame_get(document, frameDuration.reference); + if (!targetFrame) continue; + targetFrame->duration = + glm::clamp(frameDuration.duration + targetDurationDelta, FRAME_DURATION_MIN, FRAME_DURATION_MAX); + } + } + }); + } + + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + auto targetReference = draggedFrameReference; + auto targetType = draggedFrameType; + command_push( + [=, this](Manager&, Document& document) + { + auto item = command_item_reference_get(document, targetReference); + if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); + document.change(Document::FRAMES); + }); + isDraggedFrameActive = false; + draggedFrameReference = {}; + draggedFrameType = NONE; + draggedFrameIndex = -1; + draggedFrameStart = -1; + draggedFrameStartDuration = -1; + draggedFrameStartDurations.clear(); + draggedFrameStartMouseX = 0.0f; + draggedFrameWidth = 0.0f; + isDraggedFrameSnapshot = false; + frameSelectionLocked.clear(); + } } + context_menu(); + + ImGui::EndChild(); + if (isLightTheme && isDefaultChild) ImGui::PopStyleColor(); + ImGui::PopStyleVar(); + + index++; + ImGui::PopID(); + } + void TimelineContext::frames_child() -{ - auto cursorPos = ImGui::GetCursorPos(); - ImGui::SetCursorPos(ImVec2(cursorPos.x + ITEM_CHILD_WIDTH, cursorPos.y)); + { + auto cursorPos = ImGui::GetCursorPos(); + ImGui::SetCursorPos(ImVec2(cursorPos.x + ITEM_CHILD_WIDTH, cursorPos.y)); - auto framesChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y); + auto framesChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y); - if (ImGui::BeginChild("##Frames Child", framesChildSize, ImGuiChildFlags_Borders)) + if (ImGui::BeginChild("##Frames Child", framesChildSize, ImGuiChildFlags_Borders)) + { + auto viewListChildSize = + ImVec2(ImGui::GetContentRegionAvail().x, + ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); + + auto animationsLength = [&]() { - auto viewListChildSize = - ImVec2(ImGui::GetContentRegionAvail().x, - ImGui::GetContentRegionAvail().y - ImGui::GetTextLineHeightWithSpacing() - style.ItemSpacing.y * 2); + int length{}; + if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) + for (auto& item : animations->children) + if (item.type == ElementType::ANIMATION) length = std::max(length, animation_length_get(item)); + return length; + }(); + auto childWidth = animationsLength * ImGui::GetTextLineHeight(); + if (animation && animation->frameNum > animationsLength) + childWidth = animation->frameNum * ImGui::GetTextLineHeight(); + childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); - auto animationsLength = [&]() + childWidth *= WIDTH_MULTIPLIER; + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) + { + playheadLineCenterX = 0.0f; + playheadLineTopY = 0.0f; + isPlayheadLineSet = false; + isFrameBoxClipSet = false; + if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { - int length{}; - if (auto animations = anm2.element_get(ElementType::ANIMATIONS)) - for (auto& item : animations->children) - if (item.type == ElementType::ANIMATION) length = std::max(length, animation_length_get(item)); - return length; - }(); - auto childWidth = animationsLength * ImGui::GetTextLineHeight(); - if (animation && animation->frameNum > animationsLength) - childWidth = animation->frameNum * ImGui::GetTextLineHeight(); - childWidth = std::max(childWidth, ImGui::GetContentRegionAvail().x); + group_selection_reset_for(document); + document.frame_references_set(all_frame_references_for_items_get()); + if (!document.frames.references.empty()) frames_selection_sync_for(document); + } - childWidth *= WIDTH_MULTIPLIER; - - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); - if (ImGui::BeginChild("##Frames List Child", viewListChildSize, true, ImGuiWindowFlags_HorizontalScrollbar)) + ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); + if (ImGui::BeginTable("##Frames List Table", 1, + ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) { - playheadLineCenterX = 0.0f; - playheadLineTopY = 0.0f; - isPlayheadLineSet = false; - isFrameBoxClipSet = false; - if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; + + scroll.x = ImGui::GetScrollX(); + scroll.y = ImGui::GetScrollY(); + + isHorizontalScroll = window->ScrollbarX; + + if (isWindowHovered) { - group_selection_reset_for(document); - document.frame_references_set(all_frame_references_for_items_get()); - if (!document.frames.references.empty()) - frames_selection_sync_for(document); + auto& io = ImGui::GetIO(); + auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; + + scroll.x -= io.MouseWheelH * lineHeight; + scroll.y -= io.MouseWheel * lineHeight; } - ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2()); - if (ImGui::BeginTable("##Frames List Table", 1, - ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) - { - ImGuiWindow* window = ImGui::GetCurrentWindow(); - window->Flags |= ImGuiWindowFlags_NoScrollWithMouse; - - scroll.x = ImGui::GetScrollX(); - scroll.y = ImGui::GetScrollY(); - - isHorizontalScroll = window->ScrollbarX; - - if (isWindowHovered) - { - auto& io = ImGui::GetIO(); - auto lineHeight = ImGui::GetTextLineHeightWithSpacing() * 2; - - scroll.x -= io.MouseWheelH * lineHeight; - scroll.y -= io.MouseWheel * lineHeight; - } - - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - - auto frameBoxDrawList = ImGui::GetWindowDrawList(); - frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); - frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); - isFrameBoxClipSet = true; - if (isFrameBoxPending || isFrameBoxSelecting) - { - auto& io = ImGui::GetIO(); - auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; - frameBoxEnd = frame_box_content_point_get(); - auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); - if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) - { - isFrameBoxPending = false; - isFrameBoxSelecting = true; - } - auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); - auto scrollStep = edgeSize * 0.5f; - if (isFrameBoxSelecting) - { - if (io.MousePos.x < frameBoxClipMin.x + edgeSize) - scroll.x -= scrollStep; - else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) - scroll.x += scrollStep; - if (io.MousePos.y < frameBoxClipMin.y + edgeSize) - scroll.y -= scrollStep; - else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) - scroll.y += scrollStep; - ImGui::SetScrollX(scroll.x); - ImGui::SetScrollY(scroll.y); - frameBoxEnd = frame_box_content_point_get(); - frameBoxSelection.clear(); - } - } - - int index{}; - - ImGui::TableSetupScrollFreeze(0, 1); - ImGui::TableSetupColumn("##Frames"); - - auto frames_child_row = [&](const TimelineItemRow& row) - { - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(0); - frame_child(row, index, childWidth); - }; - - frames_child_row({.type = NONE}); - - if (animation) - { - ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); - - for (const auto& row : timeline_item_rows_get()) - frames_child_row(row); - - ImGui::PopStyleVar(); - } - ImGui::EndTable(); - } - - if (isFrameBoxClipSet) - { - auto overlayCursor = ImGui::GetCursorScreenPos(); - auto overlayPos = ImGui::GetWindowPos(); - auto overlaySize = ImGui::GetWindowSize(); - ImGui::SetCursorScreenPos(overlayPos); - if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, - ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | - ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | - ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) - frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); - ImGui::EndChild(); - ImGui::SetCursorScreenPos(overlayCursor); - } + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + auto frameBoxDrawList = ImGui::GetWindowDrawList(); + frameBoxClipMin = frameBoxDrawList->GetClipRectMin(); + frameBoxClipMax = frameBoxDrawList->GetClipRectMax(); + isFrameBoxClipSet = true; if (isFrameBoxPending || isFrameBoxSelecting) { - if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + auto& io = ImGui::GetIO(); + auto threshold = ImGui::GetTextLineHeightWithSpacing() * 0.125f; + frameBoxEnd = frame_box_content_point_get(); + auto distance = ImVec2(frameBoxEnd.x - frameBoxStart.x, frameBoxEnd.y - frameBoxStart.y); + if (isFrameBoxPending && distance.x * distance.x + distance.y * distance.y >= threshold * threshold) { - if (isFrameBoxSelecting) - { - group_selection_reset_for(document); - if (isFrameBoxAdditive) - { - auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); - selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); - document.frame_references_set(std::move(selectedFrames)); - } - else - document.frame_references_set(frameBoxSelection); - frames_selection_sync_for(document); - } isFrameBoxPending = false; - isFrameBoxSelecting = false; + isFrameBoxSelecting = true; + } + auto edgeSize = ImGui::GetTextLineHeightWithSpacing(); + auto scrollStep = edgeSize * 0.5f; + if (isFrameBoxSelecting) + { + if (io.MousePos.x < frameBoxClipMin.x + edgeSize) + scroll.x -= scrollStep; + else if (io.MousePos.x > frameBoxClipMax.x - edgeSize) + scroll.x += scrollStep; + if (io.MousePos.y < frameBoxClipMin.y + edgeSize) + scroll.y -= scrollStep; + else if (io.MousePos.y > frameBoxClipMax.y - edgeSize) + scroll.y += scrollStep; + ImGui::SetScrollX(scroll.x); + ImGui::SetScrollY(scroll.y); + frameBoxEnd = frame_box_content_point_get(); frameBoxSelection.clear(); } } - ImGui::PopStyleVar(); + int index{}; + + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn("##Frames"); + + auto frames_child_row = [&](const TimelineItemRow& row) + { + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(0); + frame_child(row, index, childWidth); + }; + + frames_child_row({.type = NONE}); + + if (animation) + { + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 2.0f); + + for (const auto& row : timeline_item_rows_get()) + frames_child_row(row); + + ImGui::PopStyleVar(); + } + ImGui::EndTable(); } - ImGui::EndChild(); - ImGui::PopStyleVar(); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); - - ImGui::SetCursorPos( - ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); - - auto widgetSize = widget_size_with_row_get(10); - - ImGui::BeginDisabled(!animation); + if (isFrameBoxClipSet) { - auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); - auto tooltip = - playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); + auto overlayCursor = ImGui::GetCursorScreenPos(); + auto overlayPos = ImGui::GetWindowPos(); + auto overlaySize = ImGui::GetWindowSize(); + ImGui::SetCursorScreenPos(overlayPos); + if (ImGui::BeginChild("##Frames Overlay Child", overlaySize, ImGuiChildFlags_None, + ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoBackground | + ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | + ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoNavInputs)) + frame_overlay_draw(ImGui::GetWindowDrawList(), frameBoxClipMin, frameBoxClipMax); + ImGui::EndChild(); + ImGui::SetCursorScreenPos(overlayCursor); + } - shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); - if (ImGui::Button(label, widgetSize)) playback.toggle(); - set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); + if (isFrameBoxPending || isFrameBoxSelecting) + { + if (ImGui::IsMouseReleased(ImGuiMouseButton_Left)) + { + if (isFrameBoxSelecting) + { + group_selection_reset_for(document); + if (isFrameBoxAdditive) + { + auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); + selectedFrames.insert(frameBoxSelection.begin(), frameBoxSelection.end()); + document.frame_references_set(std::move(selectedFrames)); + } + else + document.frame_references_set(frameBoxSelection); + frames_selection_sync_for(document); + } + isFrameBoxPending = false; + isFrameBoxSelecting = false; + frameBoxSelection.clear(); + } + } + + ImGui::PopStyleVar(); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); + + ImGui::SetCursorPos( + ImVec2(ImGui::GetStyle().WindowPadding.x, ImGui::GetCursorPos().y + ImGui::GetStyle().ItemSpacing.y)); + + auto widgetSize = widget_size_with_row_get(10); + + ImGui::BeginDisabled(!animation); + { + auto label = playback.isPlaying ? localize.get(LABEL_PAUSE) : localize.get(LABEL_PLAY); + auto tooltip = + playback.isPlaying ? localize.get(TOOLTIP_PAUSE_ANIMATION) : localize.get(TOOLTIP_PLAY_ANIMATION); + + shortcut(manager.chords[SHORTCUT_PLAY_PAUSE]); + if (ImGui::Button(label, widgetSize)) playback.toggle(); + set_item_tooltip_shortcut(tooltip, settings.shortcutPlayPause); + + ImGui::SameLine(); + + auto item = selected_item_get(); + auto selectedFrames = frame_references_for_current_get(); + auto selectedBakeFrames = selectedFrames; + std::erase_if(selectedBakeFrames, + [](const Reference& frameReference) { return frameReference.itemType == TRIGGER; }); + + ImGui::BeginDisabled(!item); + { + shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); + if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) frame_insert(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); ImGui::SameLine(); - auto item = selected_item_get(); - auto selectedFrames = frame_references_for_current_get(); - auto selectedBakeFrames = selectedFrames; - std::erase_if(selectedBakeFrames, [](const Reference& frameReference) - { return frameReference.itemType == TRIGGER; }); - - ImGui::BeginDisabled(!item); + ImGui::BeginDisabled(selectedFrames.empty()); { - shortcut(manager.chords[SHORTCUT_INSERT_FRAME]); - if (ImGui::Button(localize.get(LABEL_INSERT), widgetSize)) frame_insert(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_INSERT_FRAME), settings.shortcutInsertFrame); + shortcut(manager.chords[SHORTCUT_REMOVE]); + if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) frames_delete_action(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); ImGui::SameLine(); - ImGui::BeginDisabled(selectedFrames.empty()); - { - shortcut(manager.chords[SHORTCUT_REMOVE]); - if (ImGui::Button(localize.get(LABEL_DELETE), widgetSize)) frames_delete_action(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_DELETE_FRAMES), settings.shortcutRemove); - - ImGui::SameLine(); - - ImGui::BeginDisabled(selectedBakeFrames.empty()); - if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) bakePopup.open(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); - ImGui::EndDisabled(); - } + ImGui::BeginDisabled(selectedBakeFrames.empty()); + if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize)) bakePopup.open(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_BAKE_FRAMES), settings.shortcutBake); ImGui::EndDisabled(); } ImGui::EndDisabled(); - - ImGui::SameLine(); - - ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); - shortcut(manager.chords[SHORTCUT_FIT]); - if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) fit_animation_length(); - set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); - ImGui::EndDisabled(); - - ImGui::SameLine(); - - auto frameNum = animation ? animation->frameNum : dummy_value(); - auto currentAnimationIndex = reference.animationIndex; - ImGui::SetNextItemWidth(widgetSize.x); - auto isLengthChanged = input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, - FRAME_NUM_MAX, STEP, STEP_FAST, - !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); - if (ImGui::IsItemActivated()) animationLengthEditIndex = currentAnimationIndex; - if (isLengthChanged && animation) - { - auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; - edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->frameNum = frameNum; - }); - } - if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); - - ImGui::SameLine(); - - auto isLoop = animation ? animation->isLoop : dummy_value(); - ImGui::SetNextItemWidth(widgetSize.x); - if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) - { - auto animationIndex = reference.animationIndex; - edit_command_push(EDIT_LOOP, Document::ANIMATIONS, - [=, this](Manager&, Document& document) - { - auto animation = command_animation_get(document, animationIndex); - if (!animation) return; - animation->isLoop = isLoop; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); } ImGui::EndDisabled(); ImGui::SameLine(); - auto info = info_get(); - auto fps = info ? info->fps : 30; - ImGui::SetNextItemWidth(widgetSize.x); - if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) - { - edit_command_push(EDIT_FPS, Document::INFO, - [=, this](Manager&, Document& document) - { - auto info = command_info_get(document); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->fps = fps; - }); - } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); + ImGui::BeginDisabled(!animation || animation->frameNum == animation_length_get(*animation)); + shortcut(manager.chords[SHORTCUT_FIT]); + if (ImGui::Button(localize.get(LABEL_FIT_ANIMATION_LENGTH), widgetSize)) fit_animation_length(); + set_item_tooltip_shortcut(localize.get(TOOLTIP_FIT_ANIMATION_LENGTH), settings.shortcutFit); + ImGui::EndDisabled(); ImGui::SameLine(); - info = info_get(); - auto createdBy = info ? info->createdBy : std::string{}; + auto frameNum = animation ? animation->frameNum : dummy_value(); + auto currentAnimationIndex = reference.animationIndex; ImGui::SetNextItemWidth(widgetSize.x); - if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) + auto isLengthChanged = + input_int_range(localize.get(LABEL_ANIMATION_LENGTH), frameNum, FRAME_NUM_MIN, FRAME_NUM_MAX, STEP, + STEP_FAST, !animation ? ImGuiInputTextFlags_DisplayEmptyRefVal : 0); + if (ImGui::IsItemActivated()) animationLengthEditIndex = currentAnimationIndex; + if (isLengthChanged && animation) { - edit_command_push(EDIT_AUTHOR, Document::INFO, + auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; + edit_command_push(EDIT_ANIMATION_LENGTH, Document::ANIMATIONS, [=, this](Manager&, Document& document) { - auto info = command_info_get(document); - if (!info) - { - document.anm2.root.children.push_back(element_make(ElementType::INFO)); - info = &document.anm2.root.children.back(); - } - info->createdBy = createdBy; + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + animation->frameNum = frameNum; }); } - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); + if (ImGui::IsItemDeactivated()) animationLengthEditIndex = -1; + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ANIMATION_LENGTH)); ImGui::SameLine(); + auto isLoop = animation ? animation->isLoop : dummy_value(); ImGui::SetNextItemWidth(widgetSize.x); - ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); - ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); - - ImGui::PopStyleVar(); + if (ImGui::Checkbox(localize.get(LABEL_LOOP), &isLoop) && animation) + { + auto animationIndex = reference.animationIndex; + edit_command_push(EDIT_LOOP, Document::ANIMATIONS, + [=, this](Manager&, Document& document) + { + auto animation = command_animation_get(document, animationIndex); + if (!animation) return; + animation->isLoop = isLoop; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_LOOP_ANIMATION)); } - ImGui::EndChild(); + ImGui::EndDisabled(); - ImGui::SetCursorPos(cursorPos); + ImGui::SameLine(); + + auto info = info_get(); + auto fps = info ? info->fps : 30; + ImGui::SetNextItemWidth(widgetSize.x); + if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) + { + edit_command_push(EDIT_FPS, Document::INFO, + [=, this](Manager&, Document& document) + { + auto info = command_info_get(document); + if (!info) + { + document.anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &document.anm2.root.children.back(); + } + info->fps = fps; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); + + ImGui::SameLine(); + + info = info_get(); + auto createdBy = info ? info->createdBy : std::string{}; + ImGui::SetNextItemWidth(widgetSize.x); + if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) + { + edit_command_push(EDIT_AUTHOR, Document::INFO, + [=, this](Manager&, Document& document) + { + auto info = command_info_get(document); + if (!info) + { + document.anm2.root.children.push_back(element_make(ElementType::INFO)); + info = &document.anm2.root.children.back(); + } + info->createdBy = createdBy; + }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); + + ImGui::SameLine(); + + ImGui::SetNextItemWidth(widgetSize.x); + ImGui::Checkbox(localize.get(LABEL_SOUND), &settings.timelineIsSound); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SOUND)); + + ImGui::PopStyleVar(); } + ImGui::EndChild(); + + ImGui::SetCursorPos(cursorPos); + } } diff --git a/src/imgui/window/timeline/popups.cpp b/src/imgui/window/timeline/popups.cpp index 9a7c961..20afaf8 100644 --- a/src/imgui/window/timeline/popups.cpp +++ b/src/imgui/window/timeline/popups.cpp @@ -36,11 +36,10 @@ namespace anm2ed::imgui { auto targetFrames = makeManyRegionReferences; auto format = settings.generateRegionNameFormat; - auto mapping = isMakeManyRegionsMapFrames ? Document::RegionFrameMapping::SET - : Document::RegionFrameMapping::PRESERVE; + auto mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET : RegionFrameMapping::PRESERVE; edit_command_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, Document::ALL, [=, this](Manager&, Document& document) mutable - { document.regions_generate_from_frames(targetFrames, format, mapping); }); + { document.anm2.regions_generate({}, targetFrames, format, mapping); }); makeManyRegionsPopup.close(); } @@ -178,16 +177,17 @@ namespace anm2ed::imgui if (!selectedFrames.empty()) { if (!isShortenChordHeld) frames_snapshot_command_push(EDIT_SHORTEN_FRAME, selectedFrames); - command_push([=, this](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); - } - document.anm2_change(Document::FRAMES); - }); + command_push( + [=, this](Manager&, Document& document) + { + for (auto frameReference : selectedFrames) + { + auto frame = command_frame_get(document, frameReference); + if (!frame) continue; + frame->duration = std::max(FRAME_DURATION_MIN, frame->duration - 1); + } + document.change(Document::FRAMES); + }); } } isShortenChordHeld = isShortenFrame; @@ -203,16 +203,17 @@ namespace anm2ed::imgui if (!selectedFrames.empty()) { if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames); - command_push([=, this](Manager&, Document& document) - { - for (auto frameReference : selectedFrames) - { - auto frame = command_frame_get(document, frameReference); - if (!frame) continue; - frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); - } - document.anm2_change(Document::FRAMES); - }); + command_push( + [=, this](Manager&, Document& document) + { + for (auto frameReference : selectedFrames) + { + auto frame = command_frame_get(document, frameReference); + if (!frame) continue; + frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1); + } + document.change(Document::FRAMES); + }); } } isExtendChordHeld = isExtendFrame; diff --git a/src/imgui/window/window.cpp b/src/imgui/window/window.cpp index ca0f2fa..9ef6747 100644 --- a/src/imgui/window/window.cpp +++ b/src/imgui/window/window.cpp @@ -181,16 +181,16 @@ namespace anm2ed::imgui void window_edit(Window& window, Document& document, const std::string& message, auto behavior) { - document.anm2_snapshot(message); + document.snapshots.anm2_push(message); behavior(); - document.anm2_change(window.changeType); + document.change(window.changeType); } void window_edit(Document& document, Document::ChangeType changeType, const std::string& message, auto behavior) { - document.anm2_snapshot(message); + document.snapshots.anm2_push(message); behavior(); - document.anm2_change(changeType); + document.change(changeType); } void window_rename_finish(Window& window, Manager& manager, int key, int count, const std::string& name) @@ -201,9 +201,8 @@ namespace anm2ed::imgui auto elementGet = window.element_get; auto renameEdit = window.renameEdit; auto renameFinish = window.rename_finish; - manager.command_push({manager.selected, - [changeType, containerType, elementType, elementGet, renameEdit, renameFinish, key, count, - name](Manager&, Document& document) mutable + manager.command_push({manager.selected, [changeType, containerType, elementType, elementGet, renameEdit, + renameFinish, key, count, name](Manager&, Document& document) mutable { auto element = elementGet ? elementGet(document.anm2, key) : nullptr; if (!element) @@ -211,10 +210,10 @@ namespace anm2ed::imgui element = child_id_get(*container, elementType, key); if (!element || element->name == name) return; - document.anm2_snapshot(localize.get(renameEdit)); + document.snapshots.anm2_push(localize.get(renameEdit)); element->name = name; if (renameFinish) renameFinish(document, *element, key, count); - document.anm2_change(changeType); + document.change(changeType); }}); } @@ -265,7 +264,7 @@ namespace anm2ed::imgui if (pasted.deserialize(window.elementType, clipboard.get(), true, &errorString, document.directory_get())) { - document.anm2_snapshot(localize.get(window.pasteEdit)); + document.snapshots.anm2_push(localize.get(window.pasteEdit)); document.anm2 = std::move(pasted); container = window_container_get(window, document.anm2); auto maxIdAfter = container ? element_child_max_id_get(*container, window.elementType) : -1; @@ -275,16 +274,11 @@ namespace anm2ed::imgui storage->selection = {maxIdAfter}; storage->reference = maxIdAfter; } - document.anm2_change(window.changeType); + document.change(window.changeType); return; } - if (window.deserializeFailedToast) - { - toasts.push(std::vformat(localize.get(window.deserializeFailedToast), std::make_format_args(errorString))); - logger.error(std::vformat(localize.get(window.deserializeFailedToast, anm2ed::ENGLISH), - std::make_format_args(errorString))); - } + if (window.deserializeFailedToast) toast_log(Level::ERROR, window.deserializeFailedToast, errorString); }; window_command_push(window, manager, settings, clipboard, paste); @@ -473,12 +467,11 @@ namespace anm2ed::imgui { if (item.id < 0) return; auto it = std::find_if(items.begin(), items.end(), [&](const AnimationDragDropItem& current) - { return current.type == item.type && current.id == item.id; }); + { return current.type == item.type && current.id == item.id; }); if (it == items.end()) items.push_back(item); } - bool is_window_animation_drag_drop_item_selected(Document& document, const Window& window, - AnimationDragDropItem item) + bool is_window_animation_drag_drop_item_selected(Document& document, const Window& window, AnimationDragDropItem item) { if (item.type == AnimationDragDropType::GROUP) return window.selection.contains(item.id); return document.animation.selection.contains(item.id); @@ -566,8 +559,8 @@ namespace anm2ed::imgui std::sort(childIndices.begin(), childIndices.end()); childIndices.erase(std::unique(childIndices.begin(), childIndices.end()), childIndices.end()); - auto movedChildIndices = anm2ed::util::vector::move_indices_to_position(animations->children, childIndices, - targetChildIndex); + auto movedChildIndices = + anm2ed::util::vector::move_indices_to_position(animations->children, childIndices, targetChildIndex); if (movedChildIndices.empty()) return; document.animation.selection.clear(); @@ -583,26 +576,24 @@ namespace anm2ed::imgui } void window_animation_move_command_push(Window& window, Manager& manager, std::vector items, - int targetGroupId, - auto target_child_index_get) + int targetGroupId, auto target_child_index_get) { if (items.empty()) return; - manager.command_push({manager.selected, [&window, items, targetGroupId, target_child_index_get](Manager&, - Document& document) - mutable - { - auto move = [&]() - { - auto animations = window_container_get(window, document.anm2); - if (!animations) return; - window_animation_items_move(window, document, items, target_child_index_get(*animations), - targetGroupId); - }; - window_edit(window, document, localize.get(EDIT_MOVE_ANIMATIONS), move); - }}); + manager.command_push( + {manager.selected, [&window, items, targetGroupId, target_child_index_get](Manager&, Document& document) mutable + { + auto move = [&]() + { + auto animations = window_container_get(window, document.anm2); + if (!animations) return; + window_animation_items_move(window, document, items, target_child_index_get(*animations), targetGroupId); + }; + window_edit(window, document, localize.get(EDIT_MOVE_ANIMATIONS), move); + }}); } - void window_animation_drag_drop_source_update(Document& document, const Window& window, AnimationDragDropItem fallback) + void window_animation_drag_drop_source_update(Document& document, const Window& window, + AnimationDragDropItem fallback) { if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; @@ -619,9 +610,9 @@ namespace anm2ed::imgui if (!ImGui::BeginDragDropTarget()) return false; bool isDelivered{}; - if (auto payload = ImGui::AcceptDragDropPayload( - "Animation Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + if (auto payload = + ImGui::AcceptDragDropPayload("Animation Drag Drop", ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { auto items = window_animation_payload_items_get(*payload); if (items.empty()) @@ -641,10 +632,11 @@ namespace anm2ed::imgui { auto targetGroupId = isDropIntoGroup ? groupId : -1; window_animation_move_command_push( - window, manager, items, targetGroupId, [groupId, dropZone, isDropIntoGroup](const Element& items) + window, manager, items, targetGroupId, + [groupId, dropZone, isDropIntoGroup](const Element& items) { - auto targetDropZone = !isDropIntoGroup && dropZone == AnimationDropZone::INSIDE ? AnimationDropZone::AFTER - : dropZone; + auto targetDropZone = + !isDropIntoGroup && dropZone == AnimationDropZone::INSIDE ? AnimationDropZone::AFTER : dropZone; return window_animation_group_child_insert_index_get(items, groupId, targetDropZone); }); isDelivered = true; @@ -748,8 +740,8 @@ namespace anm2ed::imgui for (auto& item : animations->children) if (item.type == ElementType::ANIMATION && groupIds.contains(item.groupId)) item.groupId = -1; - std::erase_if(animations->children, [&](const Element& item) - { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); + std::erase_if(animations->children, + [&](const Element& item) { return item.type == ElementType::GROUP && groupIds.contains(item.id); }); } std::string window_animation_clipboard_text_get(Document& document, const Window& window) @@ -806,7 +798,7 @@ namespace anm2ed::imgui auto& overlayDocumentId = document.overlayDocumentId; int merged{-1}; - document.anm2_snapshot(localize.get(EDIT_MERGE_ANIMATIONS)); + document.snapshots.anm2_push(localize.get(EDIT_MERGE_ANIMATIONS)); if (options.selection.empty()) { auto selected = quickSelection ? *quickSelection : std::set(selection.begin(), selection.end()); @@ -850,12 +842,11 @@ namespace anm2ed::imgui if (merged == -1) return -1; selection = {merged}; reference = {merged}; - document.anm2_change(Document::ANIMATIONS); + document.change(Document::ANIMATIONS); return merged; } - void window_spritesheets_merge(Document& document, const std::set& ids, - const SpritesheetMergeOptions& options) + void window_spritesheets_merge(Document& document, const std::set& ids, const SpritesheetMergeOptions& options) { if (ids.size() <= 1) return; @@ -869,17 +860,15 @@ namespace anm2ed::imgui document.spritesheet.reference = baseID; document.region.reference = -1; document.region.selection.clear(); - toasts.push(localize.get(TOAST_MERGE_SPRITESHEETS)); - logger.info(localize.get(TOAST_MERGE_SPRITESHEETS, anm2ed::ENGLISH)); + toast_log(Level::INFO, TOAST_MERGE_SPRITESHEETS); } else { - toasts.push(localize.get(TOAST_MERGE_SPRITESHEETS_FAILED)); - logger.error(localize.get(TOAST_MERGE_SPRITESHEETS_FAILED, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_MERGE_SPRITESHEETS_FAILED); } }; - document.anm2_textures_snapshot(localize.get(EDIT_MERGE_SPRITESHEETS)); + document.snapshots.anm2_textures_push(localize.get(EDIT_MERGE_SPRITESHEETS)); behavior(); document.change(Document::ALL); } @@ -898,17 +887,15 @@ namespace anm2ed::imgui { if (document.spritesheet_pack(id, std::max(0, padding))) { - toasts.push(localize.get(TOAST_PACK_SPRITESHEET)); - logger.info(localize.get(TOAST_PACK_SPRITESHEET, anm2ed::ENGLISH)); + toast_log(Level::INFO, TOAST_PACK_SPRITESHEET); } else { - toasts.push(localize.get(TOAST_PACK_SPRITESHEET_FAILED)); - logger.error(localize.get(TOAST_PACK_SPRITESHEET_FAILED, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_PACK_SPRITESHEET_FAILED); } }; - document.anm2_textures_snapshot(localize.get(EDIT_PACK_SPRITESHEET)); + document.snapshots.anm2_textures_push(localize.get(EDIT_PACK_SPRITESHEET)); behavior(); document.change(Document::SPRITESHEETS); } @@ -928,15 +915,11 @@ namespace anm2ed::imgui if (texture->write_png(spritesheet->path)) { document.spritesheet_hash_set_saved(id); - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); } else { - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), std::make_format_args(id, pathString))); - logger.error(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); } } } @@ -981,8 +964,7 @@ namespace anm2ed::imgui if (options.path.empty()) pathString = "in memory"; if (options.path.empty() && !options.isMakeSpritesheet) { - toasts.push(localize.get(TOAST_EXPORT_REGION_PATH_EMPTY)); - logger.error(localize.get(TOAST_EXPORT_REGION_PATH_EMPTY, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); return false; } @@ -991,9 +973,7 @@ namespace anm2ed::imgui auto texture = document.texture_get(options.spritesheetId); if (!spritesheet || !region || !texture || !texture->is_valid()) { - toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args("", pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), - std::make_format_args("", pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, "", pathString); return false; } @@ -1003,9 +983,7 @@ namespace anm2ed::imgui ivec2 exportSize{}; if (!window_region_pixels_get(sourceRegion, *texture, pixels, exportSize)) { - toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args(regionName, pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), - std::make_format_args(regionName, pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, regionName, pathString); return false; } @@ -1019,10 +997,7 @@ namespace anm2ed::imgui path::ensure_directory(outputPath.parent_path()); if (!Texture::write_pixels_png(outputPath, exportSize, pixels.data())) { - toasts.push( - std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED), std::make_format_args(regionName, pathString))); - logger.error(std::vformat(localize.get(TOAST_EXPORT_REGION_FAILED, anm2ed::ENGLISH), - std::make_format_args(regionName, pathString))); + toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, regionName, pathString); return false; } } @@ -1030,7 +1005,7 @@ namespace anm2ed::imgui exportedSpritesheetId = -1; if (options.isMakeSpritesheet || options.isRemoveCurrent) { - document.anm2_textures_snapshot(localize.get(EDIT_EXPORT_REGION)); + document.snapshots.anm2_textures_push(localize.get(EDIT_EXPORT_REGION)); if (options.isMakeSpritesheet) { @@ -1081,9 +1056,7 @@ namespace anm2ed::imgui document.change(Document::SPRITESHEETS); } - toasts.push(std::vformat(localize.get(TOAST_EXPORT_REGION), std::make_format_args(regionName, pathString))); - logger.info( - std::vformat(localize.get(TOAST_EXPORT_REGION, anm2ed::ENGLISH), std::make_format_args(regionName, pathString))); + toast_log(Level::INFO, TOAST_EXPORT_REGION, regionName, pathString); return true; } @@ -1106,47 +1079,51 @@ namespace anm2ed::imgui auto& selection = window.storage_get(document).selection; if (window_flag_has(window.flags, WINDOW_ADD)) - actions.add(ACTION_ADD, []() { return true; }, - [&]() { window_add(window, manager, settings, document, clipboard); }, window.addTooltip); + actions.add( + ACTION_ADD, []() { return true; }, [&]() { window_add(window, manager, settings, document, clipboard); }, + window.addTooltip); if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add(ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }, - window.duplicateTooltip); + actions.add( + ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }, + window.duplicateTooltip); if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add(ACTION_MERGE, - [&]() - { - if (window.elementType == ElementType::ANIMATION) - { - if (is_window_animation_group_selected(window)) return is_window_merge_available(window, document); - return selection.size() == 1; - } - return selection.size() == 1; - }, - [&]() - { - auto command = window.merge_open && !is_window_animation_group_selected(window) ? window.merge_open - : window.merge; - window_command_run(window, manager, settings, document, clipboard, command); - }, - window.mergeTooltip); + actions.add( + ACTION_MERGE, + [&]() + { + if (window.elementType == ElementType::ANIMATION) + { + if (is_window_animation_group_selected(window)) return is_window_merge_available(window, document); + return selection.size() == 1; + } + return selection.size() == 1; + }, + [&]() + { + auto command = + window.merge_open && !is_window_animation_group_selected(window) ? window.merge_open : window.merge; + window_command_run(window, manager, settings, document, clipboard, command); + }, + window.mergeTooltip); if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add(ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, - window.removeTooltip); + actions.add( + ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, [&]() + { window_command_run(window, manager, settings, document, clipboard, window.remove); }, window.removeTooltip); if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) - actions.add(ACTION_REMOVE_UNUSED, []() { return true; }, - [&]() { window_remove_unused(window, manager, settings, document, clipboard); }, - window.removeUnusedTooltip); + actions.add( + ACTION_REMOVE_UNUSED, []() { return true; }, + [&]() { window_remove_unused(window, manager, settings, document, clipboard); }, window.removeUnusedTooltip); if (window_flag_has(window.flags, WINDOW_DEFAULT)) - actions.add(ACTION_DEFAULT, [&]() { return selection.size() == 1; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }, - window.defaultTooltip); + actions.add( + ACTION_DEFAULT, [&]() { return selection.size() == 1; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }, + window.defaultTooltip); return actions; } @@ -1164,56 +1141,67 @@ namespace anm2ed::imgui } if (window_flag_has(window.flags, WINDOW_RENAME)) - actions.add(ACTION_RENAME, [&]() { return is_window_item_renameable(window, document); }, - [&]() - { - if (selection.size() == 1) - window.renameQueued = *selection.begin(); - else if (window.elementType == ElementType::ANIMATION && window.selection.size() == 1) - window.renameQueued = window_animation_group_key_get(*window.selection.begin()); - }); + actions.add( + ACTION_RENAME, [&]() { return is_window_item_renameable(window, document); }, + [&]() + { + if (selection.size() == 1) + window.renameQueued = *selection.begin(); + else if (window.elementType == ElementType::ANIMATION && window.selection.size() == 1) + window.renameQueued = window_animation_group_key_get(*window.selection.begin()); + }); if (window_flag_has(window.flags, WINDOW_PROPERTIES)) - actions.add(ACTION_PROPERTIES, [&]() { return selection.size() == 1; }, - [&]() { window_properties(window, manager, *selection.begin()); }); + actions.add( + ACTION_PROPERTIES, [&]() { return selection.size() == 1; }, + [&]() { window_properties(window, manager, *selection.begin()); }); if (window_flag_has(window.flags, WINDOW_ADD)) - actions.add(ACTION_ADD, []() { return true; }, - [&]() { window_add(window, manager, settings, document, clipboard); }); + actions.add( + ACTION_ADD, []() { return true; }, [&]() { window_add(window, manager, settings, document, clipboard); }); if (window_flag_has(window.flags, WINDOW_DUPLICATE)) - actions.add(ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }); + actions.add( + ACTION_DUPLICATE, [&]() { return is_window_item_selected(window, document); }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.duplicate); }); if (window_flag_has(window.flags, WINDOW_MERGE)) - actions.add(ACTION_MERGE, [&]() { return is_window_merge_available(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge); }); + actions.add( + ACTION_MERGE, [&]() { return is_window_merge_available(window, document); }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge); }); if (window_flag_has(window.flags, WINDOW_GROUP)) - actions.add(ACTION_GROUP, - [&]() - { - if (window.elementType == ElementType::ANIMATION) - return !window_animation_groupable_indices_get(document).empty(); - return !selection.empty(); - }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.group); }); + actions.add( + ACTION_GROUP, + [&]() + { + if (window.elementType == ElementType::ANIMATION) + return !window_animation_groupable_indices_get(document).empty(); + return !selection.empty(); + }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.group); }); if (window_flag_has(window.flags, WINDOW_REMOVE)) - actions.add(ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); + actions.add( + ACTION_REMOVE, [&]() { return !selection.empty() || is_window_animation_group_selected(window); }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); if (window_flag_has(window.flags, WINDOW_REMOVE_UNUSED)) - actions.add(ACTION_REMOVE_UNUSED, []() { return true; }, - [&]() { window_remove_unused(window, manager, settings, document, clipboard); }); + actions.add( + ACTION_REMOVE_UNUSED, []() { return true; }, + [&]() { window_remove_unused(window, manager, settings, document, clipboard); }); if (window_flag_has(window.flags, WINDOW_DEFAULT)) - actions.add(ACTION_DEFAULT, [&]() { return selection.size() == 1; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }); + actions.add( + ACTION_DEFAULT, [&]() { return selection.size() == 1; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.default_set); }); actions.separator(); if (window_flag_has(window.flags, WINDOW_CUT)) - actions.add(ACTION_CUT, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.cut); }); + actions.add( + ACTION_CUT, [&]() { return is_window_item_selected(window, document); }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.cut); }); if (window_flag_has(window.flags, WINDOW_COPY)) - actions.add(ACTION_COPY, [&]() { return is_window_item_selected(window, document); }, - [&]() { window_copy(window, manager, settings, document, clipboard); }); + actions.add( + ACTION_COPY, [&]() { return is_window_item_selected(window, document); }, + [&]() { window_copy(window, manager, settings, document, clipboard); }); if (window_flag_has(window.flags, WINDOW_PASTE)) - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, - [&]() { window_paste(window, manager, settings, document, clipboard); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, + [&]() { window_paste(window, manager, settings, document, clipboard); }); return actions; } @@ -1462,8 +1450,8 @@ namespace anm2ed::imgui window.renameEdit = SNAPSHOT_RENAME_ANIMATION; window.pasteEdit = EDIT_PASTE_ANIMATIONS; window.deserializeFailedToast = TOAST_DESERIALIZE_ANIMATIONS_FAILED; - window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_GROUP | WINDOW_REMOVE | WINDOW_DEFAULT | WINDOW_CUT | - WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; + window.flags = WINDOW_ADD | WINDOW_DUPLICATE | WINDOW_MERGE | WINDOW_GROUP | WINDOW_REMOVE | WINDOW_DEFAULT | + WINDOW_CUT | WINDOW_COPY | WINDOW_PASTE | WINDOW_RENAME; window.popup = PopupHelper(LABEL_ANIMATIONS_MERGE_POPUP); window.storage_get = [](Document& document) -> Storage& { return document.animation; }; window.element_get = [](Anm2& anm2, int index) { return anm2.element_get(ElementType::ANIMATION, index); }; @@ -1517,9 +1505,9 @@ namespace anm2ed::imgui if (ImGui::BeginDragDropTarget()) { - if (auto payload = ImGui::AcceptDragDropPayload( - "Animation Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + if (auto payload = + ImGui::AcceptDragDropPayload("Animation Drag Drop", ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { auto items = window_animation_payload_items_get(*payload); if (items.empty()) @@ -1551,8 +1539,8 @@ namespace anm2ed::imgui return false; }; - window.rows_update = [](Window& window, Manager& manager, Settings&, Resources& resources, Clipboard&, - Document& document, ImVec2) + window.rows_update = + [](Window& window, Manager& manager, Settings&, Resources& resources, Clipboard&, Document& document, ImVec2) { auto container = window_container_get(window, document.anm2); auto& storage = window.storage_get(document); @@ -1752,10 +1740,9 @@ namespace anm2ed::imgui } ImGui::SetNextItemOpen(item.isExpanded, ImGuiCond_Always); auto treeFlags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_SpanAvailWidth; - auto tree = - tree_node_input_text(label, std::format("###Document #{} Animation Group #{}", manager.selected, - item.id), - name, isGroupSelected, treeFlags, window.renameState); + auto tree = tree_node_input_text( + label, std::format("###Document #{} Animation Group #{}", manager.selected, item.id), name, + isGroupSelected, treeFlags, window.renameState); auto groupItemMin = ImGui::GetItemRectMin(); auto groupItemMax = ImGui::GetItemRectMax(); auto isGroupOpen = tree.isOpen; @@ -1774,13 +1761,13 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [targetGroupId, targetName](Manager&, Document& document) { auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto group = animations ? child_id_get(*animations, ElementType::GROUP, - targetGroupId) - : nullptr; + auto group = animations + ? child_id_get(*animations, ElementType::GROUP, targetGroupId) + : nullptr; if (!group || group->name == targetName) return; - document.anm2_snapshot(localize.get(EDIT_RENAME_GROUP)); + document.snapshots.anm2_push(localize.get(EDIT_RENAME_GROUP)); group->name = targetName; - document.anm2_change(Document::ANIMATIONS); + document.change(Document::ANIMATIONS); }}); } window.renameId = -1; @@ -1793,13 +1780,13 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [targetGroupId, isGroupOpen](Manager&, Document& document) { auto animations = document.anm2.element_get(ElementType::ANIMATIONS); - auto group = animations ? child_id_get(*animations, ElementType::GROUP, - targetGroupId) - : nullptr; + auto group = animations + ? child_id_get(*animations, ElementType::GROUP, targetGroupId) + : nullptr; if (!group || group->isExpanded == isGroupOpen) return; - document.anm2_snapshot(localize.get(EDIT_TOGGLE_GROUP_EXPANDED)); + document.snapshots.anm2_push(localize.get(EDIT_TOGGLE_GROUP_EXPANDED)); group->isExpanded = isGroupOpen; - document.anm2_change(Document::ANIMATIONS); + document.change(Document::ANIMATIONS); }}); } if (isGroupClicked) group_selection_apply(item.id); @@ -1866,9 +1853,9 @@ namespace anm2ed::imgui auto items = animations(); if (!items) return; auto groupIds = window_animation_group_ids_get(*items); - auto targetGroupId = - window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) ? *window.selection.begin() - : -1; + auto targetGroupId = window.selection.size() == 1 && groupIds.contains(*window.selection.begin()) + ? *window.selection.begin() + : -1; auto animation = element_make(ElementType::ANIMATION); animation.name = localize.get(TEXT_NEW_ANIMATION); @@ -1887,17 +1874,16 @@ namespace anm2ed::imgui referenceNullAnimations = child_first_get(*referenceAnimation, ElementType::NULL_ANIMATIONS); } - animation.children.push_back(window_track_container_shell_copy(referenceLayerAnimations, - ElementType::LAYER_ANIMATIONS, - ElementType::LAYER_ANIMATION)); - animation.children.push_back(window_track_container_shell_copy(referenceNullAnimations, - ElementType::NULL_ANIMATIONS, - ElementType::NULL_ANIMATION)); + animation.children.push_back(window_track_container_shell_copy( + referenceLayerAnimations, ElementType::LAYER_ANIMATIONS, ElementType::LAYER_ANIMATION)); + animation.children.push_back(window_track_container_shell_copy( + referenceNullAnimations, ElementType::NULL_ANIMATIONS, ElementType::NULL_ANIMATION)); animation.children.push_back(element_make(ElementType::TRIGGERS)); auto count = animation_count(); auto index = count; - if (!selection.empty()) index = std::min(*selection.rbegin() + 1, count); + if (!selection.empty()) + index = std::min(*selection.rbegin() + 1, count); else if (targetGroupId != -1) { auto groupIndices = window_animation_group_indices_get(*items, targetGroupId); @@ -1939,7 +1925,7 @@ namespace anm2ed::imgui for (auto& item : items->children) if (item.type == ElementType::ANIMATION && groupSelection.contains(item.groupId)) item.groupId = -1; std::erase_if(items->children, [&](const Element& item) - { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); + { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); } for (auto it = selection.rbegin(); it != selection.rend(); ++it) { @@ -2008,13 +1994,14 @@ namespace anm2ed::imgui { auto& mergeSelection = document.merge.selection; auto& mergeReference = document.merge.reference; - auto quickSelection = mergeSelection.empty() ? window_animation_selected_indices_get(document, window) - : std::set{}; + auto quickSelection = + mergeSelection.empty() ? window_animation_selected_indices_get(document, window) : std::set{}; auto quickGroupSelection = mergeSelection.empty() ? window.selection : std::set{}; - auto merged = window_animations_merge(document, {.selection = mergeSelection, - .reference = mergeReference, - .type = (merge::Type)settings.mergeType, - .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}, + auto merged = window_animations_merge(document, + {.selection = mergeSelection, + .reference = mergeReference, + .type = (merge::Type)settings.mergeType, + .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}, mergeSelection.empty() ? &quickSelection : nullptr, mergeSelection.empty() ? &quickGroupSelection : nullptr); if (merged != -1) @@ -2117,7 +2104,7 @@ namespace anm2ed::imgui items->children.erase(items->children.begin() + childIndex); } std::erase_if(items->children, [&](const Element& item) - { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); + { return item.type == ElementType::GROUP && groupSelection.contains(item.id); }); selection.clear(); window.selection.clear(); }; @@ -2178,10 +2165,7 @@ namespace anm2ed::imgui } else { - toasts.push( - std::vformat(localize.get(TOAST_DESERIALIZE_ANIMATIONS_FAILED), std::make_format_args(errorString))); - logger.error(std::vformat(localize.get(TOAST_DESERIALIZE_ANIMATIONS_FAILED, anm2ed::ENGLISH), - std::make_format_args(errorString))); + toast_log(Level::ERROR, TOAST_DESERIALIZE_ANIMATIONS_FAILED, errorString); } }; @@ -2457,7 +2441,7 @@ namespace anm2ed::imgui } }; - document.anm2_snapshot(localize.get(EDIT_TRIM_REGIONS)); + document.snapshots.anm2_push(localize.get(EDIT_TRIM_REGIONS)); behavior(); document.change(Document::SPRITESHEETS); }; @@ -2488,7 +2472,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.deserialize(ElementType::REGION, clipboard.get(), true, &errorString, {}, spritesheetReference)) { - document.anm2_snapshot(localize.get(EDIT_PASTE_REGIONS)); + document.snapshots.anm2_push(localize.get(EDIT_PASTE_REGIONS)); anm2 = std::move(pasted); if (auto pastedSpritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetReference)) { @@ -2506,13 +2490,11 @@ namespace anm2ed::imgui reference = maxRegionIdAfter; } } - document.anm2_change(Document::SPRITESHEETS); + document.change(Document::SPRITESHEETS); } else { - toasts.push(std::vformat(localize.get(TOAST_DESERIALIZE_REGIONS_FAILED), std::make_format_args(errorString))); - logger.error(std::vformat(localize.get(TOAST_DESERIALIZE_REGIONS_FAILED, anm2ed::ENGLISH), - std::make_format_args(errorString))); + toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); } }; window.begin_update = [](Window& window, Manager& manager, Settings&, Resources&, Clipboard&, Document& document) @@ -2606,8 +2588,8 @@ namespace anm2ed::imgui { auto cursorPos = ImGui::GetCursorPos(); auto regionChildMin = ImGui::GetWindowPos(); - auto regionChildMax = ImVec2(regionChildMin.x + ImGui::GetWindowSize().x, - regionChildMin.y + ImGui::GetWindowSize().y); + auto regionChildMax = + ImVec2(regionChildMin.x + ImGui::GetWindowSize().x, regionChildMin.y + ImGui::GetWindowSize().y); ImGui::SetNextItemSelectionUserData(i); ImGui::SetNextItemStorageID(id); @@ -2716,9 +2698,9 @@ namespace anm2ed::imgui bool isDropLineAfter{}; if (ImGui::BeginDragDropTarget()) { - if (auto payload = ImGui::AcceptDragDropPayload( - "Region Drag Drop", - ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) + if (auto payload = + ImGui::AcceptDragDropPayload("Region Drag Drop", ImGuiDragDropFlags_AcceptBeforeDelivery | + ImGuiDragDropFlags_AcceptNoDrawDefaultRect)) { isDropLineActive = true; isDropLineAfter = is_drop_after(regionRowMin, regionRowMax); @@ -2865,26 +2847,32 @@ namespace anm2ed::imgui Actions actions{}; actions_undo_redo_add(actions, manager, document); actions.separator(); - actions.add(ACTION_PROPERTIES, [&]() { return selection.size() == 1 && (bool)window.properties; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.properties); }); - actions.add(ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add(ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - actions.add(ACTION_TRIM, [&]() { return !selection.empty() && (bool)window.trim; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.trim); }, - TOOLTIP_TRIM_REGIONS); - actions.add(ACTION_EXPORT, [&]() { return selection.size() == 1; }, - [&]() - { - window.editId = *selection.begin(); - window.popup2.open(); - }); + actions.add( + ACTION_PROPERTIES, [&]() { return selection.size() == 1 && (bool)window.properties; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.properties); }); + actions.add( + ACTION_ADD, [&]() { return (bool)window.add; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); + actions.add( + ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); + actions.add( + ACTION_TRIM, [&]() { return !selection.empty() && (bool)window.trim; }, [&]() + { window_command_run(window, manager, settings, document, clipboard, window.trim); }, TOOLTIP_TRIM_REGIONS); + actions.add( + ACTION_EXPORT, [&]() { return selection.size() == 1; }, + [&]() + { + window.editId = *selection.begin(); + window.popup2.open(); + }); actions.separator(); - actions.add(ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); + actions.add( + ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); actions_popup_draw("##Region Context Menu", actions, settings); ImGui::PopStyleVar(2); }; @@ -2915,8 +2903,8 @@ namespace anm2ed::imgui window_command_run(window, manager, settings, document, clipboard, window.remove); set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_UNUSED_REGIONS), settings.shortcutAdd); }; - window.popup_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard&, - Document& document) + window.popup_update = + [](Window& window, Manager& manager, Settings& settings, Resources& resources, Clipboard&, Document& document) { auto& anm2 = document.anm2; auto& spritesheetReference = document.spritesheet.reference; @@ -3025,8 +3013,7 @@ namespace anm2ed::imgui { auto set = [&]() { - auto target = - child_id_get(*spritesheet, ElementType::REGION, editedReference); + auto target = child_id_get(*spritesheet, ElementType::REGION, editedReference); if (!target) return; auto changed = editedRegion; changed.type = ElementType::REGION; @@ -3191,9 +3178,7 @@ namespace anm2ed::imgui auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); if (!spritesheet) continue; auto pathString = path::to_utf8(spritesheet->path); - toasts.push(std::vformat(localize.get(TOAST_REMOVE_SPRITESHEET), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_REMOVE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_REMOVE_SPRITESHEET, id, pathString); element_child_id_erase(*items, ElementType::SPRITESHEET, id); } }; @@ -3216,15 +3201,11 @@ namespace anm2ed::imgui if (!spritesheet) continue; document.spritesheet_hash_set_saved(id); auto pathString = path::to_utf8(spritesheet->path); - toasts.push(std::vformat(localize.get(TOAST_RELOAD_SPRITESHEET), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_RELOAD_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, pathString); } }; window.save = [](Window&, Manager&, Settings&, Document& document, Clipboard&) - { - window_spritesheets_save(document, document.spritesheet.selection); - }; + { window_spritesheets_save(document, document.spritesheet.selection); }; window.merge_open = [](Window& window, Manager&, Settings&, Document& document, Clipboard&) { auto& selection = document.spritesheet.selection; @@ -3275,7 +3256,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.deserialize(ElementType::SPRITESHEET, clipboard.get(), true, &errorString, document.directory_get())) { - document.anm2_snapshot(localize.get(EDIT_PASTE_SPRITESHEETS)); + document.snapshots.anm2_push(localize.get(EDIT_PASTE_SPRITESHEETS)); anm2 = std::move(pasted); if (auto pastedItems = anm2.element_get(ElementType::SPRITESHEETS)) { @@ -3289,14 +3270,11 @@ namespace anm2ed::imgui region.selection.clear(); } } - document.anm2_change(Document::SPRITESHEETS); + document.change(Document::SPRITESHEETS); } else { - toasts.push( - std::vformat(localize.get(TOAST_DESERIALIZE_SPRITESHEETS_FAILED), std::make_format_args(errorString))); - logger.error(std::vformat(localize.get(TOAST_DESERIALIZE_SPRITESHEETS_FAILED, anm2ed::ENGLISH), - std::make_format_args(errorString))); + toast_log(Level::ERROR, TOAST_DESERIALIZE_SPRITESHEETS_FAILED, errorString); } }; window.rows_update = @@ -3377,7 +3355,8 @@ namespace anm2ed::imgui ImGui::SetNextItemStorageID(id); if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); auto isActivated = ImGui::Selectable("##Spritesheet Selectable", isSelected, 0, spritesheetChildSize); - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + auto isClicked = + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); if (isActivated || isClicked) { document.editTarget = Document::EditTarget::SPRITESHEET; @@ -3520,44 +3499,55 @@ namespace anm2ed::imgui Actions actions{}; actions_undo_redo_add(actions, manager, document); actions.separator(); - actions.add(ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); - actions.add(ACTION_SET_FILE_PATH, [&]() { return selection.size() == 1 && (bool)window.path_set; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.path_set); }); - actions.add(ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add(ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - actions.add(ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); - actions.add(ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); - actions.add(ACTION_MERGE, [&]() { return selection.size() > 1 && (bool)window.merge_open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge_open); }); - actions.add(ACTION_PACK, [&]() { return isPackable; }, - [&]() - { - window.editId = *selection.begin(); - window.popup2.open(); - }, - TOOLTIP_PACK_SPRITESHEET); - actions.add(ACTION_SAVE, [&]() { return !selection.empty(); }, - [&]() - { - if (settings.fileIsWarnOverwrite) - { - window.selection2 = selection; - window.popup3.open(); - } - else if (window.save) - window_command_run(window, manager, settings, document, clipboard, window.save); - }, - TOOLTIP_SAVE_SPRITESHEETS); + actions.add( + ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); + actions.add( + ACTION_SET_FILE_PATH, [&]() { return selection.size() == 1 && (bool)window.path_set; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.path_set); }); + actions.add( + ACTION_ADD, [&]() { return (bool)window.add; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); + actions.add( + ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); + actions.add( + ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); + actions.add( + ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); + actions.add( + ACTION_MERGE, [&]() { return selection.size() > 1 && (bool)window.merge_open; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.merge_open); }); + actions.add( + ACTION_PACK, [&]() { return isPackable; }, + [&]() + { + window.editId = *selection.begin(); + window.popup2.open(); + }, + TOOLTIP_PACK_SPRITESHEET); + actions.add( + ACTION_SAVE, [&]() { return !selection.empty(); }, + [&]() + { + if (settings.fileIsWarnOverwrite) + { + window.selection2 = selection; + window.popup3.open(); + } + else if (window.save) + window_command_run(window, manager, settings, document, clipboard, window.save); + }, + TOOLTIP_SAVE_SPRITESHEETS); actions.separator(); - actions.add(ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); + actions.add( + ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); actions_popup_draw("##Spritesheet Context Menu", actions, settings); ImGui::PopStyleVar(2); }; @@ -3568,15 +3558,17 @@ namespace anm2ed::imgui auto rowOneWidgetSize = widget_size_with_row_get(3); Actions rowOneActions{}; - rowOneActions.add(ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }, - TOOLTIP_ADD_SPRITESHEET); - rowOneActions.add(ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }, - TOOLTIP_RELOAD_SPRITESHEETS); - rowOneActions.add(ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }, - TOOLTIP_REPLACE_SPRITESHEET); + rowOneActions.add( + ACTION_ADD, [&]() { return (bool)window.add; }, [&]() + { window_command_run(window, manager, settings, document, clipboard, window.add); }, TOOLTIP_ADD_SPRITESHEET); + rowOneActions.add( + ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }, + TOOLTIP_RELOAD_SPRITESHEETS); + rowOneActions.add( + ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }, + TOOLTIP_REPLACE_SPRITESHEET); bool isSameLine{}; for (auto& action : rowOneActions.items) @@ -3617,10 +3609,7 @@ namespace anm2ed::imgui { document.spritesheet_hash_set_saved(id); auto pathString = path::to_utf8(spritesheet->path); - toasts.push(std::vformat(localize.get(TOAST_REPLACE_SPRITESHEET), - std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_REPLACE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_REPLACE_SPRITESHEET, id, pathString); } }}); } @@ -3646,20 +3635,13 @@ namespace anm2ed::imgui path::ensure_directory(newPath.parent_path()); if (!texture->write_png(newPath)) { - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED), - std::make_format_args(id, pathString))); - logger.error( - std::vformat(localize.get(TOAST_SAVE_SPRITESHEET_FAILED, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); return; } spritesheet->path = newPath; document.texturePaths[id] = spritesheet->path; document.spritesheet_hash_set_saved(id); - toasts.push(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET), - std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_SAVE_SPRITESHEET, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_SAVE_SPRITESHEET, id, pathString); }; window_edit(document, Document::SPRITESHEETS, @@ -3671,21 +3653,23 @@ namespace anm2ed::imgui auto rowTwoWidgetSize = widget_size_with_row_get(2); Actions rowTwoActions{}; - rowTwoActions.add(ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, - TOOLTIP_REMOVE_UNUSED_SPRITESHEETS); - rowTwoActions.add(ACTION_SAVE, [&]() { return !selection.empty(); }, - [&]() - { - if (settings.fileIsWarnOverwrite) - { - window.selection2 = selection; - window.popup3.open(); - } - else if (window.save) - window_command_run(window, manager, settings, document, clipboard, window.save); - }, - TOOLTIP_SAVE_SPRITESHEETS); + rowTwoActions.add( + ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }, + TOOLTIP_REMOVE_UNUSED_SPRITESHEETS); + rowTwoActions.add( + ACTION_SAVE, [&]() { return !selection.empty(); }, + [&]() + { + if (settings.fileIsWarnOverwrite) + { + window.selection2 = selection; + window.popup3.open(); + } + else if (window.save) + window_command_run(window, manager, settings, document, clipboard, window.save); + }, + TOOLTIP_SAVE_SPRITESHEETS); isSameLine = false; for (auto& action : rowTwoActions.items) @@ -3757,9 +3741,7 @@ namespace anm2ed::imgui .isMakePrimaryRegion = settings.mergeSpritesheetsIsMakePrimaryRegion, .regionOrigin = (origin::Type)settings.mergeSpritesheetsRegionOrigin}; manager.command_push({manager.selected, [queuedSelection, options](Manager&, Document& document) mutable - { - window_spritesheets_merge(document, queuedSelection, options); - }}); + { window_spritesheets_merge(document, queuedSelection, options); }}); close(); } ImGui::EndDisabled(); @@ -3889,9 +3871,7 @@ namespace anm2ed::imgui if (!sound) continue; document.sound_reload(id); auto pathString = path::to_utf8(sound->path); - toasts.push(std::vformat(localize.get(TOAST_RELOAD_SOUND), std::make_format_args(id, pathString))); - logger.info( - std::vformat(localize.get(TOAST_RELOAD_SOUND, anm2ed::ENGLISH), std::make_format_args(id, pathString))); + toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, pathString); } }; @@ -3934,7 +3914,7 @@ namespace anm2ed::imgui std::string errorString{}; if (pasted.deserialize(ElementType::SOUND_ELEMENT, clipboard.get(), true, &errorString, document.directory_get())) { - document.anm2_snapshot(localize.get(TOAST_SOUNDS_PASTE)); + document.snapshots.anm2_push(localize.get(TOAST_SOUNDS_PASTE)); anm2 = std::move(pasted); if (auto pastedSounds = anm2.element_get(ElementType::SOUNDS)) { @@ -3946,13 +3926,11 @@ namespace anm2ed::imgui reference = maxSoundIdAfter; } } - document.anm2_change(Document::SOUNDS); + document.change(Document::SOUNDS); } else { - toasts.push(std::vformat(localize.get(TOAST_SOUNDS_DESERIALIZE_ERROR), std::make_format_args(errorString))); - logger.error(std::vformat(localize.get(TOAST_SOUNDS_DESERIALIZE_ERROR, anm2ed::ENGLISH), - std::make_format_args(errorString))); + toast_log(Level::ERROR, TOAST_SOUNDS_DESERIALIZE_ERROR, errorString); } }; window.rows_update = [](Window& window, Manager& manager, Settings& settings, Resources& resources, @@ -4027,7 +4005,8 @@ namespace anm2ed::imgui ImGui::SetNextItemStorageID(id); if (scrollTargetId == id) ImGui::SetKeyboardFocusHere(); auto isActivated = ImGui::Selectable("##Sound Selectable", isSelected, 0, soundChildSize); - auto isClicked = ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + auto isClicked = + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); if (isActivated || isClicked) { reference = id; @@ -4126,23 +4105,31 @@ namespace anm2ed::imgui Actions actions{}; actions_undo_redo_add(actions, manager, document); actions.separator(); - actions.add(ACTION_PLAY, [&]() { return selection.size() == 1; }, [&]() { play(*selection.begin()); }, - STRING_UNDEFINED, -1); - actions.add(ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); - actions.add(ACTION_ADD, [&]() { return (bool)window.add; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); - actions.add(ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); - actions.add(ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); - actions.add(ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); + actions.add( + ACTION_PLAY, [&]() { return selection.size() == 1; }, [&]() { play(*selection.begin()); }, STRING_UNDEFINED, + -1); + actions.add( + ACTION_OPEN_DIRECTORY, [&]() { return selection.size() == 1 && (bool)window.open; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.open); }); + actions.add( + ACTION_ADD, [&]() { return (bool)window.add; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.add); }); + actions.add( + ACTION_REMOVE_UNUSED, [&]() { return (bool)window.remove; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.remove); }); + actions.add( + ACTION_RELOAD, [&]() { return !selection.empty() && (bool)window.reload; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.reload); }); + actions.add( + ACTION_REPLACE, [&]() { return selection.size() == 1 && (bool)window.replace; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.replace); }); actions.separator(); - actions.add(ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); - actions.add(ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, - [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); + actions.add( + ACTION_COPY, [&]() { return !selection.empty() && (bool)window.copy; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.copy); }); + actions.add( + ACTION_PASTE, [&]() { return !clipboard.is_empty() && (bool)window.paste; }, + [&]() { window_command_run(window, manager, settings, document, clipboard, window.paste); }); actions_popup_draw("##Sound Context Menu", actions, settings); ImGui::PopStyleVar(2); }; @@ -4197,23 +4184,20 @@ namespace anm2ed::imgui { auto id = *selection.begin(); auto dialogPath = window.dialog->path; - manager.command_push( - {manager.selected, [id, dialogPath](Manager&, Document& document) - { - auto behavior = [&]() - { - auto sound = document.anm2.element_get(ElementType::SOUND_ELEMENT, id); - if (!sound) return; - sound->path = window_asset_path_get(document, dialogPath); - document.sound_reload(id); - auto pathString = path::to_utf8(sound->path); - toasts.push(std::vformat(localize.get(TOAST_REPLACE_SOUND), std::make_format_args(id, pathString))); - logger.info(std::vformat(localize.get(TOAST_REPLACE_SOUND, anm2ed::ENGLISH), - std::make_format_args(id, pathString))); - }; + manager.command_push({manager.selected, [id, dialogPath](Manager&, Document& document) + { + auto behavior = [&]() + { + auto sound = document.anm2.element_get(ElementType::SOUND_ELEMENT, id); + if (!sound) return; + sound->path = window_asset_path_get(document, dialogPath); + document.sound_reload(id); + auto pathString = path::to_utf8(sound->path); + toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, pathString); + }; - window_edit(document, Document::SOUNDS, localize.get(EDIT_REPLACE_SOUND), behavior); - }}); + window_edit(document, Document::SOUNDS, localize.get(EDIT_REPLACE_SOUND), behavior); + }}); } window.dialog->reset(); } @@ -4303,18 +4287,17 @@ namespace anm2ed::imgui return; } - auto target = - child_id_get(*layers, ElementType::LAYER_ELEMENT, editedReference); + auto target = child_id_get(*layers, ElementType::LAYER_ELEMENT, editedReference); if (!target) return; changed.id = editedReference; *target = changed; document.layer.selection = {editedReference}; }; - window_edit(document, Document::LAYERS, - localize.get(editedReference == -1 ? EDIT_ADD_LAYER - : EDIT_SET_LAYER_PROPERTIES), - behavior); + window_edit( + document, Document::LAYERS, + localize.get(editedReference == -1 ? EDIT_ADD_LAYER : EDIT_SET_LAYER_PROPERTIES), + behavior); }}); manager.layer_properties_close(); @@ -4389,39 +4372,38 @@ namespace anm2ed::imgui { auto editedNull = null; auto editedReference = reference; - manager.command_push({manager.selected, [&window, editedNull, editedReference](Manager&, Document& document) - { - auto behavior = [&]() - { - auto nulls = document.anm2.element_get(ElementType::NULLS); - if (!nulls) return; - auto changed = editedNull; - changed.type = ElementType::NULL_ELEMENT; - changed.tag = "Null"; + manager.command_push( + {manager.selected, [&window, editedNull, editedReference](Manager&, Document& document) + { + auto behavior = [&]() + { + auto nulls = document.anm2.element_get(ElementType::NULLS); + if (!nulls) return; + auto changed = editedNull; + changed.type = ElementType::NULL_ELEMENT; + changed.tag = "Null"; - if (editedReference == -1) - { - auto id = element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT); - changed.id = id; - nulls->children.push_back(changed); - document.null.selection = {id}; - document.null.reference = id; - window.newElementId = id; - return; - } + if (editedReference == -1) + { + auto id = element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT); + changed.id = id; + nulls->children.push_back(changed); + document.null.selection = {id}; + document.null.reference = id; + window.newElementId = id; + return; + } - auto target = child_id_get(*nulls, ElementType::NULL_ELEMENT, editedReference); - if (!target) return; - changed.id = editedReference; - *target = changed; - document.null.selection = {editedReference}; - }; + auto target = child_id_get(*nulls, ElementType::NULL_ELEMENT, editedReference); + if (!target) return; + changed.id = editedReference; + *target = changed; + document.null.selection = {editedReference}; + }; - window_edit(document, Document::NULLS, - localize.get(editedReference == -1 ? EDIT_ADD_NULL - : EDIT_SET_NULL_PROPERTIES), - behavior); - }}); + window_edit(document, Document::NULLS, + localize.get(editedReference == -1 ? EDIT_ADD_NULL : EDIT_SET_NULL_PROPERTIES), behavior); + }}); manager.null_properties_close(); } diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index e7629ca..588abca 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -413,7 +413,7 @@ namespace anm2ed::imgui::wizard groupedFrames[itemReference].insert(frameReference.frameIndex); } - document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto& [itemReference, selection] : groupedFrames) { auto item = anm2.element_get(itemReference); @@ -421,13 +421,13 @@ namespace anm2ed::imgui::wizard frames_change(*item, frameChange, static_cast(itemReference.itemType), changeType, selection); } - document.anm2_change(Document::FRAMES); + document.change(Document::FRAMES); return; } if (queuedIsItemsDestination) { - document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto itemReference : queuedItemReferences) { if (itemReference.itemType == TRIGGER) continue; @@ -438,11 +438,11 @@ namespace anm2ed::imgui::wizard frames_change(*item, frameChange, static_cast(itemReference.itemType), changeType, selection); } - document.anm2_change(Document::FRAMES); + document.change(Document::FRAMES); return; } - document.anm2_snapshot(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); + document.snapshots.anm2_push(localize.get(EDIT_CHANGE_FRAME_PROPERTIES)); for (auto animationIndex : queuedAnimations) { auto animation = anm2.element_get(ElementType::ANIMATION, animationIndex); @@ -459,8 +459,7 @@ namespace anm2ed::imgui::wizard if (queuedIsLayers) { - auto layerAnimations = - child_first_get(*animation, ElementType::LAYER_ANIMATIONS); + auto layerAnimations = child_first_get(*animation, ElementType::LAYER_ANIMATIONS); if (layerAnimations) { auto item_change = [&](auto&& self, Element& item) -> void @@ -484,8 +483,7 @@ namespace anm2ed::imgui::wizard if (queuedIsNulls) { - auto nullAnimations = - child_first_get(*animation, ElementType::NULL_ANIMATIONS); + auto nullAnimations = child_first_get(*animation, ElementType::NULL_ANIMATIONS); if (nullAnimations) { auto item_change = [&](auto&& self, Element& item) -> void @@ -507,7 +505,7 @@ namespace anm2ed::imgui::wizard } } } - document.anm2_change(Document::FRAMES); + document.change(Document::FRAMES); }}); isChanged = true; }; diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index 286531f..d49b6e2 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -1,12 +1,12 @@ #include "generate_animation_from_grid.hpp" -#include -#include #include "math.hpp" #include "types.hpp" #include "util/imgui/draw.hpp" #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" +#include +#include using namespace anm2ed::types; using namespace anm2ed::util; @@ -102,10 +102,10 @@ namespace anm2ed::imgui::wizard { auto uvMin = frame.crop / textureSize; auto uvMax = (frame.crop + frame.size) / textureSize; - mat4 transform = transform_get(zoom) * - math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.shear)); + mat4 transform = + transform_get(zoom) * math::quad_model_get(frame.size, frame.position, frame.pivot, + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); auto vertices = math::uv_vertices_get(uvMin, uvMax); texture_render(shaderTexture, sourceTexture->id, transform, frame.tint, frame.colorOffset, vertices.data()); @@ -144,64 +144,60 @@ namespace anm2ed::imgui::wizard auto queuedIsMakeRegions = isMakeRegions; auto queuedRegionNameFormat = regionNameFormat; - manager.command_push({manager.selected, - [=](Manager&, Document& document) - { - auto region_name_get = [](const std::string& format, int frameNumber) - { - try - { - return std::vformat(format, std::make_format_args(frameNumber)); - } - catch (const std::format_error&) - { - return format; - } - }; + manager.command_push( + {manager.selected, [=](Manager&, Document& document) + { + auto region_name_get = [](const std::string& format, int frameNumber) + { + try + { + return std::vformat(format, std::make_format_args(frameNumber)); + } + catch (const std::format_error&) + { + return format; + } + }; - bool isChanged{}; - bool isRegionsChanged{}; - for (auto queuedReference : queuedLayerReferences) - { - auto item = document.anm2.element_get(queuedReference); - auto animation = - document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex); - auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, - queuedReference.itemID); - auto spritesheet = layer ? document.anm2.element_get(ElementType::SPRITESHEET, - layer->spritesheetId) - : nullptr; - if (!item || !animation) continue; + bool isChanged{}; + bool isRegionsChanged{}; + for (auto queuedReference : queuedLayerReferences) + { + auto item = document.anm2.element_get(queuedReference); + auto animation = document.anm2.element_get(ElementType::ANIMATION, queuedReference.animationIndex); + auto layer = document.anm2.element_get(ElementType::LAYER_ELEMENT, queuedReference.itemID); + auto spritesheet = + layer ? document.anm2.element_get(ElementType::SPRITESHEET, layer->spritesheetId) : nullptr; + if (!item || !animation) continue; - if (!isChanged) - { - document.anm2_snapshot(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); - isChanged = true; - } - auto frameIndexStart = (int)item->children.size(); - frames_generate_from_grid(*item, queuedStartPosition, queuedSize, queuedPivot, - queuedColumns, queuedCount, queuedDelay); - if (queuedIsMakeRegions && spritesheet) - for (int frameIndex = frameIndexStart; frameIndex < (int)item->children.size(); - ++frameIndex) - { - auto& frame = item->children[frameIndex]; - if (frame.type != ElementType::FRAME) continue; + if (!isChanged) + { + document.snapshots.anm2_push(localize.get(EDIT_GENERATE_ANIMATION_FROM_GRID)); + isChanged = true; + } + auto frameIndexStart = (int)item->children.size(); + frames_generate_from_grid(*item, queuedStartPosition, queuedSize, queuedPivot, queuedColumns, + queuedCount, queuedDelay); + if (queuedIsMakeRegions && spritesheet) + for (int frameIndex = frameIndexStart; frameIndex < (int)item->children.size(); ++frameIndex) + { + auto& frame = item->children[frameIndex]; + if (frame.type != ElementType::FRAME) continue; - auto region = element_make(ElementType::REGION); - region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); - region.name = region_name_get(queuedRegionNameFormat, frameIndex - frameIndexStart); - region.crop = frame.crop; - region.size = frame.size; - region.pivot = frame.pivot; - frame.regionId = region.id; - spritesheet->children.push_back(region); - isRegionsChanged = true; - } - animation->frameNum = animation_length_get(*animation); - } - if (isChanged) document.anm2_change(isRegionsChanged ? Document::ALL : Document::FRAMES); - }}); + auto region = element_make(ElementType::REGION); + region.id = element_child_next_id_get(*spritesheet, ElementType::REGION); + region.name = region_name_get(queuedRegionNameFormat, frameIndex - frameIndexStart); + region.crop = frame.crop; + region.size = frame.size; + region.pivot = frame.pivot; + frame.regionId = region.id; + spritesheet->children.push_back(region); + isRegionsChanged = true; + } + animation->frameNum = animation_length_get(*animation); + } + if (isChanged) document.change(isRegionsChanged ? Document::ALL : Document::FRAMES); + }}); isEnd = true; } ImGui::EndDisabled(); diff --git a/src/imgui/wizard/render_animation.cpp b/src/imgui/wizard/render_animation.cpp index b3f3f6e..83ac4ef 100644 --- a/src/imgui/wizard/render_animation.cpp +++ b/src/imgui/wizard/render_animation.cpp @@ -37,7 +37,8 @@ namespace anm2ed::imgui::wizard { return frameReference.animationIndex != reference.animationIndex || frameReference.itemType != reference.itemType || frameReference.itemID != reference.itemID || - frameReference.groupType != reference.groupType || frameReference.groupId != reference.groupId; + frameReference.groupType != reference.groupType || + frameReference.groupId != reference.groupId; }); if (!frameReferences.empty()) { @@ -283,8 +284,7 @@ namespace anm2ed::imgui::wizard { if (!ffmpeg_is_valid()) { - toasts.push(localize.get(TOAST_INVALID_FFMPEG)); - logger.error(localize.get(TOAST_INVALID_FFMPEG, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_INVALID_FFMPEG); return false; } return true; @@ -295,8 +295,7 @@ namespace anm2ed::imgui::wizard auto formatString = path::to_utf8(format); if (!formatString.contains("{}")) { - toasts.push(localize.get(TOAST_PNG_FORMAT_INVALID)); - logger.error(localize.get(TOAST_PNG_FORMAT_INVALID, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_PNG_FORMAT_INVALID); return false; } return true; @@ -306,8 +305,7 @@ namespace anm2ed::imgui::wizard { if (path.empty()) { - toasts.push(localize.get(TOAST_RENDER_PATH_EMPTY)); - logger.error(localize.get(TOAST_RENDER_PATH_EMPTY, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); return false; } return true; @@ -317,8 +315,7 @@ namespace anm2ed::imgui::wizard { if (!path::ensure_directory(path)) { - toasts.push(localize.get(TOAST_PNG_DIRECTORY_INVALID)); - logger.error(localize.get(TOAST_PNG_DIRECTORY_INVALID, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_PNG_DIRECTORY_INVALID); return false; } return true; @@ -328,8 +325,7 @@ namespace anm2ed::imgui::wizard { if (rows <= 0 && columns <= 0) { - toasts.push(localize.get(TOAST_RENDER_PATH_EMPTY)); - logger.error(localize.get(TOAST_RENDER_PATH_EMPTY, anm2ed::ENGLISH)); + toast_log(Level::ERROR, TOAST_RENDER_PATH_EMPTY); return false; } return true; diff --git a/src/manager.cpp b/src/manager.cpp index 4aa66f1..1ecb536 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -112,10 +112,7 @@ namespace anm2ed if (!document.is_valid()) { documents.pop_back(); - toasts.push( - std::vformat(localize.get(TOAST_OPEN_DOCUMENT_FAILED), std::make_format_args(pathString, errorString))); - logger.error(std::vformat(localize.get(TOAST_OPEN_DOCUMENT_FAILED, anm2ed::ENGLISH), - std::make_format_args(pathString, errorString))); + toast_log(Level::ERROR, TOAST_OPEN_DOCUMENT_FAILED, pathString, errorString); return nullptr; } @@ -124,8 +121,7 @@ namespace anm2ed selected = (int)documents.size() - 1; pendingSelected = selected; selection_history_push(selected); - toasts.push(std::vformat(localize.get(TOAST_OPEN_DOCUMENT), std::make_format_args(pathString))); - logger.info(std::vformat(localize.get(TOAST_OPEN_DOCUMENT, anm2ed::ENGLISH), std::make_format_args(pathString))); + toast_log(Level::INFO, TOAST_OPEN_DOCUMENT, pathString); return &document; } @@ -142,8 +138,7 @@ namespace anm2ed savePath.replace_extension(".anm2"); ensure_parent_directory_exists(savePath); - if (!document->save(savePath, &errorString, options)) - return false; + if (!document->save(savePath, &errorString, options)) return false; const auto autosavePath = document->autosave_path_get(); autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), @@ -160,17 +155,13 @@ namespace anm2ed return false; } - bool Manager::save(const std::filesystem::path& path, Options options) - { - return save(selected, path, options); - } + bool Manager::save(const std::filesystem::path& path, Options options) { return save(selected, path, options); } void Manager::autosave(Document& document, Options options) { std::string errorString{}; auto autosavePath = document.autosave_path_get(); - if (!document.autosave(&errorString, options)) - return; + if (!document.autosave(&errorString, options)) return; autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosaveFiles.insert(autosaveFiles.begin(), autosavePath); diff --git a/src/manager.hpp b/src/manager.hpp index 1f388bb..8128018 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -53,7 +53,7 @@ namespace anm2ed std::vector anm2DragDropPaths{}; bool isAnm2DragDrop{}; - int anm2DragDropMergePreset{Document::FILE_MERGE_PRESET_MERGE_BY_NAME}; + int anm2DragDropMergePreset{FILE_MERGE_PRESET_MERGE_BY_NAME}; imgui::PopupHelper anm2DragDropPopup{ imgui::PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, imgui::POPUP_NORMAL, imgui::POPUP_BY_CURSOR)}; imgui::PopupHelper anm2DragDropMergePopup{ diff --git a/src/resource/shader.cpp b/src/resource/shader.cpp index 7afcf58..4ee6404 100644 --- a/src/resource/shader.cpp +++ b/src/resource/shader.cpp @@ -1,10 +1,12 @@ #include "shader.hpp" +#include #include #include #include #include +#include "anm2/anm2.hpp" #include "log.hpp" namespace anm2ed::resource::shader @@ -26,15 +28,15 @@ namespace anm2ed::resource::shader X(UNIFORM_BINDING_MAIN_TEXTURE, "Texture") \ X(UNIFORM_BINDING_MAIN_TEXTURE, "Sampler0") \ X(UNIFORM_BINDING_MAIN_TEXTURE, "ColorMap") \ - X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ + X(UNIFORM_BINDING_TRANSFORM, UNIFORM_TRANSFORM) \ X(UNIFORM_BINDING_TRANSFORM, "Transform") \ X(UNIFORM_BINDING_TRANSFORM, "MVP") \ X(UNIFORM_BINDING_TRANSFORM, "Matrix") \ - X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ + X(UNIFORM_BINDING_FRAME_TINT, UNIFORM_TINT) \ X(UNIFORM_BINDING_FRAME_TINT, "Tint") \ X(UNIFORM_BINDING_FRAME_TINT, "Color") \ X(UNIFORM_BINDING_FRAME_TINT, "Color0") \ - X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ + X(UNIFORM_BINDING_COLOR_OFFSET, UNIFORM_COLOR_OFFSET) \ X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset") \ X(UNIFORM_BINDING_COLOR_OFFSET, "ColorOffset0") \ X(UNIFORM_BINDING_TEXTURE_SIZE, "u_texture_size") \ @@ -47,10 +49,7 @@ namespace anm2ed::resource::shader #undef X }; - bool is_shader_identifier(char character) - { - return std::isalnum((unsigned char)character) || character == '_'; - } + bool is_shader_identifier(char character) { return std::isalnum((unsigned char)character) || character == '_'; } std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) { @@ -234,9 +233,7 @@ namespace anm2ed::resource::shader std::string_view uniform_value_type_label_get(UniformValueType type) { - for (const auto& info : UNIFORM_VALUE_TYPE_INFOS) - if (type == info.type) return info.label; - return UNIFORM_VALUE_TYPE_INFOS[0].label; + return UNIFORM_VALUE_TYPE_INFOS[type < UNIFORM_VALUE_COUNT ? type : UNIFORM_VALUE_UNKNOWN].label; } bool is_uniform_value_editable(UniformValueType type) @@ -245,9 +242,100 @@ namespace anm2ed::resource::shader type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4 || type == UNIFORM_VALUE_SAMPLER2D; } - bool is_uniform_value_vector(UniformValueType type) + bool is_uniform_value_vector(UniformValueType type) { return UNIFORM_VALUE_TYPE_INFOS[type].componentCount > 0; } + + bool is_component_binding_valid(UniformBinding binding) { - return type == UNIFORM_VALUE_VEC2 || type == UNIFORM_VALUE_VEC3 || type == UNIFORM_VALUE_VEC4; + return binding == UNIFORM_BINDING_MANUAL || binding == UNIFORM_BINDING_PLAYBACK_TIME; + } + + void uniform_configs_apply(const Element& shaderElement, std::vector& uniforms) + { + for (auto& uniform : uniforms) + { + auto config = shader_uniform_get(shaderElement, uniform.name); + if (!config) continue; + + if (auto binding = uniform_binding_get(config->binding); + !config->binding.empty() && is_uniform_binding_valid(binding, uniform.valueType)) + uniform.binding = binding; + if (!config->value.empty()) uniform_value_parse(uniform, config->value); + for (int index = 0; index < (int)uniform.components.size(); ++index) + { + auto component = shader_uniform_component_get(*config, index); + if (!component) continue; + if (auto binding = uniform_binding_get(component->binding); + !component->binding.empty() && is_component_binding_valid(binding)) + uniform.components[index].binding = binding; + if (!component->value.empty()) std::stringstream{component->value} >> uniform.components[index].value; + } + } + } + + bool uniform_configs_trim(Element& shaderElement, const std::vector& uniforms) + { + bool isChanged = std::erase_if(shaderElement.children, + [&](const Element& child) + { + return child.type == ElementType::UNIFORM && + std::ranges::none_of(uniforms, [&](const Uniform& uniform) + { return uniform.name == child.name; }); + }) > 0; + + for (auto& config : shaderElement.children) + { + if (config.type != ElementType::UNIFORM) continue; + auto& uniform = *std::ranges::find(uniforms, config.name, &Uniform::name); + + if (!config.binding.empty() && !is_uniform_binding_valid(uniform_binding_get(config.binding), uniform.valueType)) + { + config.binding.clear(); + isChanged = true; + } + + auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; + auto isComponents = uniform_binding_get(config.binding) == UNIFORM_BINDING_COMPONENTS; + isChanged |= std::erase_if(config.children, + [&](const Element& component) + { + return component.type == ElementType::COMPONENT && + (!isComponents || component.index < 0 || component.index >= componentCount); + }) > 0; + + for (auto& component : config.children) + { + if (component.type != ElementType::COMPONENT || component.binding.empty() || + is_component_binding_valid(uniform_binding_get(component.binding))) + continue; + component.binding.clear(); + isChanged = true; + } + } + + return isChanged; + } + + void uniform_config_save(Element& shaderElement, const Uniform& uniform) + { + auto config = shader_uniform_get(shaderElement, uniform.name); + if (!config) + { + config = &shaderElement.children.emplace_back(element_make(ElementType::UNIFORM)); + config->name = uniform.name; + } + + config->binding = std::string(uniform_binding_value_get(uniform.binding)); + config->value = uniform_value_string_get(uniform); + std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; }); + if (uniform.binding != UNIFORM_BINDING_COMPONENTS) return; + + for (int index = 0; index < (int)uniform.components.size(); ++index) + { + auto& component = config->children.emplace_back(element_make(ElementType::COMPONENT)); + component.index = index; + component.binding = std::string(uniform_binding_value_get(uniform.components[index].binding)); + component.value = std::format("{:.6g}", uniform.components[index].value); + } } bool is_uniform_binding_valid(UniformBinding binding, UniformValueType type) @@ -302,7 +390,8 @@ namespace anm2ed::resource::shader case UNIFORM_VALUE_SAMPLER2D: return std::format("{}", uniform.intValue); case UNIFORM_VALUE_VEC2: - return std::format("{} {}", uniform_float_string_get(uniform.value.x), uniform_float_string_get(uniform.value.y)); + return std::format("{} {}", uniform_float_string_get(uniform.value.x), + uniform_float_string_get(uniform.value.y)); case UNIFORM_VALUE_VEC3: return std::format("{} {} {}", uniform_float_string_get(uniform.value.x), uniform_float_string_get(uniform.value.y), uniform_float_string_get(uniform.value.z)); @@ -374,15 +463,9 @@ namespace anm2ed::resource::shader return "#version 330 core\n" + declarations + body; } - std::string gles_fragment_convert(std::string_view source) - { - return gles_convert(source, SHADER_STAGE_FRAGMENT); - } + std::string gles_fragment_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_FRAGMENT); } - std::string gles_vertex_convert(std::string_view source) - { - return gles_convert(source, SHADER_STAGE_VERTEX); - } + std::string gles_vertex_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_VERTEX); } } namespace anm2ed::resource @@ -485,8 +568,5 @@ namespace anm2ed::resource if (is_valid()) glDeleteProgram(id); } - bool Shader::is_valid() const - { - return id != 0; - } + bool Shader::is_valid() const { return id != 0; } } diff --git a/src/resource/shader.hpp b/src/resource/shader.hpp index 6068a02..70faa07 100644 --- a/src/resource/shader.hpp +++ b/src/resource/shader.hpp @@ -8,6 +8,11 @@ #include #include +namespace anm2ed +{ + struct Element; +} + namespace anm2ed::resource::shader { struct Info @@ -257,14 +262,14 @@ namespace anm2ed::resource::shader }; #define RESOURCE_SHADER_UNIFORM_BINDINGS \ - X(IGNORE, "Ignore", "Ignore") \ + X(IGNORE, "Ignore", "Ignore") \ X(MAIN_TEXTURE, "MainTexture", "Main Texture") \ X(TRANSFORM, "Transform", "Transform") \ X(FRAME_TINT, "FrameTint", "Frame Tint") \ X(COLOR_OFFSET, "ColorOffset", "Color Offset") \ X(TEXTURE_SIZE, "TextureSize", "Texture Size") \ X(PLAYBACK_TIME, "PlaybackTime", "Playback Time") \ - X(COMPONENTS, "Components", "Per Component") \ + X(COMPONENTS, "Components", "Per Component") \ X(MANUAL, "Manual", "Manual") enum UniformBinding @@ -289,18 +294,18 @@ namespace anm2ed::resource::shader }; #define RESOURCE_SHADER_UNIFORM_VALUE_TYPES \ - X(UNKNOWN, "Unknown") \ - X(FLOAT, "Float") \ - X(INT, "Int") \ - X(VEC2, "Vec2") \ - X(VEC3, "Vec3") \ - X(VEC4, "Vec4") \ - X(MAT4, "Mat4") \ - X(SAMPLER2D, "Sampler2D") + X(UNKNOWN, "Unknown", 0) \ + X(FLOAT, "Float", 0) \ + X(INT, "Int", 0) \ + X(VEC2, "Vec2", 2) \ + X(VEC3, "Vec3", 3) \ + X(VEC4, "Vec4", 4) \ + X(MAT4, "Mat4", 0) \ + X(SAMPLER2D, "Sampler2D", 0) enum UniformValueType { -#define X(symbol, label) UNIFORM_VALUE_##symbol, +#define X(symbol, label, componentCount) UNIFORM_VALUE_##symbol, RESOURCE_SHADER_UNIFORM_VALUE_TYPES #undef X UNIFORM_VALUE_COUNT @@ -310,10 +315,11 @@ namespace anm2ed::resource::shader { UniformValueType type{}; const char* label{}; + int componentCount{}; }; inline constexpr UniformValueTypeInfo UNIFORM_VALUE_TYPE_INFOS[] = { -#define X(symbol, label) {UNIFORM_VALUE_##symbol, label}, +#define X(symbol, label, componentCount) {UNIFORM_VALUE_##symbol, label, componentCount}, RESOURCE_SHADER_UNIFORM_VALUE_TYPES #undef X }; @@ -360,6 +366,9 @@ namespace anm2ed::resource::shader {GRID_VERTEX, GRID_FRAGMENT}}; UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); + void uniform_configs_apply(const Element&, std::vector&); + bool uniform_configs_trim(Element&, const std::vector&); + void uniform_config_save(Element&, const Uniform&); UniformBinding uniform_binding_get(std::string_view); std::string_view uniform_binding_value_get(UniformBinding); std::string_view uniform_binding_label_get(UniformBinding); diff --git a/src/snapshots.cpp b/src/snapshots.cpp index 328dcd1..3e6f7d5 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -131,20 +131,9 @@ namespace anm2ed::snapshots } } - Element* element_get(Element& root, const std::vector& path) + template ElementPointer element_get(E& root, const std::vector& path) { - auto* element = &root; - for (auto index : path) - { - if (index < 0 || index >= (int)element->children.size()) return nullptr; - element = &element->children[index]; - } - return element; - } - - const Element* element_get(const Element& root, const std::vector& path) - { - auto* element = &root; + auto element = &root; for (auto index : path) { if (index < 0 || index >= (int)element->children.size()) return nullptr; @@ -158,46 +147,12 @@ namespace anm2ed::snapshots for (size_t i = 0; i < element.children.size(); ++i) { path.push_back((int)i); - if (&element.children[i] == target) return true; - if (element_path_get(element.children[i], target, path)) return true; + if (&element.children[i] == target || element_path_get(element.children[i], target, path)) return true; path.pop_back(); } return false; } - std::optional> frame_path_get(const Anm2& anm2, Reference frameReference) - { - auto frame = anm2.element_get(frameReference); - if (!frame) return std::nullopt; - - std::vector path{}; - if (!element_path_get(anm2.root, frame, path)) return std::nullopt; - return path; - } - - std::optional> track_path_get(const Anm2& anm2, Reference trackReference) - { - trackReference.frameIndex = -1; - auto track = anm2.element_get(trackReference); - if (!track) return std::nullopt; - - std::vector path{}; - if (!element_path_get(anm2.root, track, path)) return std::nullopt; - return path; - } - - std::optional> region_path_get(const Anm2& anm2, int spritesheetId, int regionId) - { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) return std::nullopt; - auto region = child_id_get(*spritesheet, ElementType::REGION, regionId); - if (!region) return std::nullopt; - - std::vector path{}; - if (!element_path_get(anm2.root, region, path)) return std::nullopt; - return path; - } - void step_state_seed(SnapshotStep& step, const Snapshot& snapshot) { #define X(type, name) step.name = SnapshotStepValue{snapshot.name, {}}; @@ -205,61 +160,27 @@ namespace anm2ed::snapshots #undef X } - void step_textures_seed(SnapshotStep& step, const Snapshot& snapshot) - { - step.textures = SnapshotStepValue{snapshot.textures, {}}; - } - - SnapshotStep step_anm2_seed(const Snapshot& snapshot, const std::string& message) + SnapshotStep step_anm2_make(const Snapshot& snapshot) { SnapshotStep step{}; - step.message = message; step.anm2.isValid = SnapshotStepValue{snapshot.anm2.isValid, {}}; step.anm2.elements.push_back({{}, snapshot.anm2.root, {}}); step_state_seed(step, snapshot); return step; } - void tracks_step_add(SnapshotStep& step, const Snapshot& snapshot, Reference trackReference) + SnapshotStep step_elements_make(const Snapshot& snapshot, const std::vector& elements) { - trackReference.frameIndex = -1; - auto path = track_path_get(snapshot.anm2, trackReference); - if (!path) return; - for (auto& elementStep : step.anm2.elements) - if (elementStep.path == *path) return; - - auto track = snapshot.anm2.element_get(trackReference); - if (!track) return; - - step.anm2.elements.push_back({std::move(*path), *track, {}}); - } - - void frames_step_add(SnapshotStep& step, const Snapshot& snapshot, Reference frameReference) - { - auto path = frame_path_get(snapshot.anm2, frameReference); - if (!path) return; - for (auto& elementStep : step.anm2.elements) - if (elementStep.path == *path) return; - - auto frame = snapshot.anm2.element_get(frameReference); - if (!frame) return; - - step.anm2.elements.push_back({std::move(*path), *frame, {}}); - } - - void regions_step_add(SnapshotStep& step, const Snapshot& snapshot, int spritesheetId, int regionId) - { - auto path = region_path_get(snapshot.anm2, spritesheetId, regionId); - if (!path) return; - for (auto& elementStep : step.anm2.elements) - if (elementStep.path == *path) return; - - auto spritesheet = snapshot.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) return; - auto region = child_id_get(*spritesheet, ElementType::REGION, regionId); - if (!region) return; - - step.anm2.elements.push_back({std::move(*path), *region, {}}); + SnapshotStep step{}; + for (auto element : elements) + { + std::vector path{}; + if (!element || !element_path_get(snapshot.anm2.root, element, path)) continue; + if (std::ranges::any_of(step.anm2.elements, [&](const SnapshotElementStep& other) { return other.path == path; })) + continue; + step.anm2.elements.push_back({std::move(path), *element, {}}); + } + return step; } SnapshotAnm2Step anm2_step_make(const Anm2& before, const Anm2& after) @@ -360,70 +281,63 @@ namespace anm2ed int SnapshotStack::max_size_get() { return maxSize; } - Snapshot* Snapshots::get() { return ¤t; } - - void Snapshots::anm2_push(const Snapshot& snapshot, const std::string& message) + void Snapshots::step_push(const std::string& message, SnapshotStep step) { - if (pendingStep) commit(snapshot); - pendingStep = snapshots::step_anm2_seed(snapshot, message); + if (pendingStep) commit(); + current.message = message; + step.message = message; + pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); } - void Snapshots::tracks_push(const Snapshot& snapshot, const std::string& message, - const std::set& trackReferences) + void Snapshots::anm2_push(const std::string& message) { step_push(message, snapshots::step_anm2_make(current)); } + + void Snapshots::tracks_push(const std::string& message, const std::set& trackReferences) { - if (pendingStep) commit(snapshot); - SnapshotStep step{}; - step.message = message; + std::vector tracks{}; for (auto trackReference : trackReferences) - snapshots::tracks_step_add(step, snapshot, trackReference); - snapshots::step_state_seed(step, snapshot); - - pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + { + trackReference.frameIndex = -1; + tracks.push_back(current.anm2.element_get(trackReference)); + } + auto step = snapshots::step_elements_make(current, tracks); + snapshots::step_state_seed(step, current); + step_push(message, std::move(step)); } - void Snapshots::frames_push(const Snapshot& snapshot, const std::string& message, - const std::set& frameReferences) + void Snapshots::frames_push(const std::string& message, const std::set& frameReferences) { - if (pendingStep) commit(snapshot); - SnapshotStep step{}; - step.message = message; + std::vector frames{}; for (auto frameReference : frameReferences) - snapshots::frames_step_add(step, snapshot, frameReference); - - pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + frames.push_back(current.anm2.element_get(frameReference)); + step_push(message, snapshots::step_elements_make(current, frames)); } - void Snapshots::regions_push(const Snapshot& snapshot, const std::string& message, int spritesheetId, - const std::set& regionIds) + void Snapshots::regions_push(const std::string& message, int spritesheetId, const std::set& regionIds) + { + std::vector regions{}; + if (auto spritesheet = current.anm2.element_get(ElementType::SPRITESHEET, spritesheetId)) + for (auto regionId : regionIds) + regions.push_back(child_id_get(*spritesheet, ElementType::REGION, regionId)); + step_push(message, snapshots::step_elements_make(current, regions)); + } + + void Snapshots::textures_push(const std::string& message) { - if (pendingStep) commit(snapshot); SnapshotStep step{}; - step.message = message; - for (auto regionId : regionIds) - snapshots::regions_step_add(step, snapshot, spritesheetId, regionId); - - pendingStep = step.is_empty() ? std::nullopt : std::optional(std::move(step)); + step.textures = SnapshotStepValue{current.textures, {}}; + step_push(message, std::move(step)); } - void Snapshots::textures_push(const Snapshot& snapshot, const std::string& message) + void Snapshots::anm2_textures_push(const std::string& message) { - if (pendingStep) commit(snapshot); - SnapshotStep step{}; - step.message = message; - snapshots::step_textures_seed(step, snapshot); - pendingStep = std::move(step); + auto step = snapshots::step_anm2_make(current); + step.textures = SnapshotStepValue{current.textures, {}}; + step_push(message, std::move(step)); } - void Snapshots::anm2_textures_push(const Snapshot& snapshot, const std::string& message) - { - if (pendingStep) commit(snapshot); - auto step = snapshots::step_anm2_seed(snapshot, message); - snapshots::step_textures_seed(step, snapshot); - pendingStep = std::move(step); - } - - void Snapshots::commit(const Snapshot& snapshot) + void Snapshots::commit() { + const auto& snapshot = current; if (!pendingStep) return; auto step = std::move(*pendingStep); diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 3ed285d..8892927 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -137,14 +137,14 @@ namespace anm2ed Snapshot current{}; std::optional pendingStep{}; - Snapshot* get(); - void anm2_push(const Snapshot&, const std::string&); - void tracks_push(const Snapshot&, const std::string&, const std::set&); - void frames_push(const Snapshot&, const std::string&, const std::set&); - void regions_push(const Snapshot&, const std::string&, int, const std::set&); - void textures_push(const Snapshot&, const std::string&); - void anm2_textures_push(const Snapshot&, const std::string&); - void commit(const Snapshot&); + void anm2_push(const std::string&); + void tracks_push(const std::string&, const std::set&); + void frames_push(const std::string&, const std::set&); + void regions_push(const std::string&, int, const std::set&); + void textures_push(const std::string&); + void anm2_textures_push(const std::string&); + void step_push(const std::string&, SnapshotStep); + void commit(); bool undo(); bool redo(); void reset(); diff --git a/src/state.cpp b/src/state.cpp index b6a4ef8..461d0fa 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -107,27 +107,25 @@ namespace anm2ed if (!spritesheetDropPaths.empty()) { auto paths = spritesheetDropPaths; - manager.command_push({manager.selected, [paths](Manager&, Document& document) - { document.spritesheets_add(paths); }}); + manager.command_push( + {manager.selected, [paths](Manager&, Document& document) { document.spritesheets_add(paths); }}); } if (!soundDropPaths.empty()) { auto paths = soundDropPaths; - manager.command_push({manager.selected, [paths](Manager&, Document& document) - { document.sounds_add(paths); }}); + manager.command_push( + {manager.selected, [paths](Manager&, Document& document) { document.sounds_add(paths); }}); } } else { if (!spritesheetDropPaths.empty()) { - toasts.push(localize.get(TOAST_ADD_SPRITESHEET_FAILED)); - logger.warning(localize.get(TOAST_ADD_SPRITESHEET_FAILED, anm2ed::ENGLISH)); + toast_log(Level::WARNING, TOAST_ADD_SPRITESHEET_FAILED); } if (!soundDropPaths.empty()) { - toasts.push(localize.get(TOAST_ADD_SOUND_FAILED)); - logger.warning(localize.get(TOAST_ADD_SOUND_FAILED, anm2ed::ENGLISH)); + toast_log(Level::WARNING, TOAST_ADD_SOUND_FAILED); } } spritesheetDropPaths.clear(); diff --git a/src/util/pack.cpp b/src/util/pack.cpp new file mode 100644 index 0000000..4ad98e0 --- /dev/null +++ b/src/util/pack.cpp @@ -0,0 +1,150 @@ +#include "pack.hpp" + +#include +#include +#include +#include + +namespace anm2ed::util::pack +{ + constexpr int WIDTH_CANDIDATES_MAX = 512; + + struct Rect + { + int x{}; + int y{}; + int w{}; + int h{}; + }; + + bool is_rect_intersecting(const Rect& a, const Rect& b) + { + return !(b.x >= a.x + a.w || b.x + b.w <= a.x || b.y >= a.y + a.h || b.y + b.h <= a.y); + } + + bool is_rect_contained(const Rect& a, const Rect& b) + { + return b.x >= a.x && b.y >= a.y && b.x + b.w <= a.x + a.w && b.y + b.h <= a.y + a.h; + } + + void free_rects_split(std::vector& freeRects, const Rect& used) + { + std::vector next{}; + next.reserve(freeRects.size() * 2); + for (auto& free : freeRects) + { + if (!is_rect_intersecting(free, used)) + { + next.push_back(free); + continue; + } + if (used.x > free.x) next.push_back({free.x, free.y, used.x - free.x, free.h}); + if (used.x + used.w < free.x + free.w) + next.push_back({used.x + used.w, free.y, free.x + free.w - (used.x + used.w), free.h}); + if (used.y > free.y) next.push_back({free.x, free.y, free.w, used.y - free.y}); + if (used.y + used.h < free.y + free.h) + next.push_back({free.x, used.y + used.h, free.w, free.y + free.h - (used.y + used.h)}); + } + freeRects = std::move(next); + } + + void free_rects_prune(std::vector& freeRects) + { + for (int i = 0; i < (int)freeRects.size(); ++i) + { + if (freeRects[i].w <= 0 || freeRects[i].h <= 0) + { + freeRects.erase(freeRects.begin() + i--); + continue; + } + for (int j = i + 1; j < (int)freeRects.size();) + { + if (is_rect_contained(freeRects[i], freeRects[j])) + freeRects.erase(freeRects.begin() + j); + else if (is_rect_contained(freeRects[j], freeRects[i])) + { + freeRects.erase(freeRects.begin() + i--); + break; + } + else + ++j; + } + } + } + + bool rect_insert(std::vector& freeRects, glm::ivec2 size, Rect& result) + { + int bestShort = std::numeric_limits::max(); + int bestLong = std::numeric_limits::max(); + bool isFound{}; + for (auto& free : freeRects) + { + if (size.x > free.w || size.y > free.h) continue; + int shortSide = std::min(free.w - size.x, free.h - size.y); + int longSide = std::max(free.w - size.x, free.h - size.y); + if (shortSide > bestShort || (shortSide == bestShort && longSide >= bestLong)) continue; + bestShort = shortSide; + bestLong = longSide; + result = {free.x, free.y, size.x, size.y}; + isFound = true; + } + if (!isFound) return false; + free_rects_split(freeRects, result); + free_rects_prune(freeRects); + return true; + } + + bool rects_pack(const std::vector& sizes, glm::ivec2& packedSize, std::vector& positions) + { + if (sizes.empty()) return false; + + glm::ivec2 maxSize{}; + glm::ivec2 sumSize{}; + std::int64_t totalArea{}; + for (auto& size : sizes) + { + maxSize = glm::max(maxSize, size); + sumSize += size; + totalArea += (std::int64_t)size.x * size.y; + } + if (maxSize.x <= 0 || maxSize.y <= 0) return false; + + int bestSquareDelta = std::numeric_limits::max(); + int bestArea = std::numeric_limits::max(); + int endWidth = std::max(maxSize.x, sumSize.x); + int step = std::max(1, (endWidth - maxSize.x) / WIDTH_CANDIDATES_MAX); + + for (int width = maxSize.x; width <= endWidth; width += step) + { + std::vector candidate(sizes.size()); + glm::ivec2 used{}; + bool isValid{}; + for (int height = std::max(maxSize.y, (int)std::ceil((double)totalArea / width)); height <= sumSize.y && !isValid; + ++height) + { + std::vector freeRects{{0, 0, width, height}}; + used = {}; + isValid = true; + for (int i = 0; i < (int)sizes.size() && isValid; ++i) + { + Rect rect{}; + isValid = rect_insert(freeRects, sizes[i], rect); + candidate[i] = {rect.x, rect.y}; + used = glm::max(used, glm::ivec2(rect.x + rect.w, rect.y + rect.h)); + } + } + if (!isValid) continue; + + int area = used.x * used.y; + int squareDelta = std::abs(used.x - used.y); + if (squareDelta > bestSquareDelta || (squareDelta == bestSquareDelta && area >= bestArea)) continue; + bestSquareDelta = squareDelta; + bestArea = area; + packedSize = used; + positions = std::move(candidate); + if (bestArea == totalArea && bestSquareDelta == 0) break; + } + + return bestArea != std::numeric_limits::max(); + } +} diff --git a/src/util/pack.hpp b/src/util/pack.hpp new file mode 100644 index 0000000..1e7f012 --- /dev/null +++ b/src/util/pack.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include + +namespace anm2ed::util::pack +{ + bool rects_pack(const std::vector&, glm::ivec2&, std::vector&); +}