Split anm2 and timeline into modules; merge groups by name

Baseline before de-bloat refactor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-03 12:41:23 -04:00
1 parent 9e9dd8bd8a
commit 41ed347925
20 files changed
+7849 -7415

No files matched your search

+2
View File
@@ -94,6 +94,8 @@ file(GLOB PROJECT_SRC CONFIGURE_DEPENDS
src/imgui/*.hpp
src/imgui/window/*.cpp
src/imgui/window/*.hpp
src/imgui/window/timeline/*.cpp
src/imgui/window/timeline/*.hpp
src/imgui/popup/*.cpp
src/imgui/popup/*.hpp
src/imgui/wizard/*.cpp
+185
View File
@@ -0,0 +1,185 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
Element Anm2::frame_effective(int layerId, const Element& frame) const
{
auto resolved = frame;
if (frame.regionId == -1) return resolved;
auto layer = element_get(ElementType::LAYER_ELEMENT, layerId);
if (!layer) return resolved;
auto spritesheet = element_get(ElementType::SPRITESHEET, layer->spritesheetId);
if (!spritesheet) return resolved;
auto region = element_child_id_get(*spritesheet, ElementType::REGION, frame.regionId);
if (!region) return resolved;
resolved.crop = region->crop;
resolved.size = region->size;
resolved.pivot = region->pivot;
return resolved;
}
glm::vec4 Anm2::animation_rect(const Element& animation, bool isRootTransform) const
{
constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
float minX = std::numeric_limits<float>::infinity();
float minY = std::numeric_limits<float>::infinity();
float maxX = -std::numeric_limits<float>::infinity();
float maxY = -std::numeric_limits<float>::infinity();
bool isAny{};
for (float t = 0.0f; t < (float)animation.frameNum; t += 1.0f)
{
glm::mat4 transform(1.0f);
auto root = animation_item_get(animation, ItemType::ROOT);
if (isRootTransform && root)
{
auto rootFrame = frame_generate(*root, t);
transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale),
rootFrame.rotation, math::percent_to_unit(rootFrame.shear));
}
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](const Element& layerAnimation)
{
if (!layerAnimation.isVisible || !is_track_group_visible(*layerAnimations, layerAnimation)) return;
auto itemTransform = transform;
if (isRootTransform && layerAnimation.groupId != -1)
if (auto group = child_id_get(*layerAnimations, ElementType::GROUP, layerAnimation.groupId))
if (auto groupRoot = child_first_get(*group, ElementType::ROOT_ANIMATION))
{
auto groupRootFrame = frame_generate(*groupRoot, t);
itemTransform *= math::quad_model_parent_get(
groupRootFrame.position, {}, math::percent_to_unit(groupRootFrame.scale),
groupRootFrame.rotation, math::percent_to_unit(groupRootFrame.shear));
}
auto frame = frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, t));
if (frame.size == glm::vec2() || !frame.isVisible) return;
auto layerTransform =
itemTransform * math::quad_model_get(frame.size, frame.position, frame.pivot,
math::percent_to_unit(frame.scale), frame.rotation,
math::percent_to_unit(frame.shear));
for (auto& corner : CORNERS)
{
auto world = layerTransform * glm::vec4(corner, 0.0f, 1.0f);
minX = std::min(minX, world.x);
minY = std::min(minY, world.y);
maxX = std::max(maxX, world.x);
maxY = std::max(maxY, world.y);
isAny = true;
}
});
}
if (!isAny) return glm::vec4(-1.0f);
return {minX, minY, maxX - minX, maxY - minY};
}
Element* animation_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();
}
int Anm2::layer_animation_add(int animationIndex, int id, int insertBeforeId, std::string name, int spritesheetId,
types::destination::Type destination)
{
auto layers = element_get(ElementType::LAYERS);
if (!layers) return -1;
id = id == -1 ? element_child_next_id_get(*layers, ElementType::LAYER_ELEMENT) : id;
auto layer = element_child_id_get(*layers, ElementType::LAYER_ELEMENT, id);
if (!layer)
{
layers->children.push_back(element_make(ElementType::LAYER_ELEMENT));
layer = &layers->children.back();
layer->id = id;
}
if (!name.empty()) layer->name = name;
layer->spritesheetId = element_get(ElementType::SPRITESHEET, spritesheetId) ? spritesheetId : 0;
auto add = [&](Element& animation)
{
if (animation_item_get(animation, ItemType::LAYER, id)) return;
auto layerAnimations = animation_container_get(animation, ElementType::LAYER_ANIMATIONS);
auto item = element_make(ElementType::LAYER_ANIMATION);
item.layerId = id;
if (insertBeforeId != -1)
for (auto it = layerAnimations->children.begin(); it != layerAnimations->children.end(); ++it)
if (it->type == ElementType::LAYER_ANIMATION && it->layerId == insertBeforeId)
{
layerAnimations->children.insert(it, item);
return;
}
layerAnimations->children.push_back(item);
};
if (destination == types::destination::ALL)
{
if (auto animations = element_get(ElementType::ANIMATIONS))
for (auto& animation : animations->children)
if (animation.type == ElementType::ANIMATION) add(animation);
}
else if (auto animation = element_get(ElementType::ANIMATION, animationIndex))
add(*animation);
return id;
}
int Anm2::null_animation_add(int animationIndex, int id, std::string name, bool isShowRect,
types::destination::Type destination)
{
auto nulls = element_get(ElementType::NULLS);
if (!nulls) return -1;
id = id == -1 ? element_child_next_id_get(*nulls, ElementType::NULL_ELEMENT) : id;
auto null = element_child_id_get(*nulls, ElementType::NULL_ELEMENT, id);
if (!null)
{
nulls->children.push_back(element_make(ElementType::NULL_ELEMENT));
null = &nulls->children.back();
null->id = id;
}
if (!name.empty()) null->name = name;
null->isShowRect = isShowRect;
auto add = [&](Element& animation)
{
if (animation_item_get(animation, ItemType::NULL_, id)) return;
auto nullAnimations = animation_container_get(animation, ElementType::NULL_ANIMATIONS);
auto item = element_make(ElementType::NULL_ANIMATION);
item.nullId = id;
nullAnimations->children.push_back(item);
};
if (destination == types::destination::ALL)
{
if (auto animations = element_get(ElementType::ANIMATIONS))
for (auto& animation : animations->children)
if (animation.type == ElementType::ANIMATION) add(animation);
}
else if (auto animation = element_get(ElementType::ANIMATION, animationIndex))
add(*animation);
return id;
}
}
+2 -3183
View File
File diff suppressed because it is too large. Load diff
+683
View File
@@ -0,0 +1,683 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
constexpr std::array<std::string_view, (std::size_t)ElementType::COUNT> ELEMENT_TAGS = {
#define X(symbol, tag) std::string_view{tag},
ANM2_ELEMENT_TYPES
#undef X
};
ElementType element_type_get(std::string_view tag)
{
for (std::size_t i = 0; i < ELEMENT_TAGS.size(); ++i)
if (ELEMENT_TAGS[i] == tag) return (ElementType)i;
return ElementType::UNKNOWN;
}
std::string_view element_tag_get(ElementType type)
{
auto index = (std::size_t)type;
if (index >= ELEMENT_TAGS.size()) return {};
return ELEMENT_TAGS[index];
}
ElementType element_container_type_get(ElementType type)
{
switch (type)
{
case ElementType::SPRITESHEET:
return ElementType::SPRITESHEETS;
case ElementType::SHADER:
return ElementType::SHADERS;
case ElementType::LAYER_ELEMENT:
return ElementType::LAYERS;
case ElementType::NULL_ELEMENT:
return ElementType::NULLS;
case ElementType::EVENT_ELEMENT:
return ElementType::EVENTS;
case ElementType::SOUND_ELEMENT:
return ElementType::SOUNDS;
case ElementType::ANIMATION:
return ElementType::ANIMATIONS;
default:
return ElementType::UNKNOWN;
}
}
Element element_make(ElementType type)
{
Element element{};
element.type = type;
element.tag = std::string(element_tag_get(type));
return element;
}
Element root_animation_make()
{
auto root = element_make(ElementType::ROOT_ANIMATION);
root.children.push_back(element_make(ElementType::FRAME));
return root;
}
Element* child_first_get(Element& element, ElementType type)
{
for (auto& child : element.children)
if (child.type == type) return &child;
return nullptr;
}
const Element* child_first_get(const Element& element, ElementType type)
{
for (const auto& child : element.children)
if (child.type == type) return &child;
return nullptr;
}
Element* element_child_first_get(Element& element, ElementType type) { return child_first_get(element, type); }
const Element* element_child_first_get(const Element& element, ElementType type)
{
return child_first_get(element, type);
}
Element* shader_uniform_get(Element& shader, std::string_view name, bool isCreate)
{
for (auto& child : shader.children)
if (child.type == ElementType::UNIFORM && child.name == name) return &child;
if (!isCreate) return nullptr;
shader.children.push_back(element_make(ElementType::UNIFORM));
shader.children.back().name = std::string(name);
return &shader.children.back();
}
const Element* shader_uniform_get(const Element& shader, std::string_view name)
{
for (const auto& child : shader.children)
if (child.type == ElementType::UNIFORM && child.name == name) return &child;
return nullptr;
}
Element* shader_uniform_component_get(Element& uniform, int index, bool isCreate)
{
for (auto& child : uniform.children)
if (child.type == ElementType::COMPONENT && child.index == index) return &child;
if (!isCreate) return nullptr;
uniform.children.push_back(element_make(ElementType::COMPONENT));
uniform.children.back().index = index;
return &uniform.children.back();
}
const Element* shader_uniform_component_get(const Element& uniform, int index)
{
for (const auto& child : uniform.children)
if (child.type == ElementType::COMPONENT && child.index == index) return &child;
return nullptr;
}
Element* child_id_get(Element& element, ElementType type, int id)
{
for (auto& child : element.children)
if (child.type == type && child.id == id) return &child;
return nullptr;
}
const Element* child_id_get(const Element& element, ElementType type, int id)
{
for (const auto& child : element.children)
if (child.type == type && child.id == id) return &child;
return nullptr;
}
Element* element_child_id_get(Element& element, ElementType type, int id) { return child_id_get(element, type, id); }
const Element* element_child_id_get(const Element& element, ElementType type, int id)
{
return child_id_get(element, type, id);
}
int element_child_max_id_get(const Element& element, ElementType type)
{
int maxId{-1};
for (const auto& child : element.children)
if (child.type == type) maxId = std::max(maxId, child.id);
return maxId;
}
int element_child_next_id_get(const Element& element, ElementType type)
{
return element_child_max_id_get(element, type) + 1;
}
bool element_child_id_erase(Element& element, ElementType type, int id)
{
for (auto it = element.children.begin(); it != element.children.end(); ++it)
{
if (it->type != type || it->id != id) continue;
element.children.erase(it);
return true;
}
return false;
}
Element* element_first_get(Element& element, ElementType type)
{
if (element.type == type) return &element;
for (auto& child : element.children)
if (auto result = element_first_get(child, type); result) return result;
return nullptr;
}
const Element* element_first_get(const Element& element, ElementType type)
{
if (element.type == type) return &element;
for (const auto& child : element.children)
if (auto result = element_first_get(child, type); result) return result;
return nullptr;
}
float interpolation_factor(Interpolation interpolation, float value)
{
value = glm::clamp(value, 0.0f, 1.0f);
if (interpolation == Interpolation::LINEAR) return value;
if (interpolation == Interpolation::EASE_IN) return value * value;
if (interpolation == Interpolation::EASE_OUT) return 1.0f - ((1.0f - value) * (1.0f - value));
if (interpolation == Interpolation::EASE_IN_OUT)
return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f);
return 0.0f;
}
bool is_track(const Element& element)
{
return element.type == ElementType::ROOT_ANIMATION || element.type == ElementType::LAYER_ANIMATION ||
element.type == ElementType::NULL_ANIMATION || element.type == ElementType::TRIGGERS;
}
bool is_track_child_valid(ElementType parentType, ElementType childType)
{
if (parentType == ElementType::CONTENT && childType == ElementType::SHADERS) return true;
if (parentType == ElementType::SHADERS) return childType == ElementType::SHADER;
if (parentType == ElementType::SHADER) return childType == ElementType::UNIFORM;
if (parentType == ElementType::UNIFORM) return childType == ElementType::COMPONENT;
if (childType == ElementType::SHADERS || childType == ElementType::SHADER || childType == ElementType::UNIFORM ||
childType == ElementType::COMPONENT)
return false;
if (parentType == ElementType::TRIGGERS) return childType == ElementType::TRIGGER;
if (parentType == ElementType::TRIGGER) return childType == ElementType::SOUND_ELEMENT;
if (parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS)
return childType == ElementType::GROUP;
if (parentType == ElementType::ROOT_ANIMATION || parentType == ElementType::LAYER_ANIMATION ||
parentType == ElementType::NULL_ANIMATION)
return childType == ElementType::FRAME;
return true;
}
ElementType track_frame_type_get(const Element& track)
{
return track.type == ElementType::TRIGGERS ? ElementType::TRIGGER : ElementType::FRAME;
}
ElementType item_type_to_track_type_get(ItemType type)
{
if (type == ItemType::ROOT) return ElementType::ROOT_ANIMATION;
if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATION;
if (type == ItemType::NULL_) return ElementType::NULL_ANIMATION;
if (type == ItemType::TRIGGER) return ElementType::TRIGGERS;
return ElementType::UNKNOWN;
}
ElementType item_type_to_container_type_get(ItemType type)
{
if (type == ItemType::LAYER) return ElementType::LAYER_ANIMATIONS;
if (type == ItemType::NULL_) return ElementType::NULL_ANIMATIONS;
return ElementType::UNKNOWN;
}
Element* animation_group_get(Element& animation, int groupType, int groupId)
{
if (groupId < 0) return nullptr;
auto containerType = item_type_to_container_type_get(static_cast<ItemType>(groupType));
auto container = child_first_get(animation, containerType);
return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr;
}
const Element* animation_group_get(const Element& animation, int groupType, int groupId)
{
if (groupId < 0) return nullptr;
auto containerType = item_type_to_container_type_get(static_cast<ItemType>(groupType));
auto container = child_first_get(animation, containerType);
return container ? child_id_get(*container, ElementType::GROUP, groupId) : nullptr;
}
Element* animation_group_root_get(Element& animation, int groupType, int groupId)
{
auto group = animation_group_get(animation, groupType, groupId);
return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr;
}
const Element* animation_group_root_get(const Element& animation, int groupType, int groupId)
{
auto group = animation_group_get(animation, groupType, groupId);
return group ? child_first_get(*group, ElementType::ROOT_ANIMATION) : nullptr;
}
Element* animation_group_root_ensure(Element& animation, int groupType, int groupId)
{
auto group = animation_group_get(animation, groupType, groupId);
if (!group) return nullptr;
if (auto root = child_first_get(*group, ElementType::ROOT_ANIMATION)) return root;
group->children.push_back(root_animation_make());
return &group->children.back();
}
int track_id_get(const Element& track)
{
if (track.type == ElementType::LAYER_ANIMATION) return track.layerId;
if (track.type == ElementType::NULL_ANIMATION) return track.nullId;
return -1;
}
Element* track_find(Element& parent, ElementType trackType, int id)
{
for (auto& child : parent.children)
{
if (child.type == trackType && track_id_get(child) == id) return &child;
if (child.type == ElementType::GROUP)
if (auto found = track_find(child, trackType, id)) return found;
}
return nullptr;
}
const Element* track_find(const Element& parent, ElementType trackType, int id)
{
for (const auto& child : parent.children)
{
if (child.type == trackType && track_id_get(child) == id) return &child;
if (child.type == ElementType::GROUP)
if (auto found = track_find(child, trackType, id)) return found;
}
return nullptr;
}
Element* track_group_find(Element& parent, ElementType trackType, int id, int groupId)
{
for (auto& child : parent.children)
{
if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child;
if (child.type == ElementType::GROUP)
if (auto found = track_group_find(child, trackType, id, groupId)) return found;
}
return nullptr;
}
const Element* track_group_find(const Element& parent, ElementType trackType, int id, int groupId)
{
for (const auto& child : parent.children)
{
if (child.type == trackType && track_id_get(child) == id && child.groupId == groupId) return &child;
if (child.type == ElementType::GROUP)
if (auto found = track_group_find(child, trackType, id, groupId)) return found;
}
return nullptr;
}
bool is_track_group_visible(const Element& container, const Element& track)
{
if (track.groupId == -1) return true;
for (const auto& child : container.children)
if (child.type == ElementType::GROUP && child.id == track.groupId) return child.isVisible;
return true;
}
Element* animation_item_get(Element& animation, ItemType type, int id, int groupType, int groupId)
{
auto trackType = item_type_to_track_type_get(type);
if (type == ItemType::ROOT && groupType != NONE && groupId != -1)
return animation_group_root_get(animation, groupType, groupId);
if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType);
auto container = child_first_get(animation, item_type_to_container_type_get(type));
if (!container) return nullptr;
return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId)
: track_find(*container, trackType, id);
}
Element* animation_item_get(Element& animation, ItemType type, int id)
{
return animation_item_get(animation, type, id, NONE, -1);
}
const Element* animation_item_get(const Element& animation, ItemType type, int id, int groupType, int groupId)
{
auto trackType = item_type_to_track_type_get(type);
if (type == ItemType::ROOT && groupType != NONE && groupId != -1)
return animation_group_root_get(animation, groupType, groupId);
if (type == ItemType::ROOT || type == ItemType::TRIGGER) return child_first_get(animation, trackType);
auto container = child_first_get(animation, item_type_to_container_type_get(type));
if (!container) return nullptr;
return groupType != NONE && groupId != -1 ? track_group_find(*container, trackType, id, groupId)
: track_find(*container, trackType, id);
}
const Element* animation_item_get(const Element& animation, ItemType type, int id)
{
return animation_item_get(animation, type, id, NONE, -1);
}
int track_frame_child_index_get(const Element& track, int index)
{
if (index < 0) return -1;
auto frameType = track_frame_type_get(track);
int frameIndex{};
for (int i = 0; i < (int)track.children.size(); ++i)
{
if (track.children[i].type != frameType) continue;
if (frameIndex == index) return i;
++frameIndex;
}
return -1;
}
int track_frames_count_get(const Element& track)
{
auto frameType = track_frame_type_get(track);
int count{};
for (const auto& child : track.children)
if (child.type == frameType) ++count;
return count;
}
int track_frame_insert_child_index_get(const Element& track, int index)
{
auto targetFrameIndex = std::max(0, index);
auto frameType = track_frame_type_get(track);
int frameIndex{};
for (int i = 0; i < (int)track.children.size(); ++i)
{
if (track.children[i].type != frameType) continue;
if (frameIndex == targetFrameIndex) return i;
++frameIndex;
}
return (int)track.children.size();
}
Element* track_frame_get(Element& track, int index)
{
auto childIndex = track_frame_child_index_get(track, index);
return childIndex == -1 ? nullptr : &track.children[childIndex];
}
const Element* track_frame_get(const Element& track, int index)
{
auto childIndex = track_frame_child_index_get(track, index);
return childIndex == -1 ? nullptr : &track.children[childIndex];
}
Element* Anm2::element_get(ElementType type)
{
if (type == ElementType::ANIMATED_ACTOR) return &root;
if (type == ElementType::ANIMATIONS) return element_first_get(root, type);
auto content = child_first_get(root, ElementType::CONTENT);
if (!content) return nullptr;
if (type == ElementType::CONTENT) return content;
if (auto container = child_first_get(*content, type)) return container;
switch (type)
{
case ElementType::SPRITESHEETS:
case ElementType::SHADERS:
case ElementType::LAYERS:
case ElementType::NULLS:
case ElementType::EVENTS:
case ElementType::SOUNDS:
content->children.push_back(element_make(type));
return &content->children.back();
default:
break;
}
return element_first_get(root, type);
}
const Element* Anm2::element_get(ElementType type) const
{
if (type == ElementType::ANIMATED_ACTOR) return &root;
if (type == ElementType::ANIMATIONS) return element_first_get(root, type);
auto content = child_first_get(root, ElementType::CONTENT);
if (!content) return nullptr;
if (type == ElementType::CONTENT) return content;
if (auto container = child_first_get(*content, type)) return container;
return element_first_get(root, type);
}
Element* Anm2::element_get(ElementType type, int id)
{
if (type == ElementType::ANIMATION)
{
auto animations = element_get(ElementType::ANIMATIONS);
if (!animations || id < 0) return nullptr;
int current{};
for (auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
if (current == id) return &animation;
++current;
}
return nullptr;
}
auto container = element_get(element_container_type_get(type));
return container ? child_id_get(*container, type, id) : nullptr;
}
const Element* Anm2::element_get(ElementType type, int id) const
{
if (type == ElementType::ANIMATION)
{
auto animations = element_get(ElementType::ANIMATIONS);
if (!animations || id < 0) return nullptr;
int current{};
for (const auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
if (current == id) return &animation;
++current;
}
return nullptr;
}
auto container = element_get(element_container_type_get(type));
return container ? child_id_get(*container, type, id) : nullptr;
}
Element* Anm2::element_get(int animationIndex, ItemType type, int id)
{
auto animation = element_get(ElementType::ANIMATION, animationIndex);
return animation ? animation_item_get(*animation, type, id) : nullptr;
}
const Element* Anm2::element_get(int animationIndex, ItemType type, int id) const
{
auto animation = element_get(ElementType::ANIMATION, animationIndex);
return animation ? animation_item_get(*animation, type, id) : nullptr;
}
Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId)
{
auto animation = element_get(ElementType::ANIMATION, animationIndex);
return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr;
}
const Element* Anm2::element_get(int animationIndex, ItemType type, int id, int groupType, int groupId) const
{
auto animation = element_get(ElementType::ANIMATION, animationIndex);
return animation ? animation_item_get(*animation, type, id, groupType, groupId) : nullptr;
}
Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id)
{
auto item = element_get(animationIndex, type, id);
return item ? track_frame_get(*item, frameIndex) : nullptr;
}
const Element* Anm2::element_get(int animationIndex, ItemType type, int frameIndex, int id) const
{
auto item = element_get(animationIndex, type, id);
return item ? track_frame_get(*item, frameIndex) : nullptr;
}
Element* Anm2::element_get(Reference reference)
{
auto itemType = static_cast<ItemType>(reference.itemType);
auto item =
element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId);
if (reference.frameIndex < 0) return item;
return item ? track_frame_get(*item, reference.frameIndex) : nullptr;
}
const Element* Anm2::element_get(Reference reference) const
{
auto itemType = static_cast<ItemType>(reference.itemType);
auto item =
element_get(reference.animationIndex, itemType, reference.itemID, reference.groupType, reference.groupId);
if (reference.frameIndex < 0) return item;
return item ? track_frame_get(*item, reference.frameIndex) : nullptr;
}
std::set<int> Anm2::element_unused(ElementType type) const
{
std::set<int> used{};
if (type == ElementType::SPRITESHEET)
{
if (auto layers = element_get(ElementType::LAYERS))
for (const auto& layer : layers->children)
if (layer.type == ElementType::LAYER_ELEMENT && layer.spritesheetId != -1) used.insert(layer.spritesheetId);
}
else if (auto animations = element_get(ElementType::ANIMATIONS))
for (const auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
if (type == ElementType::EVENT_ELEMENT)
{
auto triggers = child_first_get(animation, ElementType::TRIGGERS);
if (!triggers) continue;
for (const auto& trigger : triggers->children)
if (trigger.type == ElementType::TRIGGER && trigger.eventId != -1) used.insert(trigger.eventId);
}
else if (type == ElementType::SOUND_ELEMENT)
{
auto triggers = child_first_get(animation, ElementType::TRIGGERS);
if (!triggers) continue;
for (const auto& trigger : triggers->children)
{
if (trigger.type != ElementType::TRIGGER) continue;
for (auto id : trigger.soundIds)
used.insert(id);
}
}
else if (type == ElementType::SHADER)
{
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](const Element& layerAnimation)
{
for (const auto& frame : layerAnimation.children)
if (frame.type == ElementType::FRAME && frame.shaderId != -1) used.insert(frame.shaderId);
});
}
else if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT)
{
auto containerType =
type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS;
auto tracks = child_first_get(animation, containerType);
if (!tracks) continue;
auto trackType =
type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION;
tracks_each(*tracks, trackType,
[&](const Element& track)
{
if (track.type == ElementType::LAYER_ANIMATION)
used.insert(track.layerId);
else if (track.type == ElementType::NULL_ANIMATION)
used.insert(track.nullId);
});
}
}
std::set<int> unused{};
if (auto container = element_get(element_container_type_get(type)))
for (const auto& element : container->children)
if (element.type == type && !used.contains(element.id)) unused.insert(element.id);
return unused;
}
std::set<int> Anm2::element_unused(ElementType type, const Element& animation) const
{
if (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT) return {};
std::set<int> used{};
auto containerType =
type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATIONS : ElementType::NULL_ANIMATIONS;
if (auto tracks = child_first_get(animation, containerType))
{
auto trackType = type == ElementType::LAYER_ELEMENT ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION;
tracks_each(*tracks, trackType,
[&](const Element& track)
{
if (track.type == ElementType::LAYER_ANIMATION)
used.insert(track.layerId);
else if (track.type == ElementType::NULL_ANIMATION)
used.insert(track.nullId);
});
}
std::set<int> unused{};
if (auto container = element_get(element_container_type_get(type)))
for (const auto& element : container->children)
if (element.type == type && !used.contains(element.id)) unused.insert(element.id);
return unused;
}
std::set<int> Anm2::element_unused(ElementType type, int parentId) const
{
if (type != ElementType::REGION) return {};
std::set<int> used{};
auto animations = element_first_get(root, ElementType::ANIMATIONS);
if (animations)
for (const auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](const Element& layerAnimation)
{
auto layer = element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId);
if (!layer || layer->spritesheetId != parentId) return;
for (const auto& frame : layerAnimation.children)
{
if (frame.type != ElementType::FRAME) continue;
if (frame.regionId != -1) used.insert(frame.regionId);
}
});
}
std::set<int> unused{};
if (auto spritesheet = element_get(ElementType::SPRITESHEET, parentId))
for (const auto& child : spritesheet->children)
if (child.type == type && !used.contains(child.id)) unused.insert(child.id);
return unused;
}
}
+478
View File
@@ -0,0 +1,478 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
enum class InterpolationBakeType
{
SPECIAL,
ALL
};
Element frame_generate(const Element& track, float time)
{
auto frame = element_make(track_frame_type_get(track));
frame.isVisible = false;
if (track.children.empty()) return frame;
time = std::max(time, 0.0f);
const Element* frameNext = nullptr;
int durationCurrent{};
int durationNext{};
auto frameType = track_frame_type_get(track);
for (int i = 0; i < (int)track.children.size(); ++i)
{
const auto& iFrame = track.children[i];
if (iFrame.type != frameType) continue;
if (frameType == ElementType::TRIGGER)
{
if ((int)time == iFrame.atFrame)
{
frame = iFrame;
break;
}
continue;
}
frame = iFrame;
durationNext += frame.duration;
if (time >= durationCurrent && time < durationNext)
{
for (int next = i + 1; next < (int)track.children.size(); ++next)
if (track.children[next].type == ElementType::FRAME)
{
frameNext = &track.children[next];
break;
}
break;
}
durationCurrent += frame.duration;
}
if (frameType != ElementType::TRIGGER && frame.interpolation != Interpolation::NONE && frameNext &&
frame.duration > 1)
{
auto amount =
interpolation_factor(frame.interpolation, (time - durationCurrent) / (durationNext - durationCurrent));
frame.rotation = glm::mix(frame.rotation, frameNext->rotation, amount);
frame.position = glm::mix(frame.position, frameNext->position, amount);
frame.scale = glm::mix(frame.scale, frameNext->scale, amount);
frame.shear = glm::mix(frame.shear, frameNext->shear, amount);
frame.colorOffset = glm::mix(frame.colorOffset, frameNext->colorOffset, amount);
frame.tint = glm::mix(frame.tint, frameNext->tint, amount);
}
return frame;
}
int frame_index_from_at_frame_get(const Element& track, int atFrame)
{
int index{};
for (const auto& frame : track.children)
{
if (frame.type != ElementType::TRIGGER) continue;
if (frame.atFrame == atFrame) return index;
++index;
}
return -1;
}
int frame_index_from_time_get(const Element& track, float time)
{
if (track.type == ElementType::TRIGGERS) return frame_index_from_at_frame_get(track, (int)time);
auto frameType = track_frame_type_get(track);
int frameCount{};
for (const auto& frame : track.children)
if (frame.type == frameType) ++frameCount;
if (frameCount == 0) return -1;
if (time <= 0.0f) return 0;
float duration{};
int index{};
for (const auto& frame : track.children)
{
if (frame.type != frameType) continue;
duration += frame.duration;
if (time < duration) return index;
++index;
}
return frameCount - 1;
}
float frame_time_from_index_get(const Element& track, int index)
{
if (index < 0) return 0.0f;
auto frameType = track_frame_type_get(track);
float time{};
int frameIndex{};
for (const auto& frame : track.children)
{
if (frame.type != frameType) continue;
if (frameIndex == index) return frameType == ElementType::TRIGGER ? (float)frame.atFrame : time;
time += frame.duration;
++frameIndex;
}
return 0.0f;
}
void frame_bake(Element& track, int index, int interval, bool isRoundScale, bool isRoundRotation)
{
auto childIndex = track_frame_child_index_get(track, index);
if (childIndex == -1) return;
auto frame = &track.children[childIndex];
auto original = *frame;
if (original.duration <= FRAME_DURATION_MIN)
{
frame->interpolation = Interpolation::NONE;
return;
}
auto nextFrame = track_frame_get(track, index + 1);
auto next = nextFrame ? *nextFrame : original;
int duration{};
interval = std::max(interval, FRAME_DURATION_MIN);
std::vector<Element> bakedFrames{};
bakedFrames.reserve((original.duration + interval - 1) / interval);
while (duration < original.duration)
{
auto baked = original;
auto amount = interpolation_factor(original.interpolation, (float)duration / original.duration);
baked.duration = std::min(interval, original.duration - duration);
baked.interpolation = Interpolation::NONE;
baked.rotation = glm::mix(original.rotation, next.rotation, amount);
baked.position = glm::mix(original.position, next.position, amount);
baked.scale = glm::mix(original.scale, next.scale, amount);
baked.shear = glm::mix(original.shear, next.shear, amount);
baked.colorOffset = glm::mix(original.colorOffset, next.colorOffset, amount);
baked.tint = glm::mix(original.tint, next.tint, amount);
if (isRoundScale) baked.scale = glm::round(baked.scale);
if (isRoundRotation) baked.rotation = std::round(baked.rotation);
bakedFrames.push_back(baked);
duration += baked.duration;
}
if (bakedFrames.empty()) return;
track.children[childIndex] = std::move(bakedFrames.front());
track.children.insert(track.children.begin() + childIndex + 1, std::make_move_iterator(bakedFrames.begin() + 1),
std::make_move_iterator(bakedFrames.end()));
}
void frames_generate_from_grid(Element& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot,
int columns, int count, int duration)
{
for (int i = 0; i < count; ++i)
{
auto frame = element_make(ElementType::FRAME);
frame.duration = duration;
frame.pivot = pivot;
frame.size = size;
frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns));
track.children.emplace_back(frame);
}
}
void frames_sort_by_at_frame(Element& track)
{
std::sort(track.children.begin(), track.children.end(),
[](const Element& a, const Element& b) { return a.atFrame < b.atFrame; });
}
bool frames_deserialize(Element& track, const std::string& string, int start, std::set<int>& indices,
std::string* errorString)
{
XMLDocument document{};
if (document.Parse(string.c_str()) != XML_SUCCESS)
{
if (errorString) *errorString = document.ErrorStr();
return false;
}
auto frameType = track_frame_type_get(track);
auto first =
frameType == ElementType::TRIGGER ? document.FirstChildElement("Trigger") : document.FirstChildElement("Frame");
if (!first)
{
if (errorString) *errorString = frameType == ElementType::TRIGGER ? "No valid trigger(s)." : "No valid frame(s).";
return false;
}
if (frameType == ElementType::FRAME)
{
start = std::clamp(start, 0, track_frames_count_get(track));
std::vector<Element> frames{};
for (auto element = first; element; element = element->NextSiblingElement("Frame"))
{
auto frame = element_read(element);
if (frame.type != ElementType::FRAME) continue;
frames.push_back(std::move(frame));
}
if (frames.empty()) return false;
auto count = (int)frames.size();
track.children.reserve(track.children.size() + frames.size());
auto childIndex = track_frame_insert_child_index_get(track, start);
track.children.insert(track.children.begin() + childIndex, std::make_move_iterator(frames.begin()),
std::make_move_iterator(frames.end()));
for (int offset = 0; offset < count; ++offset)
indices.insert(start + offset);
return !indices.empty();
}
auto has_conflict = [&](int value)
{
for (auto& trigger : track.children)
if (trigger.type == ElementType::TRIGGER && trigger.atFrame == value) return true;
return false;
};
std::vector<int> atFrames{};
int count{};
for (auto element = first; element; element = element->NextSiblingElement("Trigger"))
{
auto trigger = element_read(element);
if (trigger.type != ElementType::TRIGGER) continue;
trigger.atFrame = start + count;
while (has_conflict(trigger.atFrame))
++trigger.atFrame;
atFrames.push_back(trigger.atFrame);
track.children.push_back(trigger);
++count;
}
frames_sort_by_at_frame(track);
for (auto atFrame : atFrames)
if (auto index = frame_index_from_at_frame_get(track, atFrame); index != -1) indices.insert(index);
return !indices.empty();
}
void frames_change(Element& track, FrameChange change, ItemType itemType, ChangeType changeType,
const std::set<int>& selection)
{
const auto clamp_identity = [](auto value) { return value; };
const auto clamp_duration = [](int value) { return std::max(FRAME_DURATION_MIN, value); };
if (selection.empty()) return;
auto apply_scalar_with_clamp = [&](auto& target, const auto& optionalValue, auto clampFunc)
{
if (!optionalValue) return;
auto value = *optionalValue;
switch (changeType)
{
case ChangeType::ADJUST:
target = clampFunc(value);
break;
case ChangeType::ADD:
target = clampFunc(target + value);
break;
case ChangeType::SUBTRACT:
target = clampFunc(target - value);
break;
case ChangeType::MULTIPLY:
target = clampFunc(target * value);
break;
case ChangeType::DIVIDE:
if (value == decltype(value){}) return;
target = clampFunc(target / value);
break;
}
};
auto apply_scalar = [&](auto& target, const auto& optionalValue)
{ apply_scalar_with_clamp(target, optionalValue, clamp_identity); };
for (auto index : selection)
{
auto frame = track_frame_get(track, index);
if (!frame) continue;
if (change.isVisible) frame->isVisible = *change.isVisible;
if (change.interpolation) frame->interpolation = *change.interpolation;
if (change.isFlipX) frame->scale.x = -frame->scale.x;
if (change.isFlipY) frame->scale.y = -frame->scale.y;
apply_scalar(frame->rotation, change.rotation);
apply_scalar_with_clamp(frame->duration, change.duration, clamp_duration);
if (itemType == ItemType::LAYER)
{
apply_scalar(frame->crop.x, change.cropX);
apply_scalar(frame->crop.y, change.cropY);
apply_scalar(frame->pivot.x, change.pivotX);
apply_scalar(frame->pivot.y, change.pivotY);
apply_scalar(frame->size.x, change.sizeX);
apply_scalar(frame->size.y, change.sizeY);
if (change.regionId) frame->regionId = *change.regionId;
if (change.shaderId) frame->shaderId = *change.shaderId;
}
apply_scalar(frame->position.x, change.positionX);
apply_scalar(frame->position.y, change.positionY);
apply_scalar(frame->scale.x, change.scaleX);
apply_scalar(frame->scale.y, change.scaleY);
apply_scalar(frame->shear.x, change.shearX);
apply_scalar(frame->shear.y, change.shearY);
apply_scalar(frame->colorOffset.x, change.colorOffsetR);
apply_scalar(frame->colorOffset.y, change.colorOffsetG);
apply_scalar(frame->colorOffset.z, change.colorOffsetB);
apply_scalar(frame->tint.x, change.tintR);
apply_scalar(frame->tint.y, change.tintG);
apply_scalar(frame->tint.z, change.tintB);
apply_scalar(frame->tint.w, change.tintA);
}
}
bool is_special_interpolated_frames(const Element& element)
{
if (element.type == ElementType::FRAME && element.interpolation != Interpolation::NONE &&
element.interpolation != Interpolation::LINEAR)
return true;
for (const auto& child : element.children)
if (is_special_interpolated_frames(child)) return true;
return false;
}
bool is_frame_interpolation_baked(const Element& frame, InterpolationBakeType type)
{
if (frame.interpolation == Interpolation::NONE) return false;
return type == InterpolationBakeType::ALL || frame.interpolation != Interpolation::LINEAR;
}
void track_frames_bake(Element& track, int interval, bool isRoundScale, bool isRoundRotation,
InterpolationBakeType type)
{
for (int index = (int)track.children.size() - 1; index >= 0; --index)
{
auto original = track.children[index];
if (original.type != ElementType::FRAME) continue;
if (!is_frame_interpolation_baked(original, type)) continue;
if (original.duration <= FRAME_DURATION_MIN)
{
track.children[index].interpolation = Interpolation::NONE;
continue;
}
auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME
? track.children[index + 1]
: original;
int duration{};
int insertIndex = index;
while (duration < original.duration)
{
auto baked = original;
float amount = interpolation_factor(original.interpolation, (float)duration / original.duration);
baked.duration = std::min(interval, original.duration - duration);
baked.interpolation = Interpolation::NONE;
baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount);
baked.position = glm::mix(original.position, nextFrame.position, amount);
baked.scale = glm::mix(original.scale, nextFrame.scale, amount);
baked.shear = glm::mix(original.shear, nextFrame.shear, amount);
baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount);
baked.tint = glm::mix(original.tint, nextFrame.tint, amount);
if (isRoundScale) baked.scale = glm::round(baked.scale);
if (isRoundRotation) baked.rotation = std::round(baked.rotation);
if (insertIndex == index)
track.children[insertIndex] = baked;
else
track.children.insert(track.children.begin() + insertIndex, baked);
duration += baked.duration;
++insertIndex;
}
}
}
void interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation,
InterpolationBakeType type)
{
if (is_track(element))
{
track_frames_bake(element, interval, isRoundScale, isRoundRotation, type);
return;
}
for (auto& child : element.children)
interpolated_frames_bake(child, interval, isRoundScale, isRoundRotation, type);
}
void special_interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation)
{
interpolated_frames_bake(element, interval, isRoundScale, isRoundRotation, InterpolationBakeType::SPECIAL);
}
void all_interpolated_frames_bake(Element& element, int interval, bool isRoundScale, bool isRoundRotation)
{
interpolated_frames_bake(element, interval, isRoundScale, isRoundRotation, InterpolationBakeType::ALL);
}
void layer_animation_ids_remap(Element& element, const std::unordered_map<int, int>& remap)
{
if (element.type == ElementType::LAYER_ANIMATION)
if (auto it = remap.find(element.layerId); it != remap.end()) element.layerId = it->second;
for (auto& child : element.children)
layer_animation_ids_remap(child, remap);
}
int track_length_get(const Element& track)
{
int length{};
if (track.type == ElementType::TRIGGERS)
{
for (const auto& trigger : track.children)
if (trigger.type == ElementType::TRIGGER) length = std::max(length, trigger.atFrame);
return length;
}
for (const auto& frame : track.children)
if (frame.type == ElementType::FRAME) length += frame.duration;
return length;
}
int animation_length_get(const Element& animation)
{
int length{};
auto group_roots_length_apply = [&](const Element& container)
{
for (const auto& child : container.children)
if (child.type == ElementType::GROUP)
if (auto rootAnimation = child_first_get(child, ElementType::ROOT_ANIMATION))
length = std::max(length, track_length_get(*rootAnimation));
};
if (auto rootAnimation = child_first_get(animation, ElementType::ROOT_ANIMATION))
length = std::max(length, track_length_get(*rootAnimation));
if (auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS))
{
group_roots_length_apply(*layerAnimations);
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](const Element& track) { length = std::max(length, track_length_get(track)); });
}
if (auto nullAnimations = child_first_get(animation, ElementType::NULL_ANIMATIONS))
{
group_roots_length_apply(*nullAnimations);
tracks_each(*nullAnimations, ElementType::NULL_ANIMATION,
[&](const Element& track) { length = std::max(length, track_length_get(track)); });
}
if (auto triggers = child_first_get(animation, ElementType::TRIGGERS))
length = std::max(length, track_length_get(*triggers));
return std::max(length, FRAME_DURATION_MIN);
}
}
+440
View File
@@ -0,0 +1,440 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
constexpr std::string_view ANM2ED_GROUP_FRAME_BACKUP_TAG = "FrameRestore";
bool is_frame_transform_default(const Element& frame)
{
auto base = element_make(ElementType::FRAME);
return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation &&
frame.shear == base.shear && frame.tint == base.tint && frame.colorOffset == base.colorOffset;
}
bool is_root_animation_transform_default(const Element& root)
{
for (const auto& frame : root.children)
if (frame.type == ElementType::FRAME && !is_frame_transform_default(frame)) return false;
return true;
}
bool is_group_frame_backup(const Element& element)
{
return element.type == ElementType::UNKNOWN && element.tag == ANM2ED_GROUP_FRAME_BACKUP_TAG;
}
void group_frame_backups_erase(Element& group)
{
std::erase_if(group.children, [](const Element& child) { return is_group_frame_backup(child); });
}
Element group_frame_backup_make(const Element& container, const Element& group, ElementType trackType)
{
Element backup{};
backup.type = ElementType::UNKNOWN;
backup.tag = std::string(ANM2ED_GROUP_FRAME_BACKUP_TAG);
if (auto root = child_first_get(group, ElementType::ROOT_ANIMATION)) backup.children.push_back(*root);
for (const auto& item : container.children)
if (item.type == trackType && item.groupId == group.id) backup.children.push_back(item);
return backup;
}
void frame_group_root_apply(Element& frame, const Element& rootFrame)
{
auto rootScale = math::percent_to_unit(rootFrame.scale);
auto offset = frame.position * rootScale;
auto radians = glm::radians(rootFrame.rotation);
auto cos = std::cos(radians);
auto sin = std::sin(radians);
frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos);
frame.scale *= rootScale;
frame.rotation += rootFrame.rotation;
frame.tint *= rootFrame.tint;
frame.colorOffset += rootFrame.colorOffset;
}
void track_group_root_bake(Element& track, const Element& root, int frameNum)
{
auto trackLength = track_length_get(track);
if (trackLength <= 0) return;
auto length = std::max({trackLength, track_length_get(root), frameNum, FRAME_DURATION_MIN});
std::vector<Element> frames{};
frames.reserve(length);
for (int time = 0; time < length; ++time)
{
auto frame = frame_generate(track, (float)time);
auto rootFrame = frame_generate(root, (float)time);
frame_group_root_apply(frame, rootFrame);
frame.duration = FRAME_DURATION_MIN;
frame.interpolation = Interpolation::NONE;
frames.push_back(std::move(frame));
}
track.children = std::move(frames);
}
void group_frames_bake(Element& container, ElementType trackType, int frameNum)
{
for (auto& group : container.children)
{
if (group.type != ElementType::GROUP) continue;
group_frame_backups_erase(group);
auto root = child_first_get(group, ElementType::ROOT_ANIMATION);
if (!root || is_root_animation_transform_default(*root)) continue;
auto backup = group_frame_backup_make(container, group, trackType);
for (auto& item : container.children)
if (item.type == trackType && item.groupId == group.id) track_group_root_bake(item, *root, frameNum);
*root = root_animation_make();
group.children.push_back(std::move(backup));
}
}
void group_frames_bake(Element& element)
{
if (element.type == ElementType::ANIMATION)
{
if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS))
group_frames_bake(*layerAnimations, ElementType::LAYER_ANIMATION, element.frameNum);
if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS))
group_frames_bake(*nullAnimations, ElementType::NULL_ANIMATION, element.frameNum);
}
for (auto& child : element.children)
group_frames_bake(child);
}
void group_frames_restore(Element& container, ElementType trackType)
{
std::set<int> restoredGroupIds{};
for (auto& group : container.children)
{
if (group.type != ElementType::GROUP) continue;
if (group.id < 0) continue;
const Element* backup{};
for (const auto& child : group.children)
if (is_group_frame_backup(child))
{
backup = &child;
break;
}
if (!backup) continue;
auto root = root_animation_make();
if (auto currentRoot = child_first_get(group, ElementType::ROOT_ANIMATION)) root = *currentRoot;
std::vector<Element> restoredTracks{};
bool isRootRestored{};
for (const auto& child : backup->children)
{
if (child.type == ElementType::ROOT_ANIMATION && !isRootRestored)
{
root = child;
isRootRestored = true;
}
else if (child.type == trackType)
{
auto track = child;
track.groupId = group.id;
restoredTracks.push_back(std::move(track));
}
}
if (!isRootRestored && restoredTracks.empty()) continue;
group.children = {std::move(root)};
group.children.insert(group.children.end(), std::make_move_iterator(restoredTracks.begin()),
std::make_move_iterator(restoredTracks.end()));
restoredGroupIds.insert(group.id);
}
if (restoredGroupIds.empty()) return;
std::erase_if(container.children, [&](const Element& item)
{ return item.type == trackType && restoredGroupIds.contains(item.groupId); });
}
void group_frames_restore(Element& element)
{
if (element.type == ElementType::ANIMATION)
{
if (auto layerAnimations = child_first_get(element, ElementType::LAYER_ANIMATIONS))
group_frames_restore(*layerAnimations, ElementType::LAYER_ANIMATION);
if (auto nullAnimations = child_first_get(element, ElementType::NULL_ANIMATIONS))
group_frames_restore(*nullAnimations, ElementType::NULL_ANIMATION);
}
for (auto& child : element.children)
group_frames_restore(child);
}
int child_index_get(const Element& element, ElementType type)
{
for (int i = 0; i < (int)element.children.size(); ++i)
if (element.children[i].type == type) return i;
return -1;
}
ElementType track_container_track_type_get(ElementType containerType)
{
if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION;
if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION;
return ElementType::UNKNOWN;
}
ElementType track_container_group_container_type_get(ElementType containerType)
{
if (containerType == ElementType::LAYER_ANIMATIONS) return ElementType::LAYER_ANIMATION_GROUPS;
if (containerType == ElementType::NULL_ANIMATIONS) return ElementType::NULL_ANIMATION_GROUPS;
return ElementType::UNKNOWN;
}
int track_group_insert_index_get(const Element& container, ElementType trackType, int groupId)
{
for (int i = 0; i < (int)container.children.size(); ++i)
if (container.children[i].type == trackType && container.children[i].groupId == groupId) return i;
return (int)container.children.size();
}
void group_metadata_embed(Element& animation, ElementType trackContainerType)
{
auto groupContainerType = track_container_group_container_type_get(trackContainerType);
auto trackType = track_container_track_type_get(trackContainerType);
auto groupContainerIndex = child_index_get(animation, groupContainerType);
if (groupContainerIndex < 0 || trackType == ElementType::UNKNOWN) return;
std::vector<Element> groups{};
for (const auto& child : animation.children[groupContainerIndex].children)
if (child.type == ElementType::GROUP) groups.push_back(child);
if (!groups.empty())
{
auto trackContainerIndex = child_index_get(animation, trackContainerType);
if (trackContainerIndex < 0)
{
animation.children.push_back(element_make(trackContainerType));
trackContainerIndex = (int)animation.children.size() - 1;
}
auto& container = animation.children[trackContainerIndex];
std::set<int> groupIds{};
for (const auto& group : groups)
if (group.id >= 0) groupIds.insert(group.id);
std::erase_if(container.children, [&](const Element& child)
{ return child.type == ElementType::GROUP && groupIds.contains(child.id); });
std::stable_sort(groups.begin(), groups.end(),
[](const Element& left, const Element& right)
{
if (left.index == -1 || right.index == -1) return left.index != -1;
return left.index < right.index;
});
for (auto& group : groups)
{
auto insertIndex = group.index >= 0 ? std::min(group.index, (int)container.children.size())
: track_group_insert_index_get(container, trackType, group.id);
group.index = -1;
container.children.insert(container.children.begin() + insertIndex, std::move(group));
}
}
std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; });
}
void group_metadata_embed(Element& element)
{
if (element.type == ElementType::ANIMATION)
{
group_metadata_embed(element, ElementType::LAYER_ANIMATIONS);
group_metadata_embed(element, ElementType::NULL_ANIMATIONS);
}
for (auto& child : element.children)
group_metadata_embed(child);
}
void group_metadata_extract(Element& animation, ElementType trackContainerType, Flags flags)
{
auto groupContainerType = track_container_group_container_type_get(trackContainerType);
if (groupContainerType == ElementType::UNKNOWN) return;
std::erase_if(animation.children, [&](const Element& child) { return child.type == groupContainerType; });
if (!has_flag(flags, SERIALIZE_GROUPS)) return;
auto trackContainerIndex = child_index_get(animation, trackContainerType);
if (trackContainerIndex < 0) return;
auto& container = animation.children[trackContainerIndex];
auto groupContainer = element_make(groupContainerType);
std::vector<Element> tracks{};
tracks.reserve(container.children.size());
for (int i = 0; i < (int)container.children.size(); ++i)
{
auto child = container.children[i];
if (child.type == ElementType::GROUP)
{
child.index = i;
groupContainer.children.push_back(std::move(child));
}
else
tracks.push_back(std::move(child));
}
container.children = std::move(tracks);
if (groupContainer.children.empty()) return;
animation.children.insert(animation.children.begin() + trackContainerIndex + 1, std::move(groupContainer));
}
void group_metadata_extract(Element& element, Flags flags)
{
if (element.type == ElementType::ANIMATION)
{
group_metadata_extract(element, ElementType::LAYER_ANIMATIONS, flags);
group_metadata_extract(element, ElementType::NULL_ANIMATIONS, flags);
}
for (auto& child : element.children)
group_metadata_extract(child, flags);
}
void groups_flatten(Element& element)
{
auto container_flatten = [](Element& container, ElementType childType, bool isRootKept)
{
int nextGroupId{};
for (const auto& item : container.children)
if (item.type == ElementType::GROUP) nextGroupId = std::max(nextGroupId, item.id + 1);
std::vector<Element> flattened{};
for (auto item : container.children)
{
if (item.type != ElementType::GROUP)
{
flattened.push_back(item);
continue;
}
if (item.id < 0) item.id = nextGroupId++;
auto groupId = item.id;
auto children = std::move(item.children);
item.children.clear();
if (isRootKept)
{
bool isRootFound{};
for (auto child : children)
if (child.type == ElementType::ROOT_ANIMATION)
{
if (isRootFound) continue;
item.children.push_back(child);
isRootFound = true;
}
if (!isRootFound) item.children.push_back(root_animation_make());
}
flattened.push_back(item);
for (auto child : children)
{
if (child.type != childType) continue;
child.groupId = groupId;
flattened.push_back(child);
}
}
std::set<int> groupIds{};
for (const auto& item : flattened)
if (item.type == ElementType::GROUP) groupIds.insert(item.id);
for (auto& item : flattened)
if (item.type == childType && !groupIds.contains(item.groupId)) item.groupId = -1;
container.children = std::move(flattened);
};
if (element.type == ElementType::ANIMATIONS)
container_flatten(element, ElementType::ANIMATION, false);
else if (element.type == ElementType::LAYER_ANIMATIONS)
container_flatten(element, ElementType::LAYER_ANIMATION, true);
else if (element.type == ElementType::NULL_ANIMATIONS)
container_flatten(element, ElementType::NULL_ANIMATION, true);
for (auto& child : element.children)
groups_flatten(child);
}
void group_children_nest(Element& container, ElementType childType)
{
if (childType == ElementType::UNKNOWN) return;
std::set<int> groupIds{};
for (const auto& child : container.children)
if (child.type == ElementType::GROUP && child.id >= 0) groupIds.insert(child.id);
if (groupIds.empty()) return;
std::unordered_map<int, std::vector<Element>> groupedChildren{};
for (const auto& child : container.children)
{
if (child.type != childType || !groupIds.contains(child.groupId)) continue;
auto groupedChild = child;
groupedChild.groupId = -1;
groupedChildren[child.groupId].push_back(std::move(groupedChild));
}
std::vector<Element> nested{};
nested.reserve(container.children.size());
for (auto child : container.children)
{
if (child.type == childType && groupIds.contains(child.groupId)) continue;
if (child.type == ElementType::GROUP)
{
auto groupId = child.id;
child.index = -1;
if (auto grouped = groupedChildren.find(groupId); grouped != groupedChildren.end())
child.children.insert(child.children.end(), std::make_move_iterator(grouped->second.begin()),
std::make_move_iterator(grouped->second.end()));
}
nested.push_back(std::move(child));
}
container.children = std::move(nested);
}
void groups_nest(Element& element)
{
if (element.type == ElementType::ANIMATIONS)
group_children_nest(element, ElementType::ANIMATION);
else if (element.type == ElementType::LAYER_ANIMATIONS)
group_children_nest(element, ElementType::LAYER_ANIMATION);
else if (element.type == ElementType::NULL_ANIMATIONS)
group_children_nest(element, ElementType::NULL_ANIMATION);
for (auto& child : element.children)
groups_nest(child);
}
void source_document_erase(Element& element)
{
std::erase_if(element.children, [](const Element& child) { return is_source_document_tag(child.tag); });
for (auto& child : element.children)
source_document_erase(child);
}
}
+333
View File
@@ -0,0 +1,333 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
constexpr std::uint64_t ANM2_HASH_OFFSET = 14695981039346656037ull;
constexpr std::uint64_t ANM2_HASH_PRIME = 1099511628211ull;
struct BakeAttributes
{
Interpolation interpolation{Interpolation::NONE};
int delay{FRAME_DURATION_MIN};
};
void element_hash_append(std::uint64_t&, const Element&, ElementType, Flags,
std::optional<BakeAttributes> = std::nullopt);
void hash_byte_append(std::uint64_t& hash, unsigned char value)
{
hash ^= value;
hash *= ANM2_HASH_PRIME;
}
void hash_bytes_append(std::uint64_t& hash, const char* data, std::size_t size)
{
for (std::size_t i = 0; i < size; ++i)
hash_byte_append(hash, (unsigned char)data[i]);
}
void hash_string_append(std::uint64_t& hash, std::string_view value)
{
auto size = (std::uint64_t)value.size();
hash_bytes_append(hash, reinterpret_cast<const char*>(&size), sizeof(size));
hash_bytes_append(hash, value.data(), value.size());
}
void hash_attr_append(std::uint64_t& hash, std::string_view name, std::string_view value)
{
hash_byte_append(hash, 'A');
hash_string_append(hash, name);
hash_string_append(hash, value);
}
void hash_attr_append(std::uint64_t& hash, std::string_view name, int value)
{
char buffer[32]{};
XMLUtil::ToStr(value, buffer, sizeof(buffer));
hash_attr_append(hash, name, std::string_view(buffer));
}
void hash_attr_append(std::uint64_t& hash, std::string_view name, bool isValue)
{
char buffer[8]{};
XMLUtil::ToStr(isValue, buffer, sizeof(buffer));
hash_attr_append(hash, name, std::string_view(buffer));
}
void hash_attr_append(std::uint64_t& hash, std::string_view name, float value)
{
char buffer[64]{};
XMLUtil::ToStr(value, buffer, sizeof(buffer));
hash_attr_append(hash, name, std::string_view(buffer));
}
void hash_path_attr_append(std::uint64_t& hash, std::string_view name, const std::filesystem::path& pathValue)
{
if (pathValue.empty()) return;
auto value = path::to_utf8(pathValue);
hash_attr_append(hash, name, value);
}
void hash_interpolation_attr_append(std::uint64_t& hash, Interpolation interpolation)
{
if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR)
{
hash_attr_append(hash, "Interpolated", interpolation == Interpolation::LINEAR);
return;
}
auto value = INTERPOLATION_VALUES[(std::size_t)interpolation];
if (!value.empty()) hash_attr_append(hash, "Interpolated", value);
}
void hash_origin_attr_append(std::uint64_t& hash, const Element& element)
{
auto origin = ORIGIN_VALUES[(std::size_t)element.origin];
if (!origin.empty())
{
hash_attr_append(hash, "Origin", origin);
return;
}
hash_attr_append(hash, "XPivot", element.pivot.x);
hash_attr_append(hash, "YPivot", element.pivot.y);
}
void frame_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags)
{
if (parentType == ElementType::LAYER_ANIMATION)
{
bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1;
bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion;
if (isHasValidRegion) hash_attr_append(hash, "RegionId", element.regionId);
if (isWriteRegionValues)
{
hash_attr_append(hash, "XPivot", element.pivot.x);
hash_attr_append(hash, "YPivot", element.pivot.y);
hash_attr_append(hash, "XCrop", element.crop.x);
hash_attr_append(hash, "YCrop", element.crop.y);
hash_attr_append(hash, "Width", element.size.x);
hash_attr_append(hash, "Height", element.size.y);
}
}
hash_attr_append(hash, "XPosition", element.position.x);
hash_attr_append(hash, "YPosition", element.position.y);
hash_attr_append(hash, "Delay", element.duration);
hash_attr_append(hash, "Visible", element.isVisible);
hash_attr_append(hash, "XScale", element.scale.x);
hash_attr_append(hash, "YScale", element.scale.y);
if (has_flag(flags, SERIALIZE_EXTENSIONS))
{
hash_attr_append(hash, "ShearX", element.shear.x);
hash_attr_append(hash, "ShearY", element.shear.y);
}
hash_attr_append(hash, "RedTint", color_write(element.tint.r));
hash_attr_append(hash, "GreenTint", color_write(element.tint.g));
hash_attr_append(hash, "BlueTint", color_write(element.tint.b));
hash_attr_append(hash, "AlphaTint", color_write(element.tint.a));
hash_attr_append(hash, "RedOffset", color_write(element.colorOffset.r));
hash_attr_append(hash, "GreenOffset", color_write(element.colorOffset.g));
hash_attr_append(hash, "BlueOffset", color_write(element.colorOffset.b));
hash_attr_append(hash, "Rotation", element.rotation);
hash_interpolation_attr_append(hash, element.interpolation);
if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1)
hash_attr_append(hash, "ShaderId", element.shaderId);
}
void bake_attributes_hash_append(std::uint64_t& hash, Interpolation interpolation, int bakeDelay)
{
auto value = INTERPOLATION_VALUES[(std::size_t)interpolation];
if (!value.empty()) hash_attr_append(hash, "BakeInterpolation", value);
hash_attr_append(hash, "BakeDelay", bakeDelay);
}
void element_attributes_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags)
{
if (element.type == ElementType::INFO)
{
hash_attr_append(hash, "CreatedBy", element.createdBy);
hash_attr_append(hash, "CreatedOn", element.createdOn);
hash_attr_append(hash, "Fps", element.fps);
hash_attr_append(hash, "Version", element.version);
}
else if (element.type == ElementType::ANIMATIONS)
hash_attr_append(hash, "DefaultAnimation", element.defaultAnimation);
else if (element.type == ElementType::SPRITESHEET)
{
hash_attr_append(hash, "Id", element.id);
hash_path_attr_append(hash, "Path", element.path);
}
else if (element.type == ElementType::SHADER)
{
hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
hash_path_attr_append(hash, "Vertex", element.vertex);
hash_path_attr_append(hash, "Fragment", element.fragment);
}
else if (element.type == ElementType::UNIFORM)
{
hash_attr_append(hash, "Name", element.name);
if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding);
if (!element.value.empty()) hash_attr_append(hash, "Value", element.value);
}
else if (element.type == ElementType::COMPONENT)
{
hash_attr_append(hash, "Index", element.index);
if (!element.binding.empty()) hash_attr_append(hash, "Binding", element.binding);
if (!element.value.empty()) hash_attr_append(hash, "Value", element.value);
}
else if (element.type == ElementType::REGION)
{
hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
hash_attr_append(hash, "XCrop", element.crop.x);
hash_attr_append(hash, "YCrop", element.crop.y);
hash_attr_append(hash, "Width", element.size.x);
hash_attr_append(hash, "Height", element.size.y);
hash_origin_attr_append(hash, element);
}
else if (element.type == ElementType::LAYER_ELEMENT)
{
hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
hash_attr_append(hash, "SpritesheetId", element.spritesheetId);
}
else if (element.type == ElementType::NULL_ELEMENT)
{
hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
if (element.isShowRect) hash_attr_append(hash, "ShowRect", element.isShowRect);
}
else if (element.type == ElementType::GROUP)
{
if (!is_nested_group_parent(parentType, flags)) hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
hash_attr_append(hash, "IsExpanded", element.isExpanded);
hash_attr_append(hash, "Visible", element.isVisible);
if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) &&
element.index != -1)
hash_attr_append(hash, "Index", element.index);
}
else if (element.type == ElementType::EVENT_ELEMENT)
{
hash_attr_append(hash, "Id", element.id);
hash_attr_append(hash, "Name", element.name);
}
else if (element.type == ElementType::SOUND_ELEMENT)
{
hash_attr_append(hash, "Id", element.id);
if (parentType != ElementType::TRIGGER) hash_path_attr_append(hash, "Path", element.path);
}
else if (element.type == ElementType::ANIMATION)
{
hash_attr_append(hash, "Name", element.name);
hash_attr_append(hash, "FrameNum", element.frameNum);
hash_attr_append(hash, "Loop", element.isLoop);
if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId);
}
else if (element.type == ElementType::LAYER_ANIMATION)
{
hash_attr_append(hash, "LayerId", element.layerId);
hash_attr_append(hash, "Visible", element.isVisible);
if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId);
}
else if (element.type == ElementType::NULL_ANIMATION)
{
hash_attr_append(hash, "NullId", element.nullId);
hash_attr_append(hash, "Visible", element.isVisible);
if (element.groupId != -1 && is_group_id_serialized(flags)) hash_attr_append(hash, "GroupId", element.groupId);
}
else if (element.type == ElementType::FRAME)
frame_attributes_hash_append(hash, element, parentType, flags);
else if (element.type == ElementType::TRIGGER)
{
if (element.eventId != -1) hash_attr_append(hash, "EventId", element.eventId);
hash_attr_append(hash, "AtFrame", element.atFrame);
}
}
void trigger_sounds_hash_append(std::uint64_t& hash, const Element& element, Flags flags)
{
if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return;
for (auto soundId : element.soundIds)
{
if (soundId == -1) continue;
auto sound = element_make(ElementType::SOUND_ELEMENT);
sound.id = soundId;
element_hash_append(hash, sound, ElementType::TRIGGER, flags);
}
}
void baked_frames_hash_append(std::uint64_t& hash, const Element& track, int index, Flags flags)
{
const auto& original = track.children[index];
auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME
? track.children[index + 1]
: original;
auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN);
for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex)
{
auto baked = original;
auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay);
baked.duration = FRAME_DURATION_MIN;
baked.interpolation = Interpolation::NONE;
baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount);
baked.position = glm::mix(original.position, nextFrame.position, amount);
baked.scale = glm::mix(original.scale, nextFrame.scale, amount);
baked.shear = glm::mix(original.shear, nextFrame.shear, amount);
baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount);
baked.tint = glm::mix(original.tint, nextFrame.tint, amount);
element_hash_append(hash, baked, track.type, flags,
bakeIndex == 0 ? std::optional<BakeAttributes>({original.interpolation, bakeDelay})
: std::nullopt);
}
}
void element_hash_append(std::uint64_t& hash, const Element& element, ElementType parentType, Flags flags,
std::optional<BakeAttributes> bakeAttributes)
{
auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type);
hash_byte_append(hash, 'E');
hash_string_append(hash, tag.empty() ? std::string_view(element.tag) : tag);
element_attributes_hash_append(hash, element, parentType, flags);
if (bakeAttributes) bake_attributes_hash_append(hash, bakeAttributes->interpolation, bakeAttributes->delay);
hash_byte_append(hash, '[');
trigger_sounds_hash_append(hash, element, flags);
for (int i = 0; i < (int)element.children.size(); ++i)
{
const auto& child = element.children[i];
if (element_write_skip(child, element.type, flags)) continue;
if (is_track(element) && is_frame_bake_serialized(child, flags))
baked_frames_hash_append(hash, element, i, flags);
else
element_hash_append(hash, child, element.type, flags);
}
hash_byte_append(hash, ']');
}
std::uint64_t element_hash(const Element& element, Flags flags)
{
auto hash = ANM2_HASH_OFFSET;
element_hash_append(hash, element, ElementType::UNKNOWN, flags);
return hash;
}
std::uint64_t anm2_hash_get(const Element& root, Options options)
{
auto hash = ANM2_HASH_OFFSET;
hash_byte_append(hash, options.isExtendedFormat ? 'E' : 'A');
element_hash_append(hash, root, ElementType::UNKNOWN, SERIALIZE_ANM2ED_DEFAULT);
return hash;
}
}
+106
View File
@@ -0,0 +1,106 @@
#pragma once
#include "anm2.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <filesystem>
#include <format>
#include <functional>
#include <iterator>
#include <limits>
#include <map>
#include <optional>
#include <set>
#include <string_view>
#include <unordered_map>
#include <vector>
#include <tinyxml2/tinyxml2.h>
#include "file.hpp"
#include "math.hpp"
#include "path.hpp"
#include "time.hpp"
#include "working_directory.hpp"
#include "xml.hpp"
namespace anm2ed
{
inline constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)";
inline constexpr std::array<std::string_view, (std::size_t)Interpolation::COUNT> INTERPOLATION_VALUES = {
"", "", "EaseIn", "EaseOut", "EaseInOut"};
inline constexpr std::array<std::string_view, (std::size_t)Origin::COUNT> ORIGIN_VALUES = {"", "TopLeft", "Center"};
inline constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument";
bool is_source_document_tag(std::string_view);
ElementType element_type_get(std::string_view);
std::string_view element_tag_get(ElementType);
ElementType element_container_type_get(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();
void group_frames_bake(Element&);
void group_frames_restore(Element&);
void group_metadata_embed(Element&);
void group_metadata_extract(Element&, Flags);
void groups_flatten(Element&);
void groups_nest(Element&);
void source_document_erase(Element&);
void shader_ids_repair(Element&);
void shader_frame_ids_repair(Element&);
void shader_ids_remap(Element&);
void region_ids_remap(Element&);
void region_frame_ids_repair(Element&);
void layer_animation_ids_remap(Element&, const std::unordered_map<int, int>&);
Element* child_first_get(Element&, ElementType);
const Element* child_first_get(const Element&, ElementType);
Element* child_id_get(Element&, ElementType, int);
const Element* child_id_get(const Element&, ElementType, int);
bool is_track(const Element&);
bool is_track_child_valid(ElementType, ElementType);
bool is_track_group_visible(const Element&, const Element&);
bool is_nested_group_parent(ElementType, Flags);
bool is_group_id_serialized(Flags);
bool element_write_skip(const Element&, ElementType, Flags);
bool is_frame_bake_serialized(const Element&, Flags);
bool is_special_interpolated_frames(const Element&);
void special_interpolated_frames_bake(Element&, int, bool, bool);
void all_interpolated_frames_bake(Element&, int, bool, bool);
float interpolation_factor(Interpolation, float);
int color_write(float);
std::uint64_t anm2_hash_get(const Element&, Options);
std::uint64_t element_hash(const Element&, Flags);
ElementType track_frame_type_get(const Element&);
ElementType item_type_to_container_type_get(ItemType);
int track_id_get(const Element&);
int track_frame_child_index_get(const Element&, int);
int track_frames_count_get(const Element&);
int track_frame_insert_child_index_get(const Element&, int);
Element* track_find(Element&, ElementType, int);
const Element* track_find(const Element&, ElementType, int);
Element* track_group_find(Element&, ElementType, int, int);
const Element* track_group_find(const Element&, ElementType, int, int);
Element* animation_container_get(Element&, ElementType);
template <typename Callback> void tracks_each(Element& parent, ElementType trackType, Callback&& callback)
{
for (auto& child : parent.children)
if (child.type == trackType)
callback(child);
else if (child.type == ElementType::GROUP)
tracks_each(child, trackType, callback);
}
template <typename Callback> void tracks_each(const Element& parent, ElementType trackType, Callback&& callback)
{
for (const auto& child : parent.children)
if (child.type == trackType)
callback(child);
else if (child.type == ElementType::GROUP)
tracks_each(child, trackType, callback);
}
}
+213
View File
@@ -0,0 +1,213 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
bool Anm2::animations_deserialize(const std::string& string, int start, std::set<int>& indices,
std::string* errorString, std::set<int>* groupIds)
{
XMLDocument document{};
if (document.Parse(string.c_str()) != XML_SUCCESS)
{
if (errorString) *errorString = document.ErrorStr();
return false;
}
auto animations = element_get(ElementType::ANIMATIONS);
if (!animations)
{
if (errorString) *errorString = "No animations container.";
return false;
}
start = std::clamp(start, 0, animations_count_get(*animations));
std::vector<Element> items{};
std::map<int, int> groupRemap{};
auto nextGroupId = element_child_next_id_get(*animations, ElementType::GROUP);
for (auto element = document.FirstChildElement(); element; element = element->NextSiblingElement())
{
auto item = element_read(element);
if (item.type != ElementType::ANIMATION && item.type != ElementType::GROUP) continue;
if (item.type == ElementType::GROUP)
{
auto sourceGroupId = item.id;
if (!groupRemap.contains(sourceGroupId)) groupRemap[sourceGroupId] = nextGroupId++;
item.id = groupRemap[sourceGroupId];
if (groupIds) groupIds->insert(item.id);
}
items.push_back(item);
}
if (items.empty())
{
if (errorString) *errorString = "No valid animation(s).";
return false;
}
int count{};
for (auto& item : items)
{
if (item.type == ElementType::ANIMATION)
{
if (auto mapped = groupRemap.find(item.groupId); mapped != groupRemap.end()) item.groupId = mapped->second;
indices.insert(start + count);
++count;
}
}
auto childIndex = animations_child_insert_index_get(*animations, start);
animations->children.insert(animations->children.begin() + childIndex, items.begin(), items.end());
return true;
}
void track_merge(Element& destination, const Element& source, types::merge::Type type)
{
switch (type)
{
case types::merge::APPEND:
destination.children.insert(destination.children.end(), source.children.begin(), source.children.end());
break;
case types::merge::PREPEND:
destination.children.insert(destination.children.begin(), source.children.begin(), source.children.end());
break;
case types::merge::REPLACE:
if (destination.children.size() < source.children.size()) destination.children.resize(source.children.size());
for (int i = 0; i < (int)source.children.size(); ++i)
destination.children[i] = source.children[i];
break;
case types::merge::IGNORE:
default:
break;
}
}
void animation_tracks_merge(Element& destination, const Element& source, ElementType containerType,
types::merge::Type type)
{
auto sourceTracks = child_first_get(source, containerType);
if (!sourceTracks) return;
auto destinationTracks = child_first_get(destination, containerType);
if (!destinationTracks)
{
destination.children.push_back(element_make(containerType));
destinationTracks = &destination.children.back();
}
std::unordered_map<int, int> groupRemap{};
std::set<int> matchedGroupIds{};
for (const auto& sourceGroup : sourceTracks->children)
{
if (sourceGroup.type != ElementType::GROUP) continue;
auto destinationGroup = std::find_if(destinationTracks->children.begin(), destinationTracks->children.end(),
[&](const Element& child)
{
return child.type == ElementType::GROUP &&
child.name == sourceGroup.name && !matchedGroupIds.contains(child.id);
});
if (destinationGroup == destinationTracks->children.end())
{
auto group = sourceGroup;
group.id = element_child_next_id_get(*destinationTracks, ElementType::GROUP);
destinationTracks->children.push_back(std::move(group));
destinationGroup = std::prev(destinationTracks->children.end());
}
else if (auto sourceRoot = child_first_get(sourceGroup, ElementType::ROOT_ANIMATION))
{
auto destinationRoot = child_first_get(*destinationGroup, ElementType::ROOT_ANIMATION);
if (!destinationRoot)
{
destinationGroup->children.push_back(root_animation_make());
destinationRoot = &destinationGroup->children.back();
}
track_merge(*destinationRoot, *sourceRoot, type);
}
groupRemap[sourceGroup.id] = destinationGroup->id;
matchedGroupIds.insert(destinationGroup->id);
}
for (const auto& sourceTrack : sourceTracks->children)
{
if (sourceTrack.type == ElementType::GROUP) continue;
auto mappedGroup = groupRemap.find(sourceTrack.groupId);
auto groupId = mappedGroup != groupRemap.end() ? mappedGroup->second : -1;
if (auto destinationTrack =
track_group_find(*destinationTracks, sourceTrack.type, track_id_get(sourceTrack), groupId))
track_merge(*destinationTrack, sourceTrack, type);
else
{
auto track = sourceTrack;
track.groupId = groupId;
destinationTracks->children.push_back(std::move(track));
}
}
}
int Anm2::animations_merge(int target, std::set<int>& sources, types::merge::Type type, bool isDeleteAfter)
{
auto animations = element_get(ElementType::ANIMATIONS);
auto targetAnimation = element_get(ElementType::ANIMATION, target);
if (!animations || !targetAnimation) return target;
if (!targetAnimation->name.ends_with(ANIMATION_MERGED_SUFFIX))
targetAnimation->name += std::string(ANIMATION_MERGED_SUFFIX);
for (auto index : sources)
{
if (index == target) continue;
auto source = element_get(ElementType::ANIMATION, index);
targetAnimation = element_get(ElementType::ANIMATION, target);
if (!source || !targetAnimation) continue;
if (auto sourceRoot = child_first_get(*source, ElementType::ROOT_ANIMATION))
{
auto targetRoot = child_first_get(*targetAnimation, ElementType::ROOT_ANIMATION);
if (!targetRoot)
{
targetAnimation->children.push_back(element_make(ElementType::ROOT_ANIMATION));
targetRoot = &targetAnimation->children.back();
}
track_merge(*targetRoot, *sourceRoot, type);
}
animation_tracks_merge(*targetAnimation, *source, ElementType::LAYER_ANIMATIONS, type);
animation_tracks_merge(*targetAnimation, *source, ElementType::NULL_ANIMATIONS, type);
if (auto sourceTriggers = child_first_get(*source, ElementType::TRIGGERS))
{
auto targetTriggers = child_first_get(*targetAnimation, ElementType::TRIGGERS);
if (!targetTriggers)
{
targetAnimation->children.push_back(element_make(ElementType::TRIGGERS));
targetTriggers = &targetAnimation->children.back();
}
track_merge(*targetTriggers, *sourceTriggers, type);
}
}
int finalIndex = target;
if (isDeleteAfter)
for (auto it = sources.rbegin(); it != sources.rend(); ++it)
{
auto source = *it;
auto sourceChildIndex = animations_child_index_get(*animations, source);
if (source == target || sourceChildIndex == -1) continue;
animations->children.erase(animations->children.begin() + sourceChildIndex);
if (source < finalIndex) --finalIndex;
}
if (auto finalAnimation = element_get(ElementType::ANIMATION, finalIndex))
finalAnimation->frameNum = animation_length_get(*finalAnimation);
return finalIndex;
}
}
+260
View File
@@ -0,0 +1,260 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
void shader_ids_repair(Element& root)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr;
if (!shaders) return;
std::set<int> usedIds{};
int nextId{};
for (auto& shader : shaders->children)
{
if (shader.type != ElementType::SHADER) continue;
while (usedIds.contains(nextId))
++nextId;
if (shader.id < 0 || usedIds.contains(shader.id)) shader.id = nextId++;
usedIds.insert(shader.id);
if (shader.name.empty()) shader.name = "New Shader";
}
}
void shader_frame_ids_repair(Element& root)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr;
auto animations = element_first_get(root, ElementType::ANIMATIONS);
if (!animations) return;
std::set<int> shaderIds{};
if (shaders)
for (const auto& shader : shaders->children)
if (shader.type == ElementType::SHADER) shaderIds.insert(shader.id);
auto frame_repair = [&](auto&& self, Element& element) -> void
{
if (element.type == ElementType::FRAME && element.shaderId != -1 && !shaderIds.contains(element.shaderId))
element.shaderId = -1;
for (auto& child : element.children)
self(self, child);
};
frame_repair(frame_repair, *animations);
}
void region_frame_ids_repair(Element& root)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr;
auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr;
auto animations = element_first_get(root, ElementType::ANIMATIONS);
if (!layers || !spritesheets || !animations) return;
for (auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](Element& layerAnimation)
{
auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId);
auto spritesheet =
layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr;
if (!spritesheet) return;
for (auto& frame : layerAnimation.children)
{
if (frame.type != ElementType::FRAME) continue;
auto frameCrop = glm::ivec2(frame.crop);
auto frameSize = glm::ivec2(frame.size);
auto framePivot = glm::ivec2(frame.pivot);
auto is_region_match = [&](const Element& region)
{
return region.type == ElementType::REGION && glm::ivec2(region.crop) == frameCrop &&
glm::ivec2(region.size) == frameSize && glm::ivec2(region.pivot) == framePivot;
};
auto region = frame.regionId == -1
? nullptr
: child_id_get(*spritesheet, ElementType::REGION, frame.regionId);
if (region && is_region_match(*region)) continue;
for (const auto& candidate : spritesheet->children)
if (is_region_match(candidate))
{
frame.regionId = candidate.id;
break;
}
}
});
}
}
void region_ids_remap(Element& root)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr;
auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr;
auto animations = element_first_get(root, ElementType::ANIMATIONS);
if (!spritesheets) return;
std::unordered_map<int, std::unordered_map<int, int>> remaps{};
for (auto& spritesheet : spritesheets->children)
{
if (spritesheet.type != ElementType::SPRITESHEET) continue;
std::unordered_map<int, int> remap{};
int nextId{};
for (auto& region : spritesheet.children)
{
if (region.type != ElementType::REGION) continue;
remap[region.id] = nextId;
region.id = nextId++;
}
if (!remap.empty()) remaps[spritesheet.id] = std::move(remap);
}
if (!layers || !animations || remaps.empty()) return;
std::unordered_map<int, int> layerSpritesheets{};
for (const auto& layer : layers->children)
if (layer.type == ElementType::LAYER_ELEMENT) layerSpritesheets[layer.id] = layer.spritesheetId;
for (auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](Element& layerAnimation)
{
auto layer = layerSpritesheets.find(layerAnimation.layerId);
if (layer == layerSpritesheets.end()) return;
auto remap = remaps.find(layer->second);
if (remap == remaps.end()) return;
for (auto& frame : layerAnimation.children)
{
if (frame.type != ElementType::FRAME || frame.regionId == -1) continue;
if (auto it = remap->second.find(frame.regionId); it != remap->second.end())
frame.regionId = it->second;
else
frame.regionId = -1;
}
});
}
}
void shader_ids_remap(Element& root)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr;
std::unordered_map<int, int> remap{};
int nextId{};
if (shaders)
for (auto& shader : shaders->children)
{
if (shader.type != ElementType::SHADER) continue;
remap[shader.id] = nextId;
shader.id = nextId++;
}
auto frame_remap = [&](auto&& self, Element& element) -> void
{
if (element.type == ElementType::FRAME && element.shaderId != -1)
{
if (auto it = remap.find(element.shaderId); it != remap.end())
element.shaderId = it->second;
else
element.shaderId = -1;
}
for (auto& child : element.children)
self(self, child);
};
frame_remap(frame_remap, root);
}
void Anm2::region_frames_sync(bool isClearInvalid)
{
auto content = child_first_get(root, ElementType::CONTENT);
auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr;
auto spritesheets = content ? child_first_get(*content, ElementType::SPRITESHEETS) : nullptr;
auto animations = element_first_get(root, ElementType::ANIMATIONS);
if (!layers || !spritesheets || !animations) return;
for (auto& animation : animations->children)
{
if (animation.type != ElementType::ANIMATION) continue;
auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS);
if (!layerAnimations) continue;
tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION,
[&](Element& layerAnimation)
{
auto layer = child_id_get(*layers, ElementType::LAYER_ELEMENT, layerAnimation.layerId);
auto spritesheet =
layer ? child_id_get(*spritesheets, ElementType::SPRITESHEET, layer->spritesheetId) : nullptr;
if (!spritesheet) return;
for (auto& frame : layerAnimation.children)
{
if (frame.type != ElementType::FRAME || frame.regionId == -1) continue;
auto region = child_id_get(*spritesheet, ElementType::REGION, frame.regionId);
if (!region)
{
if (isClearInvalid) frame.regionId = -1;
continue;
}
frame.crop = region->crop;
frame.size = region->size;
frame.pivot = region->pivot;
}
});
}
}
Anm2 Anm2::normalized_for_serialize(Flags flags) const
{
auto normalized = *this;
source_document_erase(normalized.root);
group_frames_restore(normalized.root);
groups_flatten(normalized.root);
if (has_flag(flags, SERIALIZE_BAKE_GROUP_FRAMES)) group_frames_bake(normalized.root);
if (has_flag(flags, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES))
all_interpolated_frames_bake(normalized.root, FRAME_DURATION_MIN, false, false);
region_ids_remap(normalized.root);
shader_ids_remap(normalized.root);
if (has_flag(flags, SERIALIZE_GROUPS) && has_flag(flags, SERIALIZE_NESTED_GROUPS))
groups_nest(normalized.root);
else
group_metadata_extract(normalized.root, flags);
auto content = child_first_get(normalized.root, ElementType::CONTENT);
if (content) std::erase_if(content->children, [](const Element& element) { return element.tag == "Groups"; });
if (auto layers = content ? child_first_get(*content, ElementType::LAYERS) : nullptr)
{
std::unordered_map<int, int> remap{};
int nextId{};
for (auto& layer : layers->children)
{
if (layer.type != ElementType::LAYER_ELEMENT) continue;
remap[layer.id] = nextId;
layer.id = nextId++;
}
layer_animation_ids_remap(normalized.root, remap);
}
return normalized;
}
}
+618
View File
@@ -0,0 +1,618 @@
#include "internal.hpp"
using namespace anm2ed::util;
using namespace tinyxml2;
namespace anm2ed
{
#define ANM2_STRING_ATTRIBUTES \
X("Name", name) \
X("CreatedBy", createdBy) \
X("CreatedOn", createdOn) \
X("Binding", binding) \
X("Value", value) \
X("DefaultAnimation", defaultAnimation)
#define ANM2_PATH_ATTRIBUTES \
X("Path", path) \
X("Vertex", vertex) \
X("Fragment", fragment)
#define ANM2_INT_ATTRIBUTES \
X("Id", id) \
X("LayerId", layerId) \
X("NullId", nullId) \
X("SpritesheetId", spritesheetId) \
X("Fps", fps) \
X("Version", version) \
X("FrameNum", frameNum) \
X("Delay", duration) \
X("AtFrame", atFrame) \
X("EventId", eventId) \
X("RegionId", regionId) \
X("ShaderId", shaderId) \
X("SoundId", soundId) \
X("GroupId", groupId) \
X("Index", index)
#define ANM2_BOOL_ATTRIBUTES \
X("Loop", isLoop) \
X("Visible", isVisible) \
X("ShowRect", isShowRect) \
X("IsExpanded", isExpanded) \
X("Enabled", isEnabled)
#define ANM2_FLOAT_ATTRIBUTES \
X("Rotation", rotation) \
X("XPivot", pivot.x) \
X("YPivot", pivot.y) \
X("XCrop", crop.x) \
X("YCrop", crop.y) \
X("XPosition", position.x) \
X("YPosition", position.y) \
X("Width", size.x) \
X("Height", size.y) \
X("XScale", scale.x) \
X("YScale", scale.y) \
X("ShearX", shear.x) \
X("ShearY", shear.y)
#define ANM2_COLOR_ATTRIBUTES \
X("RedTint", tint.r) \
X("GreenTint", tint.g) \
X("BlueTint", tint.b) \
X("AlphaTint", tint.a) \
X("RedOffset", colorOffset.r) \
X("GreenOffset", colorOffset.g) \
X("BlueOffset", colorOffset.b)
constexpr std::string_view LEGACY_OVERLAY_TAG = "Overlay";
bool string_query(const XMLElement* element, const char* name, std::string& out)
{
if (!element) return false;
if (auto value = element->Attribute(name); value)
{
out = value;
return true;
}
return false;
}
bool path_query(const XMLElement* element, const char* name, std::filesystem::path& out)
{
std::string value{};
if (!string_query(element, name, value)) return false;
out = path::from_utf8(value);
return true;
}
void path_set(XMLElement* element, const char* name, const std::filesystem::path& value)
{
if (!element || value.empty()) return;
auto valueUtf8 = path::to_utf8(value);
element->SetAttribute(name, valueUtf8.c_str());
}
float color_read(const XMLElement* element, const char* name, float fallback)
{
int value{};
if (!element || element->QueryIntAttribute(name, &value) != XML_SUCCESS) return fallback;
return math::uint8_to_float(value);
}
int color_write(float value) { return math::float_to_uint8(value); }
Interpolation interpolation_read(const XMLElement* element, const char* attribute)
{
bool isFallback{};
if (element) element->QueryBoolAttribute(attribute, &isFallback);
auto value = element ? element->Attribute(attribute) : nullptr;
if (!value) return Interpolation::NONE;
for (std::size_t i = 0; i < INTERPOLATION_VALUES.size(); ++i)
if (!INTERPOLATION_VALUES[i].empty() && INTERPOLATION_VALUES[i] == value) return (Interpolation)i;
return isFallback ? Interpolation::LINEAR : Interpolation::NONE;
}
Interpolation interpolation_read(const XMLElement* element) { return interpolation_read(element, "Interpolated"); }
void interpolation_write(XMLElement* element, Interpolation interpolation)
{
if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR)
{
element->SetAttribute("Interpolated", interpolation == Interpolation::LINEAR);
return;
}
auto value = INTERPOLATION_VALUES[(std::size_t)interpolation];
if (!value.empty()) element->SetAttribute("Interpolated", value.data());
}
Origin origin_read(const XMLElement* element)
{
auto value = element ? element->Attribute("Origin") : nullptr;
if (!value) return Origin::CUSTOM;
for (std::size_t i = 0; i < ORIGIN_VALUES.size(); ++i)
if (!ORIGIN_VALUES[i].empty() && ORIGIN_VALUES[i] == value) return (Origin)i;
return Origin::CUSTOM;
}
void origin_write(XMLElement* out, const Element& element)
{
auto origin = ORIGIN_VALUES[(std::size_t)element.origin];
if (!origin.empty())
{
out->SetAttribute("Origin", origin.data());
return;
}
out->SetAttribute("XPivot", element.pivot.x);
out->SetAttribute("YPivot", element.pivot.y);
}
void element_attributes_read(Element& out, const XMLElement* element)
{
#define X(attribute, member) string_query(element, attribute, out.member);
ANM2_STRING_ATTRIBUTES
#undef X
#define X(attribute, member) path_query(element, attribute, out.member);
ANM2_PATH_ATTRIBUTES
#undef X
#define X(attribute, member) element->QueryIntAttribute(attribute, &out.member);
ANM2_INT_ATTRIBUTES
#undef X
#define X(attribute, member) element->QueryBoolAttribute(attribute, &out.member);
ANM2_BOOL_ATTRIBUTES
#undef X
#define X(attribute, member) element->QueryFloatAttribute(attribute, &out.member);
ANM2_FLOAT_ATTRIBUTES
#undef X
#define X(attribute, member) out.member = color_read(element, attribute, out.member);
ANM2_COLOR_ATTRIBUTES
#undef X
out.interpolation = interpolation_read(element);
out.origin = origin_read(element);
if (out.type == ElementType::REGION && out.origin == Origin::TOP_LEFT) out.pivot = {};
if (out.type == ElementType::REGION && out.origin == Origin::CENTER) out.pivot = out.size * 0.5f;
}
bool bake_attributes_read(const XMLElement* element, Interpolation& interpolation, int& bakeDelay)
{
if (!element || !element->Attribute("BakeInterpolation")) return false;
interpolation = interpolation_read(element, "BakeInterpolation");
element->QueryIntAttribute("BakeDelay", &bakeDelay);
return bakeDelay >= FRAME_DURATION_MIN;
}
const XMLElement* bake_frames_skip(const XMLElement* element, int bakeDelay)
{
for (int i = 0; element && i < bakeDelay; ++i)
element = element->NextSiblingElement();
return element;
}
void element_children_read(Element& out, const XMLElement* element)
{
auto child = element->FirstChildElement();
while (child)
{
auto childName = std::string_view(child->Name() ? child->Name() : "");
if (childName == LEGACY_OVERLAY_TAG)
{
child = child->NextSiblingElement();
continue;
}
auto childType = element_type_get(childName);
if (childType == ElementType::FRAME && is_track(out))
{
Interpolation bakeInterpolation{};
int bakeDelay{};
if (bake_attributes_read(child, bakeInterpolation, bakeDelay))
{
auto restored = element_read(child);
restored.interpolation = bakeInterpolation;
restored.duration = bakeDelay;
if (is_track_child_valid(out.type, restored.type)) out.children.push_back(std::move(restored));
child = bake_frames_skip(child, bakeDelay);
continue;
}
}
auto childElement = element_read(child);
if (is_track_child_valid(out.type, childElement.type)) out.children.push_back(std::move(childElement));
child = child->NextSiblingElement();
}
}
Element element_read(const XMLElement* element)
{
Element out{};
if (!element) return out;
out.tag = element->Name() ? element->Name() : "";
out.type = element_type_get(out.tag);
element_attributes_read(out, element);
element_children_read(out, element);
if (out.type == ElementType::TRIGGER && out.soundId != -1)
{
bool isSoundFound{};
for (const auto& child : out.children)
if (child.type == ElementType::SOUND_ELEMENT && child.id == out.soundId) isSoundFound = true;
if (!isSoundFound)
{
auto sound = element_make(ElementType::SOUND_ELEMENT);
sound.id = out.soundId;
out.children.insert(out.children.begin(), sound);
}
}
if (out.type == ElementType::TRIGGER)
for (const auto& child : out.children)
if (child.type == ElementType::SOUND_ELEMENT && child.id != -1) out.soundIds.push_back(child.id);
return out;
}
bool is_nested_group_parent(ElementType parentType, Flags flags)
{
return has_flag(flags, SERIALIZE_NESTED_GROUPS) &&
(parentType == ElementType::ANIMATIONS || parentType == ElementType::LAYER_ANIMATIONS ||
parentType == ElementType::NULL_ANIMATIONS);
}
bool is_group_id_serialized(Flags flags)
{
return has_flag(flags, SERIALIZE_GROUPS) && !has_flag(flags, SERIALIZE_NESTED_GROUPS);
}
bool element_write_skip(const Element& element, ElementType parentType, Flags flags)
{
if (!is_track_child_valid(parentType, element.type)) return true;
if ((element.type == ElementType::SHADERS || element.type == ElementType::SHADER ||
element.type == ElementType::UNIFORM || element.type == ElementType::COMPONENT) &&
!has_flag(flags, SERIALIZE_EXTENSIONS))
return true;
if (element.type == ElementType::SHADERS && element.children.empty()) return true;
if (element.type == ElementType::SOUNDS && (!has_flag(flags, SERIALIZE_SOUNDS) || element.children.empty()))
return true;
if ((element.type == ElementType::LAYER_ANIMATION_GROUPS || element.type == ElementType::NULL_ANIMATION_GROUPS) &&
(!has_flag(flags, SERIALIZE_GROUPS) || element.children.empty()))
return true;
if (element.type == ElementType::SOUND_ELEMENT && parentType == ElementType::TRIGGER) return true;
if (element.type == ElementType::REGION && !has_flag(flags, SERIALIZE_REGIONS)) return true;
if (element.type == ElementType::GROUP && !has_flag(flags, SERIALIZE_GROUPS)) return true;
return false;
}
void frame_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags)
{
if (parentType == ElementType::LAYER_ANIMATION)
{
bool isHasValidRegion = has_flag(flags, SERIALIZE_REGIONS) && element.regionId != -1;
bool isWriteRegionValues = has_flag(flags, SERIALIZE_REDUNDANT_FRAME_REGION_VALUES) || !isHasValidRegion;
if (isHasValidRegion) out->SetAttribute("RegionId", element.regionId);
if (isWriteRegionValues)
{
out->SetAttribute("XPivot", element.pivot.x);
out->SetAttribute("YPivot", element.pivot.y);
out->SetAttribute("XCrop", element.crop.x);
out->SetAttribute("YCrop", element.crop.y);
out->SetAttribute("Width", element.size.x);
out->SetAttribute("Height", element.size.y);
}
}
out->SetAttribute("XPosition", element.position.x);
out->SetAttribute("YPosition", element.position.y);
out->SetAttribute("Delay", element.duration);
out->SetAttribute("Visible", element.isVisible);
out->SetAttribute("XScale", element.scale.x);
out->SetAttribute("YScale", element.scale.y);
if (has_flag(flags, SERIALIZE_EXTENSIONS))
{
out->SetAttribute("ShearX", element.shear.x);
out->SetAttribute("ShearY", element.shear.y);
}
out->SetAttribute("RedTint", color_write(element.tint.r));
out->SetAttribute("GreenTint", color_write(element.tint.g));
out->SetAttribute("BlueTint", color_write(element.tint.b));
out->SetAttribute("AlphaTint", color_write(element.tint.a));
out->SetAttribute("RedOffset", color_write(element.colorOffset.r));
out->SetAttribute("GreenOffset", color_write(element.colorOffset.g));
out->SetAttribute("BlueOffset", color_write(element.colorOffset.b));
out->SetAttribute("Rotation", element.rotation);
interpolation_write(out, element.interpolation);
if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1)
out->SetAttribute("ShaderId", element.shaderId);
}
void element_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags)
{
if (element.type == ElementType::INFO)
{
out->SetAttribute("CreatedBy", element.createdBy.c_str());
out->SetAttribute("CreatedOn", element.createdOn.c_str());
out->SetAttribute("Fps", element.fps);
out->SetAttribute("Version", element.version);
}
else if (element.type == ElementType::ANIMATIONS)
out->SetAttribute("DefaultAnimation", element.defaultAnimation.c_str());
else if (element.type == ElementType::SPRITESHEET)
{
out->SetAttribute("Id", element.id);
path_set(out, "Path", element.path);
}
else if (element.type == ElementType::SHADER)
{
out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
path_set(out, "Vertex", element.vertex);
path_set(out, "Fragment", element.fragment);
}
else if (element.type == ElementType::UNIFORM)
{
out->SetAttribute("Name", element.name.c_str());
if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str());
if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str());
}
else if (element.type == ElementType::COMPONENT)
{
out->SetAttribute("Index", element.index);
if (!element.binding.empty()) out->SetAttribute("Binding", element.binding.c_str());
if (!element.value.empty()) out->SetAttribute("Value", element.value.c_str());
}
else if (element.type == ElementType::REGION)
{
out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
out->SetAttribute("XCrop", element.crop.x);
out->SetAttribute("YCrop", element.crop.y);
out->SetAttribute("Width", element.size.x);
out->SetAttribute("Height", element.size.y);
origin_write(out, element);
}
else if (element.type == ElementType::LAYER_ELEMENT)
{
out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
out->SetAttribute("SpritesheetId", element.spritesheetId);
}
else if (element.type == ElementType::NULL_ELEMENT)
{
out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
if (element.isShowRect) out->SetAttribute("ShowRect", element.isShowRect);
}
else if (element.type == ElementType::GROUP)
{
if (!is_nested_group_parent(parentType, flags)) out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
out->SetAttribute("IsExpanded", element.isExpanded);
out->SetAttribute("Visible", element.isVisible);
if ((parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) &&
element.index != -1)
out->SetAttribute("Index", element.index);
}
else if (element.type == ElementType::EVENT_ELEMENT)
{
out->SetAttribute("Id", element.id);
out->SetAttribute("Name", element.name.c_str());
}
else if (element.type == ElementType::SOUND_ELEMENT)
{
out->SetAttribute("Id", element.id);
if (parentType != ElementType::TRIGGER) path_set(out, "Path", element.path);
}
else if (element.type == ElementType::ANIMATION)
{
out->SetAttribute("Name", element.name.c_str());
out->SetAttribute("FrameNum", element.frameNum);
out->SetAttribute("Loop", element.isLoop);
if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId);
}
else if (element.type == ElementType::LAYER_ANIMATION)
{
out->SetAttribute("LayerId", element.layerId);
out->SetAttribute("Visible", element.isVisible);
if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId);
}
else if (element.type == ElementType::NULL_ANIMATION)
{
out->SetAttribute("NullId", element.nullId);
out->SetAttribute("Visible", element.isVisible);
if (element.groupId != -1 && is_group_id_serialized(flags)) out->SetAttribute("GroupId", element.groupId);
}
else if (element.type == ElementType::FRAME)
frame_attributes_write(out, element, parentType, flags);
else if (element.type == ElementType::TRIGGER)
{
if (element.eventId != -1) out->SetAttribute("EventId", element.eventId);
out->SetAttribute("AtFrame", element.atFrame);
}
}
void bake_attributes_write(XMLElement* out, Interpolation interpolation, int bakeDelay)
{
auto value = INTERPOLATION_VALUES[(std::size_t)interpolation];
if (!value.empty()) out->SetAttribute("BakeInterpolation", value.data());
out->SetAttribute("BakeDelay", bakeDelay);
}
bool is_frame_bake_serialized(const Element& frame, Flags flags)
{
return has_flag(flags, SERIALIZE_BAKE_SPECIAL_INTERPOLATED_FRAMES) && frame.type == ElementType::FRAME &&
frame.interpolation != Interpolation::NONE && frame.interpolation != Interpolation::LINEAR;
}
void baked_frames_insert(XMLDocument& document, XMLElement* out, const Element& track, int index, Flags flags)
{
const auto& original = track.children[index];
auto nextFrame = index + 1 < (int)track.children.size() && track.children[index + 1].type == ElementType::FRAME
? track.children[index + 1]
: original;
auto bakeDelay = std::max(original.duration, FRAME_DURATION_MIN);
for (int bakeIndex = 0; bakeIndex < bakeDelay; ++bakeIndex)
{
auto baked = original;
auto amount = interpolation_factor(original.interpolation, (float)bakeIndex / (float)bakeDelay);
baked.duration = FRAME_DURATION_MIN;
baked.interpolation = Interpolation::NONE;
baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount);
baked.position = glm::mix(original.position, nextFrame.position, amount);
baked.scale = glm::mix(original.scale, nextFrame.scale, amount);
baked.shear = glm::mix(original.shear, nextFrame.shear, amount);
baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount);
baked.tint = glm::mix(original.tint, nextFrame.tint, amount);
auto frame = element_to_xml(document, baked, track.type, flags);
if (bakeIndex == 0) bake_attributes_write(frame, original.interpolation, bakeDelay);
out->InsertEndChild(frame);
}
}
void trigger_sounds_xml_insert(XMLDocument& document, XMLElement* out, const Element& element, Flags flags)
{
if (element.type != ElementType::TRIGGER || !has_flag(flags, SERIALIZE_SOUNDS)) return;
for (auto soundId : element.soundIds)
{
if (soundId == -1) continue;
auto sound = document.NewElement(element_tag_get(ElementType::SOUND_ELEMENT).data());
sound->SetAttribute("Id", soundId);
out->InsertEndChild(sound);
}
}
XMLElement* element_to_xml(XMLDocument& document, const Element& element, ElementType parentType, Flags flags)
{
auto tag = element.type == ElementType::UNKNOWN ? std::string_view(element.tag) : element_tag_get(element.type);
auto out = document.NewElement(tag.empty() ? element.tag.c_str() : tag.data());
element_attributes_write(out, element, parentType, flags);
trigger_sounds_xml_insert(document, out, element, flags);
for (int i = 0; i < (int)element.children.size(); ++i)
{
const auto& child = element.children[i];
if (element_write_skip(child, element.type, flags)) continue;
if (is_track(element) && is_frame_bake_serialized(child, flags))
baked_frames_insert(document, out, element, i, flags);
else
out->InsertEndChild(element_to_xml(document, child, element.type, flags));
}
return out;
}
XMLElement* element_to_xml(XMLDocument& document, const Element& element, Flags flags)
{
return element_to_xml(document, element, ElementType::UNKNOWN, flags);
}
std::string element_to_string(const Element& element, ElementType parentType, Flags flags)
{
XMLDocument document{};
document.InsertEndChild(element_to_xml(document, element, parentType, flags));
return xml::document_to_string(document);
}
std::string element_to_string(const Element& element, Flags flags)
{
return element_to_string(element, ElementType::UNKNOWN, flags);
}
bool Anm2::deserialize(ElementType type, const std::string& string, bool isAppend, std::string* errorString,
const std::filesystem::path& directory)
{
XMLDocument document{};
if (document.Parse(string.c_str()) != XML_SUCCESS)
{
if (errorString) *errorString = document.ErrorStr();
return false;
}
auto tag = element_tag_get(type);
if (tag.empty() || !document.FirstChildElement(tag.data()))
{
if (errorString) *errorString = std::format("No valid {}(s).", tag);
return false;
}
auto containerType = element_container_type_get(type);
auto container = element_get(containerType);
if (!container)
{
if (errorString) *errorString = std::format("No {} container.", element_tag_get(containerType));
return false;
}
std::optional<WorkingDirectory> workingDirectory{};
if ((type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET) && !directory.empty())
workingDirectory.emplace(directory);
for (auto xmlElement = document.FirstChildElement(tag.data()); xmlElement;
xmlElement = xmlElement->NextSiblingElement(tag.data()))
{
auto element = element_read(xmlElement);
if (element.type != type) continue;
if (isAppend)
element.id = element_child_next_id_get(*container, type);
else
element_child_id_erase(*container, type, element.id);
if (type == ElementType::SOUND_ELEMENT || type == ElementType::SPRITESHEET)
element.path = path::backslash_handle(element.path);
container->children.push_back(element);
}
return true;
}
bool Anm2::regions_deserialize(int spritesheetId, const std::string& string, bool isAppend, std::string* errorString)
{
XMLDocument document{};
if (document.Parse(string.c_str()) != XML_SUCCESS)
{
if (errorString) *errorString = document.ErrorStr();
return false;
}
if (!document.FirstChildElement("Region"))
{
if (errorString) *errorString = "No valid region(s).";
return false;
}
auto spritesheet = element_get(ElementType::SPRITESHEET, spritesheetId);
if (!spritesheet)
{
if (errorString) *errorString = "No spritesheet.";
return false;
}
for (auto element = document.FirstChildElement("Region"); element; element = element->NextSiblingElement("Region"))
{
auto region = element_read(element);
if (region.type != ElementType::REGION) continue;
if (isAppend)
region.id = element_child_next_id_get(*spritesheet, ElementType::REGION);
else
element_child_id_erase(*spritesheet, ElementType::REGION, region.id);
spritesheet->children.push_back(region);
}
return true;
}
}
+1 -1
View File
@@ -8,7 +8,7 @@
#include "window/onionskin.hpp"
#include "window/shaders.hpp"
#include "window/spritesheet_editor.hpp"
#include "window/timeline.hpp"
#include "window/timeline/timeline.hpp"
#include "window/tools.hpp"
#include "window/welcome.hpp"
#include "window/window.hpp"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+355
View File
@@ -0,0 +1,355 @@
#pragma once
#include "timeline.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <format>
#include <functional>
#include <map>
#include <optional>
#include <set>
#include <imgui_internal.h>
#include "actions.hpp"
#include "log.hpp"
#include "math.hpp"
#include "toast.hpp"
#include "util/imgui/draw.hpp"
#include "util/imgui/input.hpp"
#include "util/imgui/layout.hpp"
#include "util/imgui/shortcut.hpp"
#include "util/imgui/tooltip.hpp"
#include "vector.hpp"
using namespace anm2ed::resource;
using namespace anm2ed::types;
using namespace anm2ed::util;
using namespace glm;
namespace anm2ed::imgui
{
constexpr auto WIDTH_MULTIPLIER = 1.25f;
constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f);
constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f);
constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f);
constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f);
constexpr auto FRAME_BORDER_COLOR_REFERENCED_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.60f);
constexpr auto FRAME_BORDER_THICKNESS = 1.0f;
constexpr auto FRAME_BORDER_THICKNESS_REFERENCED = 2.0f;
constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.05f);
constexpr auto FRAME_MULTIPLE_OVERLAY_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.1f);
constexpr auto FRAME_ROUNDING = 3.0f;
constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(color::WHITE);
constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f);
constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(color::WHITE);
constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f);
constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f;
constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(color::WHITE);
constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f);
constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f);
constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_LIGHT = ImVec4(0.8353f, 0.8353f, 0.7294f, 1.0f);
constexpr auto TIMELINE_TICK_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
constexpr auto TIMELINE_CHILD_BG_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f);
constexpr auto TIMELINE_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
enum class DropZone
{
BEFORE,
INSIDE,
AFTER
};
constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f},
{0.5216f, 0.7333f, 1.0f, 1.0f},
{1.0f, 0.9961f, 0.5882f, 1.0f},
{0.6157f, 1.0f, 0.5882f, 1.0f},
{1.0f, 0.5882f, 0.8314f, 1.0f}};
constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.0980f, 0.3765f, 0.6431f, 1.0f},
{1.0f, 0.5255f, 0.3333f, 1.0f},
{0.3686f, 0.5765f, 0.2353f, 1.0f},
{0.6118f, 0.2039f, 0.2745f, 1.0f}};
constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f},
{0.0752f, 0.2887f, 0.4931f, 1.0f},
{0.85f, 0.4467f, 0.2833f, 1.0f},
{0.2727f, 0.4265f, 0.1741f, 1.0f},
{0.4618f, 0.1539f, 0.2072f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f},
{0.3333f, 0.5725f, 0.8392f, 1.0f},
{1.0f, 0.5412f, 0.3412f, 1.0f},
{0.5255f, 0.8471f, 0.4588f, 1.0f},
{0.7961f, 0.3882f, 0.5412f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f},
{0.3733f, 0.6125f, 0.8792f, 1.0f},
{0.9106f, 0.4949f, 0.2753f, 1.0f},
{0.5655f, 0.8871f, 0.4988f, 1.0f},
{0.8361f, 0.4282f, 0.5812f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.2039f, 0.4549f, 0.7176f, 1.0f},
{0.8745f, 0.4392f, 0.2275f, 1.0f},
{0.3765f, 0.6784f, 0.2980f, 1.0f},
{0.6353f, 0.2235f, 0.3647f, 1.0f}};
constexpr auto FRAME_MULTIPLE = 5;
constexpr auto FRAME_TOOLTIP_HOVER_DELAY = 0.75f;
constexpr auto DRAG_DROP_SOURCE_FLAGS =
ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers;
#define ITEM_CHILD_WIDTH ImGui::GetTextLineHeightWithSpacing() * 12.5
struct TimelineItemRow
{
int type{NONE};
int id{-1};
int index{-1};
int groupId{-1};
int rootGroupType{NONE};
int rootGroupId{-1};
int depth{};
bool isGroup{};
};
struct RootFrameSpan
{
int start{};
int end{};
};
struct TimelineContext
{
Timeline& timeline;
bool& isDragging;
bool& isWindowHovered;
bool& isHorizontalScroll;
popup::ItemProperties& itemProperties;
PopupHelper& bakePopup;
PopupHelper& bakeIntoOtherFramesPopup;
PopupHelper& makeManyRegionsPopup;
BakeIntoOtherFramesTarget& bakeIntoOtherFramesTarget;
bool& isBakeIntoOtherFramesLayers;
bool& isBakeIntoOtherFramesNulls;
bool& isMakeManyRegionsMapFrames;
std::set<Reference>& makeManyRegionReferences;
int& hoveredTime;
bool& isFrameBoxPending;
bool& isFrameBoxSelecting;
bool& isFrameBoxAdditive;
ImVec2& frameBoxStart;
ImVec2& frameBoxEnd;
std::set<Reference>& frameBoxSelection;
TimelineRowReference& rowSelectionAnchor;
bool& isRowSelectionAnchorSet;
PopupHelper& groupPropertiesPopup;
std::string& groupName;
int& groupAnimationIndex;
int& groupType;
int& groupId;
Reference& draggedFrameReference;
bool& isDraggedFrameActive;
int& draggedFrameType;
int& draggedFrameIndex;
int& draggedFrameStart;
int& draggedFrameStartDuration;
std::vector<FrameDurationDrag>& draggedFrameStartDurations;
float& draggedFrameStartMouseX;
float& draggedFrameWidth;
bool& isDraggedFrameSnapshot;
bool& frameFocusRequested;
int& frameFocusIndex;
FrameMoveDrag& frameMoveDrag;
std::vector<int>& frameSelectionSnapshot;
std::vector<int>& frameSelectionLocked;
bool& isFrameSelectionLocked;
Reference& frameSelectionSnapshotReference;
Reference& frameSelectionAnchor;
bool& isFrameSelectionAnchorSet;
int& animationLengthEditIndex;
std::vector<TimelineRowReference>& rowDragReferences;
glm::vec2& scroll;
ImGuiStyle& style;
Manager& manager;
Settings& settings;
Resources& resources;
Clipboard& clipboard;
Document& document;
Anm2& anm2;
Playback& playback;
Reference& reference;
Storage& frames;
Storage& region;
Element* animation{};
float rowFrameChildHeight{};
bool isLightTheme{};
bool isTextPushed{};
ImVec4 iconTintDefault{};
ImVec4 itemIconTint{};
ImVec4 frameBorderColor{};
ImVec4 frameBorderColorReferenced{};
ImVec4 frameMultipleOverlayColor{};
ImVec4 textMultipleColor{};
ImVec4 playheadLineColor{};
ImVec4 playheadIconTint{};
ImVec4 timelineBackgroundColor{};
ImVec4 timelinePlayheadRectColor{};
ImVec4 timelineTickColor{};
ImVec4 itemTextColor{};
std::optional<int> frameSplitTimeAtCursor{};
int frameMoveDropType{NONE};
int frameMoveDropItemID{-1};
int frameMoveDropGroupType{NONE};
int frameMoveDropGroupId{-1};
int frameMoveDropIndex{-1};
bool isFrameMoveDropTarget{};
float playheadLineCenterX{};
float playheadLineTopY{};
bool isPlayheadLineSet{};
ImVec2 frameBoxClipMin{};
ImVec2 frameBoxClipMax{};
bool isFrameBoxClipSet{};
std::function<int(int)> type_index{};
std::function<ItemType(int)> item_type_get{};
std::function<Element*(int, int, int, int)> item_get{};
std::function<Element*()> frame_get{};
std::function<Element*()> selected_item_get{};
std::function<ElementType(const Element&)> item_frame_type_get{};
std::function<int(const Element*)> item_frames_count{};
std::function<int(const Element&, int)> item_frame_child_index_get{};
std::function<int(const Element&, int)> item_frame_insert_index_get{};
std::function<Element*(int)> layer_get{};
std::function<Element*(int)> null_get{};
std::function<Element*(int)> spritesheet_get{};
std::function<Element*()> info_get{};
std::function<ElementType(int)> container_type_get{};
std::function<ElementType(int)> track_type_get{};
std::function<int(const Element&, int)> track_id_get{};
std::function<Element*(int)> track_container_get{};
std::function<Element*(int, int)> track_group_get{};
std::function<bool(int, int)> is_track_group_visible{};
std::function<Element*(const TimelineItemRow&)> row_group_get{};
std::function<int(int, int)> group_items_count_get{};
std::function<Element*(Document&, int)> command_animation_get{};
std::function<Element*(Document&, int, int, int, int, int)> command_item_get{};
std::function<Element*(Document&, Reference)> command_item_reference_get{};
std::function<Element*(Document&, const Reference&)> command_frame_get{};
std::function<Element*(Document&, int)> command_layer_get{};
std::function<Element*(Document&, int)> command_spritesheet_get{};
std::function<Element*(Document&)> command_info_get{};
std::function<Reference(int, int, int, int)> item_reference_get{};
std::function<Reference(Reference)> item_reference_from_frame_get{};
std::function<bool(const Reference&, const Reference&)> is_same_item{};
std::function<bool(Document&, const Reference&)> is_frame_reference_valid_for{};
std::function<void(Document&)> group_selection_reset_for{};
std::function<std::set<Reference>()> frame_references_for_current_get{};
std::function<std::set<Reference>()> item_references_for_current_get{};
std::function<void(Document&)> frames_selection_sync_for{};
std::function<void(Document&, Reference)> item_selection_set_for{};
std::function<void(Document&, Reference)> frame_selection_set_for{};
std::function<void(Document&, Reference)> frame_selection_toggle_for{};
std::function<bool(Document&, Reference, Reference, bool)> frame_selection_range_set_for{};
std::function<std::set<Reference>()> all_frame_references_for_items_get{};
std::function<bool(const Reference&)> is_frame_copy_item{};
std::function<std::set<Reference>()> copy_frame_references_get{};
std::function<void(Document&)> frames_selection_reset_for{};
std::function<void(Document&)> frames_selection_set_reference_for{};
std::function<void(Document&)> frames_reference_normalize_for{};
std::function<void(Document&)> reference_clear_for{};
std::function<void(Document&, Reference)> reference_set_item_reference_for{};
std::function<void(Document&, Reference)> reference_set_timeline_item_reference_for{};
std::function<void(std::function<void(Manager&, Document&)>)> command_push{};
std::function<std::set<Reference>(std::set<Reference>)> track_references_from_frame_references_get{};
std::function<void(StringType, const std::set<Reference>&)> tracks_snapshot_command_push{};
std::function<void(StringType, const std::set<Reference>&)> frames_snapshot_command_push{};
std::function<void(StringType, Document::ChangeType, const std::set<Reference>&,
std::function<void(Manager&, Document&)>)>
frames_edit_command_push{};
std::function<void(StringType, Document::ChangeType, const std::set<Reference>&,
std::function<void(Manager&, Document&)>)>
tracks_edit_command_push{};
std::function<void(StringType, Document::ChangeType, std::function<void(Manager&, Document&)>)> edit_command_push{};
std::function<glm::vec4(int)> type_color_base_vec{};
std::function<glm::vec4(int)> type_color_active_vec{};
std::function<glm::vec4(int)> type_color_hovered_vec{};
std::function<glm::vec4(int)> item_color_vec{};
std::function<glm::vec4(int)> item_color_active_vec{};
std::function<void(GLuint, ImVec4, bool)> overlay_icon{};
std::function<void()> frames_selection_set_reference{};
std::function<void()> playback_stop{};
std::function<void()> frame_insert{};
std::function<void(Document&, std::set<Reference>)> frames_delete_for{};
std::function<void()> frames_delete_action{};
std::function<void()> frames_duplicate{};
std::function<bool(std::set<Reference>)> is_frames_reverse_available{};
std::function<void()> frames_reverse{};
std::function<void()> frames_bake{};
std::function<std::set<Reference>()> selected_root_frame_references_get{};
std::function<std::set<Reference>(const Document&, const Element&, BakeIntoOtherFramesTarget, bool, bool)>
item_references_for_bake_into_other_frames_get{};
std::function<bool()> is_bake_into_other_frames_ready{};
std::function<void(Element&, const Element&, bool, bool, bool)> frame_root_transform_apply{};
std::function<void()> bake_into_other_frames{};
std::function<void()> frame_split{};
std::function<void()> reference_clear{};
std::function<void(Reference)> reference_set_timeline_item_reference{};
std::function<std::vector<TimelineItemRow>()> timeline_item_rows_get{};
std::function<std::vector<Reference>()> timeline_item_references_get{};
std::function<Reference(const TimelineItemRow&)> group_reference_get{};
std::function<TimelineRowReference(const TimelineItemRow&)> row_reference_get{};
std::function<Reference(const TimelineRowReference&)> row_item_reference_get{};
std::function<std::vector<TimelineRowReference>()> timeline_row_references_get{};
std::function<bool(const TimelineItemRow&)> is_group_selected{};
std::function<bool(const TimelineItemRow&)> is_row_selected{};
std::function<void()> row_selection_clear{};
std::function<void(const TimelineRowReference&)> row_selection_insert{};
std::function<void(const TimelineRowReference&)> row_selection_erase{};
std::function<bool(const TimelineRowReference&)> is_row_reference_selected{};
std::function<std::size_t()> row_selection_count_get{};
std::function<void(const TimelineItemRow&)> row_selection_set{};
std::function<void(int)> reference_set_adjacent_item{};
std::function<std::vector<TimelineRowReference>()> selected_row_references_get{};
std::function<std::vector<TimelineRowReference>(const TimelineItemRow&)> row_drag_references_get{};
std::function<void()> item_remove{};
std::function<std::vector<Reference>()> item_references_groupable_get{};
std::function<void()> item_group{};
std::function<void(std::vector<TimelineRowReference>, TimelineItemRow, bool, bool)> rows_move_to_row{};
std::function<void()> fit_animation_length{};
std::function<void(const std::set<Reference>&)> frame_references_copy{};
std::function<void()> copy{};
std::function<void()> cut{};
std::function<void()> paste{};
std::function<void()> context_menu{};
std::function<void(int, int)> item_base_properties_open{};
std::function<void()> group_properties_close{};
std::function<void(const TimelineItemRow&, const Element&)> group_properties_open{};
std::function<void()> group_properties_update{};
std::function<void()> item_context_menu{};
TimelineContext(Timeline&, Manager&, Settings&, Resources&, Clipboard&);
void update();
void commands_bind();
void item_child(const TimelineItemRow&, int);
void items_child();
void frame_move_drag_clear();
void frames_move_to(int, int, int, int, int);
ImVec2 frame_box_content_point_get();
ImVec2 frame_box_screen_point_get(ImVec2);
bool is_frame_box_overlapping(ImVec2, ImVec2, ImVec2, ImVec2);
void frame_overlay_draw(ImDrawList*, ImVec2, ImVec2);
void frame_child(const TimelineItemRow&, int&, float);
void frames_child();
void draw();
};
}
File diff suppressed because it is too large. Load diff
+248
View File
@@ -0,0 +1,248 @@
#include "context.hpp"
namespace anm2ed::imgui
{
void TimelineContext::draw()
{
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
if (ImGui::Begin(localize.get(LABEL_TIMELINE_WINDOW), &settings.windowIsTimeline))
{
isWindowHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows |
ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);
frames_child();
if (frameMoveDrag.isActive && ImGui::IsMouseReleased(ImGuiMouseButton_Left))
{
if (isFrameMoveDropTarget)
frames_move_to(frameMoveDropType, frameMoveDropItemID, frameMoveDropGroupType, frameMoveDropGroupId,
frameMoveDropIndex);
frame_move_drag_clear();
}
items_child();
}
ImGui::PopStyleVar();
ImGui::End();
if (itemProperties.update(manager, settings, document, reference)) group_selection_reset_for(document);
group_properties_update();
makeManyRegionsPopup.trigger();
if (ImGui::BeginPopupModal(makeManyRegionsPopup.label(), &makeManyRegionsPopup.isOpen, ImGuiWindowFlags_NoResize))
{
input_text_string(localize.get(LABEL_FORMAT), &settings.generateRegionNameFormat);
ImGui::Checkbox(localize.get(LABEL_MAP_FRAMES_TO_REGIONS), &isMakeManyRegionsMapFrames);
auto widgetSize = widget_size_with_row_get(2);
if (ImGui::Button(localize.get(LABEL_MAKE_MANY_REGIONS), widgetSize))
{
auto targetFrames = makeManyRegionReferences;
auto format = settings.generateRegionNameFormat;
auto mapping = isMakeManyRegionsMapFrames ? Document::RegionFrameMapping::SET
: Document::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); });
makeManyRegionsPopup.close();
}
ImGui::SameLine();
if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) makeManyRegionsPopup.close();
ImGui::EndPopup();
}
makeManyRegionsPopup.end();
bakePopup.trigger();
if (ImGui::BeginPopupModal(bakePopup.label(), &bakePopup.isOpen, ImGuiWindowFlags_NoResize))
{
auto& interval = settings.bakeInterval;
auto& isRoundRotation = settings.bakeIsRoundRotation;
auto& isRoundScale = settings.bakeIsRoundScale;
auto frame = frame_get();
input_int_range(localize.get(LABEL_INTERVAL), interval, FRAME_DURATION_MIN,
frame ? frame->duration : FRAME_DURATION_MIN);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_INTERVAL));
ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION));
ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE));
auto widgetSize = widget_size_with_row_get(2);
shortcut(manager.chords[SHORTCUT_CONFIRM]);
if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize))
{
frames_bake();
bakePopup.close();
}
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_FRAMES_OPTIONS));
ImGui::SameLine();
shortcut(manager.chords[SHORTCUT_CANCEL]);
if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakePopup.close();
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES));
ImGui::EndPopup();
}
bakeIntoOtherFramesPopup.trigger();
if (ImGui::BeginPopupModal(bakeIntoOtherFramesPopup.label(), &bakeIntoOtherFramesPopup.isOpen,
ImGuiWindowFlags_NoResize))
{
auto& isRoundRotation = settings.bakeIsRoundRotation;
auto& isRoundScale = settings.bakeIsRoundScale;
auto& isMatchRootInterpolation = settings.bakeIsMatchRootInterpolation;
auto& isUseRootPivot = settings.bakeIsUseRootPivot;
int target = (int)bakeIntoOtherFramesTarget;
ImGui::RadioButton(localize.get(LABEL_CURRENT_SELECTION), &target,
(int)BakeIntoOtherFramesTarget::CURRENT_SELECTION);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_CURRENT_SELECTION));
ImGui::SameLine();
ImGui::RadioButton(localize.get(LABEL_ALL), &target, (int)BakeIntoOtherFramesTarget::ALL);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL));
bakeIntoOtherFramesTarget = (BakeIntoOtherFramesTarget)target;
auto isCurrentSelection = bakeIntoOtherFramesTarget == BakeIntoOtherFramesTarget::CURRENT_SELECTION;
ImGui::BeginDisabled(isCurrentSelection);
ImGui::Checkbox(localize.get(LABEL_LAYERS), &isBakeIntoOtherFramesLayers);
ImGui::SameLine();
ImGui::Checkbox(localize.get(LABEL_NULLS), &isBakeIntoOtherFramesNulls);
ImGui::EndDisabled();
ImGui::Checkbox(localize.get(LABEL_ROUND_ROTATION), &isRoundRotation);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_ROTATION));
ImGui::Checkbox(localize.get(LABEL_ROUND_SCALE), &isRoundScale);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROUND_SCALE));
ImGui::Checkbox(localize.get(LABEL_BAKE_MATCH_ROOT_INTERPOLATION), &isMatchRootInterpolation);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION));
ImGui::Checkbox(localize.get(LABEL_BAKE_USE_ROOT_PIVOT), &isUseRootPivot);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BAKE_USE_ROOT_PIVOT));
auto widgetSize = widget_size_with_row_get(2);
shortcut(manager.chords[SHORTCUT_CONFIRM]);
ImGui::BeginDisabled(!is_bake_into_other_frames_ready());
if (ImGui::Button(localize.get(LABEL_BAKE), widgetSize))
{
bake_into_other_frames();
bakeIntoOtherFramesPopup.close();
}
ImGui::EndDisabled();
ImGui::SameLine();
shortcut(manager.chords[SHORTCUT_CANCEL]);
if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) bakeIntoOtherFramesPopup.close();
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CANCEL_BAKE_FRAMES));
ImGui::EndPopup();
}
if (animation)
{
if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle();
if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL))
{
playback_stop();
playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX);
document.frameTime = playback.time;
}
if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL))
{
playback_stop();
playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX);
document.frameTime = playback.time;
}
static bool isShortenChordHeld = false;
auto isShortenFrame = shortcut(manager.chords[SHORTCUT_SHORTEN_FRAME], shortcut::GLOBAL);
if (isShortenFrame)
{
auto selectedFrames = frame_references_for_current_get();
std::erase_if(selectedFrames,
[](const Reference& frameReference) { return frameReference.itemType == TRIGGER; });
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);
});
}
}
isShortenChordHeld = isShortenFrame;
static bool isExtendChordHeld = false;
auto isExtendFrame = shortcut(manager.chords[SHORTCUT_EXTEND_FRAME], shortcut::GLOBAL);
if (isExtendFrame)
{
auto selectedFrames = frame_references_for_current_get();
std::erase_if(selectedFrames,
[](const Reference& frameReference) { return frameReference.itemType == TRIGGER; });
if (!selectedFrames.empty())
{
if (!isExtendChordHeld) frames_snapshot_command_push(EDIT_EXTEND_FRAME, selectedFrames);
command_push([=, this](Manager&, Document& document)
{
for (auto frameReference : selectedFrames)
{
auto frame = command_frame_get(document, frameReference);
if (!frame) continue;
frame->duration = std::min(FRAME_DURATION_MAX, frame->duration + 1);
}
document.anm2_change(Document::FRAMES);
});
}
}
isExtendChordHeld = isExtendFrame;
auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], shortcut::GLOBAL);
auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], shortcut::GLOBAL);
auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], shortcut::GLOBAL);
auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL);
if (isPreviousFrame)
if (auto item = selected_item_get(); item && !item->children.empty())
reference.frameIndex = glm::clamp(--reference.frameIndex, 0, (int)item->children.size() - 1);
if (isNextFrame)
if (auto item = selected_item_get(); item && !item->children.empty())
reference.frameIndex = glm::clamp(++reference.frameIndex, 0, (int)item->children.size() - 1);
if (isPreviousFrame || isNextFrame)
{
if (auto item = selected_item_get(); item && !item->children.empty())
{
frames_selection_set_reference();
document.frameTime = frame_time_from_index_get(*item, reference.frameIndex);
}
}
if (isPreviousItem) reference_set_adjacent_item(-1);
if (isNextItem) reference_set_adjacent_item(1);
}
if (isTextPushed) ImGui::PopStyleColor();
}
}
+67
View File
@@ -0,0 +1,67 @@
#include "context.hpp"
namespace anm2ed::imgui
{
Timeline::Timeline() = default;
Timeline::~Timeline() = default;
TimelineContext::TimelineContext(Timeline& timeline, Manager& manager, Settings& settings, Resources& resources,
Clipboard& clipboard)
: timeline(timeline), isDragging(timeline.isDragging), isWindowHovered(timeline.isWindowHovered),
isHorizontalScroll(timeline.isHorizontalScroll), itemProperties(timeline.itemProperties),
bakePopup(timeline.bakePopup), bakeIntoOtherFramesPopup(timeline.bakeIntoOtherFramesPopup),
makeManyRegionsPopup(timeline.makeManyRegionsPopup),
bakeIntoOtherFramesTarget(timeline.bakeIntoOtherFramesTarget),
isBakeIntoOtherFramesLayers(timeline.isBakeIntoOtherFramesLayers),
isBakeIntoOtherFramesNulls(timeline.isBakeIntoOtherFramesNulls),
isMakeManyRegionsMapFrames(timeline.isMakeManyRegionsMapFrames),
makeManyRegionReferences(timeline.makeManyRegionReferences), hoveredTime(timeline.hoveredTime),
isFrameBoxPending(timeline.isFrameBoxPending), isFrameBoxSelecting(timeline.isFrameBoxSelecting),
isFrameBoxAdditive(timeline.isFrameBoxAdditive), frameBoxStart(timeline.frameBoxStart),
frameBoxEnd(timeline.frameBoxEnd), frameBoxSelection(timeline.frameBoxSelection),
rowSelectionAnchor(timeline.rowSelectionAnchor), isRowSelectionAnchorSet(timeline.isRowSelectionAnchorSet),
groupPropertiesPopup(timeline.groupPropertiesPopup), groupName(timeline.groupName),
groupAnimationIndex(timeline.groupAnimationIndex), groupType(timeline.groupType), groupId(timeline.groupId),
draggedFrameReference(timeline.draggedFrameReference), isDraggedFrameActive(timeline.isDraggedFrameActive),
draggedFrameType(timeline.draggedFrameType), draggedFrameIndex(timeline.draggedFrameIndex),
draggedFrameStart(timeline.draggedFrameStart), draggedFrameStartDuration(timeline.draggedFrameStartDuration),
draggedFrameStartDurations(timeline.draggedFrameStartDurations),
draggedFrameStartMouseX(timeline.draggedFrameStartMouseX), draggedFrameWidth(timeline.draggedFrameWidth),
isDraggedFrameSnapshot(timeline.isDraggedFrameSnapshot), frameFocusRequested(timeline.frameFocusRequested),
frameFocusIndex(timeline.frameFocusIndex), frameMoveDrag(timeline.frameMoveDrag),
frameSelectionSnapshot(timeline.frameSelectionSnapshot), frameSelectionLocked(timeline.frameSelectionLocked),
isFrameSelectionLocked(timeline.isFrameSelectionLocked),
frameSelectionSnapshotReference(timeline.frameSelectionSnapshotReference),
frameSelectionAnchor(timeline.frameSelectionAnchor), isFrameSelectionAnchorSet(timeline.isFrameSelectionAnchorSet),
animationLengthEditIndex(timeline.animationLengthEditIndex), rowDragReferences(timeline.rowDragReferences),
scroll(timeline.scroll), style(timeline.style), manager(manager), settings(settings), resources(resources),
clipboard(clipboard), document(*manager.get()), anm2(document.anm2), playback(document.playback),
reference(document.reference), frames(document.frames), region(document.region)
{
}
void TimelineContext::update()
{
animation = anm2.element_get(ElementType::ANIMATION, reference.animationIndex);
rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f;
style = ImGui::GetStyle();
isLightTheme = settings.theme == theme::LIGHT;
isTextPushed = false;
if (isLightTheme)
{
ImGui::PushStyleColor(ImGuiCol_Text, TIMELINE_TEXT_COLOR_LIGHT);
isTextPushed = true;
}
commands_bind();
draw();
}
void Timeline::update(Manager& manager, Settings& settings, Resources& resources, Clipboard& clipboard)
{
if (!manager.get()) return;
context = std::make_unique<TimelineContext>(*this, manager, settings, resources, clipboard);
context->update();
}
}
@@ -1,5 +1,6 @@
#pragma once
#include <memory>
#include <set>
#include <string>
#include <vector>
@@ -14,6 +15,8 @@
namespace anm2ed::imgui
{
struct TimelineContext;
struct TimelineRowReference
{
int documentIndex{-1};
@@ -56,6 +59,8 @@ namespace anm2ed::imgui
class Timeline
{
friend struct TimelineContext;
bool isDragging{};
bool isWindowHovered{};
bool isHorizontalScroll{};
@@ -105,8 +110,11 @@ namespace anm2ed::imgui
std::vector<TimelineRowReference> rowDragReferences{};
glm::vec2 scroll{};
ImGuiStyle style{};
std::unique_ptr<TimelineContext> context{};
public:
Timeline();
~Timeline();
void update(Manager&, Settings&, Resources&, Clipboard&);
};
}
+629
View File
@@ -0,0 +1,629 @@
#include "context.hpp"
namespace anm2ed::imgui
{
void TimelineContext::item_child(const TimelineItemRow& row, int index)
{
ImGui::PushID(index);
auto type = row.type;
auto id = row.id;
auto row_reference_make = [&]()
{ return Reference{reference.animationIndex, type, id, -1, row.rootGroupType, row.rootGroupId}; };
if (row.isGroup)
{
auto group = row_group_get(row);
if (!group)
{
ImGui::PopID();
return;
}
auto label = group->name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group->name;
auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight);
auto isGroupVisible = group->isVisible;
auto colorVec = item_color_vec(type);
if (is_group_selected(row))
{
if (isLightTheme)
colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)];
else
colorVec = item_color_active_vec(type);
}
auto color = to_imvec4(isGroupVisible ? colorVec : colorVec * COLOR_HIDDEN_MULTIPLIER);
ImGui::PushStyleColor(ImGuiCol_ChildBg, color);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding);
if (ImGui::BeginChild("##Group Child", itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse))
{
auto cursorPos = ImGui::GetCursorPos();
auto groupChildMin = ImGui::GetWindowPos();
auto groupChildMax = ImVec2(groupChildMin.x + ImGui::GetWindowSize().x,
groupChildMin.y + ImGui::GetWindowSize().y);
auto toggle_group = [&]()
{
auto targetRow = row;
auto targetAnimationIndex = reference.animationIndex;
edit_command_push(EDIT_TOGGLE_GROUP_EXPANDED, Document::ITEMS,
[=, this](Manager&, Document& document) mutable
{
auto animation = command_animation_get(document, targetAnimationIndex);
auto container =
animation ? element_child_first_get(*animation, container_type_get(targetRow.type))
: nullptr;
auto group = container ? element_child_id_get(*container, ElementType::GROUP,
targetRow.id)
: nullptr;
if (!group) return;
group->isExpanded = !group->isExpanded;
});
};
ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing)));
ImGui::SetNextItemAllowOverlap();
ImGui::InvisibleButton("##Group Button", itemSize);
auto groupButtonMin = ImGui::GetItemRectMin();
auto groupButtonMax = ImGui::GetItemRectMax();
auto mousePos = ImGui::GetIO().MousePos;
auto is_mouse_in_rect = [](ImVec2 mouse, ImVec2 min, ImVec2 max)
{ return mouse.x >= min.x && mouse.x < max.x && mouse.y >= min.y && mouse.y < max.y; };
auto isGroupHovered = ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) &&
is_mouse_in_rect(mousePos, groupButtonMin, groupButtonMax);
bool isGroupTooltipDelayed{};
if (isGroupHovered)
{
auto& imguiStyle = ImGui::GetStyle();
auto previousTooltipDelay = imguiStyle.HoverDelayNormal;
imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY;
isGroupTooltipDelayed =
ImGui::IsItemHovered(ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal |
ImGuiHoveredFlags_AllowWhenDisabled | ImGuiHoveredFlags_NoSharedDelay);
imguiStyle.HoverDelayNormal = previousTooltipDelay;
}
if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS))
{
rowDragReferences = row_drag_references_get(row);
ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(),
(int)rowDragReferences.size() * (int)sizeof(TimelineRowReference));
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (auto payload = ImGui::AcceptDragDropPayload(
"Timeline Row Drag Drop",
ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
{
auto groupDropThird = (groupButtonMax.y - groupButtonMin.y) / 3.0f;
auto dropZone = DropZone::BEFORE;
if (mousePos.y >= groupButtonMax.y - groupDropThird)
dropZone = DropZone::AFTER;
else if (mousePos.y >= groupButtonMin.y + groupDropThird)
dropZone = DropZone::INSIDE;
auto isDropAfter = dropZone != DropZone::BEFORE;
auto payloadRows = (TimelineRowReference*)payload->Data;
auto payloadCount = payload->DataSize / sizeof(TimelineRowReference);
std::vector<TimelineRowReference> draggedRows(payloadRows, payloadRows + payloadCount);
auto isDropIntoGroup = dropZone == DropZone::INSIDE && (row.type == LAYER || row.type == NULL_);
for (auto draggedRow : draggedRows)
if (draggedRow.isGroup || draggedRow.type != row.type) isDropIntoGroup = false;
if (isDropIntoGroup)
drop_box_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax);
else
drop_line_draw(ImGui::GetWindowDrawList(), groupChildMin, groupChildMax, isDropAfter);
if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, isDropIntoGroup);
}
ImGui::EndDragDropTarget();
}
ImGui::SetCursorPos(cursorPos);
auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER;
ImGui::Image(resources.icons[folderIcon].id, icon_size_get());
auto iconMin = ImGui::GetItemRectMin();
auto iconMax = ImGui::GetItemRectMax();
overlay_icon(resources.icons[folderIcon].id, itemIconTint, false);
ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor);
ImGui::TextUnformatted(label.c_str());
ImGui::PopStyleColor();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4());
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f);
ImGui::SetCursorPos(
ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x,
(itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2));
int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE;
if (ImGui::ImageButton("##Group Visible Toggle", resources.icons[visibleIcon].id, icon_size_get()))
{
auto targetAnimationIndex = reference.animationIndex;
auto targetType = type;
auto targetGroupId = group->id;
auto targetVisible = !isGroupVisible;
edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES,
[=, this](Manager&, Document& document)
{
auto animation = command_animation_get(document, targetAnimationIndex);
auto container =
animation ? element_child_first_get(*animation, container_type_get(targetType))
: nullptr;
if (!container) return;
auto group = element_child_id_get(*container, ElementType::GROUP, targetGroupId);
if (!group) return;
group->isVisible = targetVisible;
});
}
auto visibleButtonMin = ImGui::GetItemRectMin();
auto visibleButtonMax = ImGui::GetItemRectMax();
overlay_icon(resources.icons[visibleIcon].id, itemIconTint, false);
ImGui::SetItemTooltip("%s", isGroupVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN)
: localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN));
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
auto isIconHovered = isGroupHovered && is_mouse_in_rect(mousePos, iconMin, iconMax);
auto isVisibleButtonHovered = isGroupHovered && is_mouse_in_rect(mousePos, visibleButtonMin, visibleButtonMax);
if (isGroupTooltipDelayed && !isVisibleButtonHovered)
{
ImGui::BeginTooltip();
ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE);
ImGui::TextUnformatted(label.c_str());
ImGui::PopFont();
ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str());
auto groupItemsCount = group_items_count_get(type, group->id);
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_ITEMS_COUNT), std::make_format_args(groupItemsCount)).c_str());
ImGui::EndTooltip();
}
if (isIconHovered && ImGui::IsMouseReleased(ImGuiMouseButton_Left) &&
!ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left))
toggle_group();
else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered &&
ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
group_properties_open(row, *group);
else if (isGroupHovered && !isIconHovered && !isVisibleButtonHovered &&
ImGui::IsMouseReleased(ImGuiMouseButton_Left) && !ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left))
row_selection_set(row);
}
ImGui::EndChild();
ImGui::PopStyleVar(2);
ImGui::PopStyleColor();
ImGui::PopID();
return;
}
auto item = item_get(type, id, row.rootGroupType, row.rootGroupId);
if (type != NONE && !item)
{
ImGui::PopID();
return;
}
auto isItemVisible = item ? item->isVisible : false;
auto isVisible = item ? item->isVisible && is_track_group_visible(type, row.groupId) : false;
if (item && type == ROOT && row.rootGroupId != -1)
isVisible = item->isVisible && is_track_group_visible(row.rootGroupType, row.rootGroupId);
auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers;
if (isOnlyShowLayers && type != LAYER) isVisible = false;
auto isReferenced = is_same_item(reference, row_reference_make());
auto isItemSelected = is_row_selected(row);
auto label = [&]() -> std::string
{
if (type == LAYER)
{
auto layer = layer_get(id);
if (!layer) return localize.get(TYPE_STRINGS[type]);
return std::vformat(localize.get(FORMAT_LAYER), std::make_format_args(id, layer->name, layer->spritesheetId));
}
if (type == NULL_)
{
auto null = null_get(id);
if (!null) return localize.get(TYPE_STRINGS[type]);
return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name));
}
return localize.get(TYPE_STRINGS[type]);
}();
auto icon = TYPE_ICONS[type];
auto iconTintCurrent = isLightTheme && type == NONE ? ImVec4(1.0f, 1.0f, 1.0f, 1.0f) : itemIconTint;
auto baseColorVec = item_color_vec(type);
auto activeColorVec = item_color_active_vec(type);
auto colorVec = baseColorVec;
if (isItemSelected && type != NONE)
{
if (isLightTheme)
colorVec = ITEM_COLOR_LIGHT_SELECTED[type_index(type)];
else
colorVec = activeColorVec;
}
auto color = to_imvec4(colorVec);
color = !isVisible ? to_imvec4(colorVec * COLOR_HIDDEN_MULTIPLIER) : color;
ImGui::PushStyleColor(ImGuiCol_ChildBg, color);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding);
auto itemSize = ImVec2(ImGui::GetContentRegionAvail().x, rowFrameChildHeight);
if (ImGui::BeginChild(label.c_str(), itemSize, ImGuiChildFlags_Borders, ImGuiWindowFlags_NoScrollWithMouse))
{
auto cursorPos = ImGui::GetCursorPos();
auto itemChildMin = ImGui::GetWindowPos();
auto itemChildMax = ImVec2(itemChildMin.x + ImGui::GetWindowSize().x, itemChildMin.y + ImGui::GetWindowSize().y);
if (type != NONE)
{
ImGui::SetCursorPos(to_imvec2(to_vec2(cursorPos) - to_vec2(style.ItemSpacing)));
ImGui::SetNextItemAllowOverlap();
ImGui::SetNextItemStorageID(id);
ImGui::InvisibleButton("##Item Button", itemSize);
auto itemButtonMin = ImGui::GetItemRectMin();
auto itemButtonMax = ImGui::GetItemRectMax();
auto isItemButtonHovered = ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);
if (type == LAYER || type == NULL_)
{
if (ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS))
{
rowDragReferences = row_drag_references_get(row);
ImGui::SetDragDropPayload("Timeline Row Drag Drop", rowDragReferences.data(),
(int)rowDragReferences.size() * (int)sizeof(TimelineRowReference));
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (auto payload = ImGui::AcceptDragDropPayload(
"Timeline Row Drag Drop",
ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
{
auto isDropAfter = is_drop_after(itemButtonMin, itemButtonMax);
drop_line_draw(ImGui::GetWindowDrawList(), itemChildMin, itemChildMax, isDropAfter);
auto payloadRows = (TimelineRowReference*)payload->Data;
auto payloadCount = payload->DataSize / sizeof(TimelineRowReference);
std::vector<TimelineRowReference> draggedRows(payloadRows, payloadRows + payloadCount);
if (payload->IsDelivery()) rows_move_to_row(draggedRows, row, isDropAfter, false);
}
ImGui::EndDragDropTarget();
}
}
if (isItemButtonHovered)
{
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) item_base_properties_open(type, id);
else if (ImGui::IsMouseReleased(ImGuiMouseButton_Left) &&
!ImGui::IsMouseDragPastThreshold(ImGuiMouseButton_Left))
row_selection_set(row);
auto& imguiStyle = ImGui::GetStyle();
auto previousTooltipFlags = imguiStyle.HoverFlagsForTooltipMouse;
auto previousTooltipDelay = imguiStyle.HoverDelayNormal;
imguiStyle.HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayNormal |
ImGuiHoveredFlags_AllowWhenDisabled |
ImGuiHoveredFlags_NoSharedDelay;
imguiStyle.HoverDelayNormal = FRAME_TOOLTIP_HOVER_DELAY;
bool showItemTooltip = ImGui::BeginItemTooltip();
imguiStyle.HoverFlagsForTooltipMouse = previousTooltipFlags;
imguiStyle.HoverDelayNormal = previousTooltipDelay;
if (showItemTooltip)
{
auto yesNoLabel = [&](bool value) { return value ? localize.get(BASIC_YES) : localize.get(BASIC_NO); };
auto visibleLabel = yesNoLabel(isVisible);
auto framesCount = item_frames_count(item);
switch (type)
{
case ROOT:
{
ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE);
ImGui::TextUnformatted(localize.get(BASIC_ROOT));
ImGui::PopFont();
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str());
auto transformLabel = yesNoLabel(settings.previewIsRootTransform);
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_TRANSFORM), std::make_format_args(transformLabel)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str());
break;
}
case LAYER:
{
auto layer = layer_get(id);
if (!layer) break;
ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE);
ImGui::TextUnformatted(layer->name.c_str());
ImGui::PopFont();
ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_SPRITESHEET_ID), std::make_format_args(layer->spritesheetId))
.c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str());
break;
}
case NULL_:
{
auto nullInfo = null_get(id);
if (!nullInfo) break;
ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE);
ImGui::TextUnformatted(nullInfo->name.c_str());
ImGui::PopFont();
auto rectLabel = yesNoLabel(nullInfo->isShowRect);
ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_RECT), std::make_format_args(rectLabel)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_FRAMES_COUNT), std::make_format_args(framesCount)).c_str());
break;
}
case TRIGGER:
{
ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE);
ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS));
ImGui::PopFont();
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_VISIBLE), std::make_format_args(visibleLabel)).c_str());
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_TRIGGERS_COUNT), std::make_format_args(framesCount)).c_str());
break;
}
default:
break;
}
ImGui::EndTooltip();
}
}
auto contentCursorPos = cursorPos;
contentCursorPos.x += (float)row.depth * ImGui::GetTextLineHeightWithSpacing();
ImGui::SetCursorPos(contentCursorPos);
ImGui::Image(resources.icons[icon].id, icon_size_get());
overlay_icon(resources.icons[icon].id, iconTintCurrent, false);
ImGui::SameLine();
if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE);
ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor);
ImGui::TextUnformatted(label.c_str());
ImGui::PopStyleColor();
if (isReferenced) ImGui::PopFont();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4());
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f);
ImGui::SetCursorPos(
ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x,
(itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2));
int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE;
if (ImGui::ImageButton("##Visible Toggle", resources.icons[visibleIcon].id, icon_size_get()))
{
auto animationIndex = reference.animationIndex;
auto targetType = type;
auto targetID = id;
auto targetGroupType = row.rootGroupType;
auto targetGroupId = row.rootGroupId;
edit_command_push(EDIT_TOGGLE_ITEM_VISIBILITY, Document::FRAMES,
[=, this](Manager&, Document& document)
{
auto item = command_item_get(document, animationIndex, targetType, targetID,
targetGroupType, targetGroupId);
if (!item) return;
item->isVisible = !item->isVisible;
});
}
overlay_icon(resources.icons[visibleIcon].id, iconTintCurrent, false);
ImGui::SetItemTooltip("%s", isItemVisible ? localize.get(TOOLTIP_ITEM_VISIBILITY_SHOWN)
: localize.get(TOOLTIP_ITEM_VISIBILITY_HIDDEN));
if (type == NULL_)
{
if (auto null = null_get(id))
{
auto& isShowRect = null->isShowRect;
auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT;
ImGui::SetCursorPos(
ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x,
(itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2));
if (ImGui::ImageButton("##Rect Toggle", resources.icons[rectIcon].id, icon_size_get()))
{
auto nullID = id;
edit_command_push(EDIT_TOGGLE_NULL_RECT, Document::FRAMES,
[=, this](Manager&, Document& document)
{
auto nulls = document.anm2.element_get(ElementType::NULLS);
auto null = nulls ? element_child_id_get(*nulls, ElementType::NULL_ELEMENT, nullID)
: nullptr;
if (!null) return;
null->isShowRect = !null->isShowRect;
});
}
overlay_icon(resources.icons[rectIcon].id, iconTintCurrent, false);
ImGui::SetItemTooltip("%s", isShowRect ? localize.get(TOOLTIP_NULL_RECT_SHOWN)
: localize.get(TOOLTIP_NULL_RECT_HIDDEN));
}
}
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
}
else
{
auto cursorPos = ImGui::GetCursorPos();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4());
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4());
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 0.0f);
ImGui::SetCursorPos(
ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x,
(itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2));
auto& isShowUnused = settings.timelineIsShowUnused;
auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED;
if (ImGui::ImageButton("##Unused Toggle", resources.icons[unusedIcon].id, icon_size_get()))
isShowUnused = !isShowUnused;
overlay_icon(resources.icons[unusedIcon].id, iconTintCurrent, false);
ImGui::SetItemTooltip("%s", isShowUnused ? localize.get(TOOLTIP_UNUSED_ITEMS_SHOWN)
: localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN));
auto& showLayersOnly = settings.timelineIsOnlyShowLayers;
auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS;
ImGui::SetCursorPos(
ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x,
(itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2));
if (ImGui::ImageButton("##Layers Toggle", resources.icons[layersIcon].id, icon_size_get()))
showLayersOnly = !showLayersOnly;
overlay_icon(resources.icons[layersIcon].id, iconTintCurrent, false);
ImGui::SetItemTooltip("%s", showLayersOnly ? localize.get(TOOLTIP_ONLY_LAYERS_VISIBLE)
: localize.get(TOOLTIP_ALL_ITEMS_VISIBLE));
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
ImGui::SetCursorPos(cursorPos);
ImGui::BeginDisabled();
ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 1.0f, 1.0f));
ImGui::Text("(?)");
ImGui::PopStyleColor();
auto tooltipShortcuts = std::vformat(
localize.get(TOOLTIP_TIMELINE_SHORTCUTS),
std::make_format_args(settings.shortcutMovePlayheadBack, settings.shortcutMovePlayheadForward,
settings.shortcutShortenFrame, settings.shortcutExtendFrame,
settings.shortcutPreviousFrame, settings.shortcutNextFrame,
settings.shortcutPreviousItem, settings.shortcutNextItem));
ImGui::SetItemTooltip("%s", tooltipShortcuts.c_str());
ImGui::EndDisabled();
}
}
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::PopStyleVar(2);
ImGui::PopID();
}
void TimelineContext::items_child()
{
auto itemsChildSize = ImVec2(ITEM_CHILD_WIDTH, ImGui::GetContentRegionAvail().y);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
bool isItemsChildOpen = ImGui::BeginChild("##Items Child", itemsChildSize, ImGuiChildFlags_Borders);
ImGui::PopStyleVar();
if (isItemsChildOpen)
{
auto itemsListChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetContentRegionAvail().y -
ImGui::GetTextLineHeightWithSpacing() -
ImGui::GetStyle().ItemSpacing.y * 2);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2());
if (ImGui::BeginChild("##Items List Child", itemsListChildSize, ImGuiChildFlags_Borders,
ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_NoScrollbar))
{
if (animation && ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused))
{
auto rowReferences = timeline_row_references_get();
row_selection_clear();
for (auto rowReference : rowReferences)
row_selection_insert(rowReference);
if (!rowReferences.empty())
{
rowSelectionAnchor = rowReferences.front();
isRowSelectionAnchorSet = true;
}
frames_selection_reset_for(document);
}
if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) &&
!item_references_groupable_get().empty())
item_group();
ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, ImVec2());
ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize, 0.0f);
if (ImGui::BeginTable("##Item Table", 1, ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY))
{
ImGui::GetCurrentWindow()->Flags |= ImGuiWindowFlags_NoScrollWithMouse;
ImGui::SetScrollY(scroll.y);
ImGui::TableSetupScrollFreeze(0, 1);
ImGui::TableSetupColumn("##Items");
auto item_child_row = [&](const TimelineItemRow& row, int index)
{
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
item_child(row, index);
};
int index{};
item_child_row({.type = NONE}, index++);
if (animation)
for (const auto& row : timeline_item_rows_get())
item_child_row(row, index++);
if (isHorizontalScroll && ImGui::GetCurrentWindow()->ScrollbarY)
{
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::Dummy(ImVec2(0, style.ScrollbarSize));
}
ImGui::EndTable();
}
ImGui::PopStyleVar(2);
item_context_menu();
}
ImGui::PopStyleVar(2);
ImGui::EndChild();
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding);
ImGui::SetCursorPos(ImVec2(ImGui::GetCursorPosX() + style.WindowPadding.x, ImGui::GetCursorPosY()));
auto widgetSize = widget_size_with_row_get(2, ImGui::GetContentRegionAvail().x - style.WindowPadding.x);
ImGui::BeginDisabled(!animation);
{
shortcut(manager.chords[SHORTCUT_ADD]);
if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) itemProperties.open();
set_item_tooltip_shortcut(localize.get(TOOLTIP_ADD_ITEM), settings.shortcutAdd);
ImGui::SameLine();
auto selectedRows = selected_row_references_get();
auto isRemoveAvailable = std::ranges::any_of(selectedRows, [](const TimelineRowReference& row)
{ return row.type == LAYER || row.type == NULL_; });
ImGui::BeginDisabled(!isRemoveAvailable);
shortcut(manager.chords[SHORTCUT_REMOVE]);
if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize)) item_remove();
set_item_tooltip_shortcut(localize.get(TOOLTIP_REMOVE_ITEMS), settings.shortcutRemove);
ImGui::EndDisabled();
}
ImGui::EndDisabled();
ImGui::PopStyleVar();
}
ImGui::EndChild();
}
}