Format like smack-a-brother, and write comments as sentences

Four-space indents, braces on their own lines, and one-statement bodies without braces.
Semicolons in comments became full stops.
Designated initializers may leave fields out without a warning.
This commit is contained in:
shweet committed 2026-11-22 17:30:03 -05:00
1 parent 40f6b554b5
commit 7afdf709c3
176 files changed
+20500 -19048

No files matched your search

+295 -282
View File
@@ -2,233 +2,246 @@
#include "model/xml.h"
constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)";
constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)";
using AnimationPointer = std::shared_ptr<const Animation>;
using AnimationPointer = std::shared_ptr<const Animation>;
std::set<int> animation_group_ids_get(const Model& model)
{
std::set<int> animation_group_ids_get(const Model& model)
{
std::set<int> ids;
for (auto& entry : model.animations.entries)
if (auto group = std::get_if<AnimationGroup>(&entry)) ids.insert(group->id);
if (auto group = std::get_if<AnimationGroup>(&entry))
ids.insert(group->id);
return ids;
}
}
std::set<int> animation_group_indices_get(const Model& model, int groupId)
{
std::set<int> animation_group_indices_get(const Model& model, int groupId)
{
std::set<int> indices;
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.animation_group_id_get(i) == groupId) indices.insert(i);
if (model.animation_group_id_get(i) == groupId)
indices.insert(i);
return indices;
}
}
// Animations and whole groups taken out of the list, remembering the order they had.
struct AnimationsTaken
{
// Animations and whole groups taken out of the list, remembering the order they had.
struct AnimationsTaken
{
std::vector<AnimationPointer> animations;
std::vector<AnimationGroup> groups;
};
};
static AnimationsTaken animations_take(Model& model, const std::set<int>& indices, const std::set<int>& groupIds)
{
static AnimationsTaken animations_take(Model& model, const std::set<int>& indices, const std::set<int>& groupIds)
{
AnimationsTaken taken = {};
int index = 0;
std::erase_if(model.animations.entries,
[&](AnimationEntry& entry)
{
if (auto animation = std::get_if<AnimationPointer>(&entry))
{
if (!indices.contains(index++)) return false;
taken.animations.push_back(std::move(*animation));
return true;
}
auto& group = std::get<AnimationGroup>(entry);
if (groupIds.contains(group.id))
{
index += (int)group.animations.size();
taken.groups.push_back(std::move(group));
return true;
}
std::erase_if(group.animations,
[&](AnimationPointer& animation)
{
if (!indices.contains(index++)) return false;
taken.animations.push_back(std::move(animation));
return true;
});
return false;
});
std::erase_if(model.animations.entries, [&](AnimationEntry& entry) {
if (auto animation = std::get_if<AnimationPointer>(&entry))
{
if (!indices.contains(index++))
return false;
taken.animations.push_back(std::move(*animation));
return true;
}
auto& group = std::get<AnimationGroup>(entry);
if (groupIds.contains(group.id))
{
index += (int)group.animations.size();
taken.groups.push_back(std::move(group));
return true;
}
std::erase_if(group.animations, [&](AnimationPointer& animation) {
if (!indices.contains(index++))
return false;
taken.animations.push_back(std::move(animation));
return true;
});
return false;
});
return taken;
}
}
// Where an animation with this uid sits: its top-level entry, and its group (or nullptr) and position there.
struct AnimationPlace
{
// Where an animation with this uid sits: its top-level entry, and its group (or nullptr) and position there.
struct AnimationPlace
{
int entry = -1;
AnimationGroup* group = nullptr;
int position = -1;
};
};
static AnimationPlace animation_place_get(Model& model, std::uint64_t uid)
{
static AnimationPlace animation_place_get(Model& model, std::uint64_t uid)
{
auto& entries = model.animations.entries;
for (int i = 0; i < (int)entries.size(); ++i)
{
if (auto animation = std::get_if<AnimationPointer>(&entries[i]))
{
if ((*animation)->uid == uid) return {i, nullptr, -1};
continue;
}
auto& group = std::get<AnimationGroup>(entries[i]);
for (int j = 0; j < (int)group.animations.size(); ++j)
if (group.animations[j]->uid == uid) return {i, &group, j};
if (auto animation = std::get_if<AnimationPointer>(&entries[i]))
{
if ((*animation)->uid == uid)
return {i, nullptr, -1};
continue;
}
auto& group = std::get<AnimationGroup>(entries[i]);
for (int j = 0; j < (int)group.animations.size(); ++j)
if (group.animations[j]->uid == uid)
return {i, &group, j};
}
return {};
}
}
static int animation_group_entry_get(const Model& model, int groupId)
{
static int animation_group_entry_get(const Model& model, int groupId)
{
auto& entries = model.animations.entries;
for (int i = 0; i < (int)entries.size(); ++i)
if (auto group = std::get_if<AnimationGroup>(&entries[i]); group && group->id == groupId) return i;
if (auto group = std::get_if<AnimationGroup>(&entries[i]); group && group->id == groupId)
return i;
return -1;
}
}
static AnimationGroup* animation_group_find(Model& model, int groupId)
{
static AnimationGroup* animation_group_find(Model& model, int groupId)
{
auto entry = animation_group_entry_get(model, groupId);
return entry == -1 ? nullptr : &std::get<AnimationGroup>(model.animations.entries[entry]);
}
}
// Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given.
static void animations_insert(Model& model, int index, int groupId, std::vector<AnimationPointer> animations)
{
// Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given.
static void animations_insert(Model& model, int index, int groupId, std::vector<AnimationPointer> animations)
{
auto before = model.animation_get(index);
auto place = before ? animation_place_get(model, before->uid) : AnimationPlace{};
if (auto group = animation_group_find(model, groupId))
{
auto position = place.group == group ? place.position : (int)group->animations.size();
group->animations.insert(group->animations.begin() + position, animations.begin(), animations.end());
return;
auto position = place.group == group ? place.position : (int)group->animations.size();
group->animations.insert(group->animations.begin() + position, animations.begin(), animations.end());
return;
}
auto& entries = model.animations.entries;
auto position = place.entry == -1 ? (int)entries.size() : place.entry;
entries.insert(entries.begin() + position, animations.begin(), animations.end());
}
}
void animation_groups_remove(Model& model, const std::set<int>& groupIds)
{
void animation_groups_remove(Model& model, const std::set<int>& groupIds)
{
auto& entries = model.animations.entries;
for (int i = 0; i < (int)entries.size(); ++i)
{
auto group = std::get_if<AnimationGroup>(&entries[i]);
if (!group || !groupIds.contains(group->id)) continue;
auto animations = std::move(group->animations);
entries.erase(entries.begin() + i);
entries.insert(entries.begin() + i, animations.begin(), animations.end());
i += (int)animations.size() - 1;
auto group = std::get_if<AnimationGroup>(&entries[i]);
if (!group || !groupIds.contains(group->id))
continue;
auto animations = std::move(group->animations);
entries.erase(entries.begin() + i);
entries.insert(entries.begin() + i, animations.begin(), animations.end());
i += (int)animations.size() - 1;
}
}
}
// An empty copy of a track list: same tracks and groups, no frames.
static std::vector<TrackEntry> track_entries_shell_get(const std::vector<TrackEntry>& entries)
{
// An empty copy of a track list: same tracks and groups, no frames.
static std::vector<TrackEntry> track_entries_shell_get(const std::vector<TrackEntry>& entries)
{
std::vector<TrackEntry> shell;
auto track_shell_get = [](const Track& track)
{ return Track{.type = track.type, .id = track.id, .isVisible = track.isVisible}; };
auto track_shell_get = [](const Track& track) {
return Track{.type = track.type, .id = track.id, .isVisible = track.isVisible};
};
for (auto& entry : entries)
if (auto track = std::get_if<Track>(&entry))
shell.emplace_back(track_shell_get(*track));
else
{
auto& group = std::get<TrackGroup>(entry);
TrackGroup copy{
.id = group.id, .name = group.name, .isExpanded = group.isExpanded, .isVisible = group.isVisible};
for (auto& groupTrack : group.tracks)
copy.tracks.push_back(track_shell_get(groupTrack));
shell.emplace_back(std::move(copy));
}
if (auto track = std::get_if<Track>(&entry))
shell.emplace_back(track_shell_get(*track));
else
{
auto& group = std::get<TrackGroup>(entry);
TrackGroup copy{
.id = group.id, .name = group.name, .isExpanded = group.isExpanded, .isVisible = group.isVisible};
for (auto& groupTrack : group.tracks)
copy.tracks.push_back(track_shell_get(groupTrack));
shell.emplace_back(std::move(copy));
}
return shell;
}
}
// Adds an animation with the same (empty) tracks as the template animation.
Uids animation_add(Model& model, int index, int groupId, int templateIndex, const std::string& name)
{
// Adds an animation with the same (empty) tracks as the template animation.
Uids animation_add(Model& model, int index, int groupId, int templateIndex, const std::string& name)
{
Animation animation = {.name = name};
if (auto source = model.animation_get(templateIndex))
{
animation.layers = track_entries_shell_get(source->layers);
animation.nulls = track_entries_shell_get(source->nulls);
animation.layers = track_entries_shell_get(source->layers);
animation.nulls = track_entries_shell_get(source->nulls);
}
if (model.animations_count_get() == 0) model.animations.defaultAnimation = animation.name;
if (model.animations_count_get() == 0)
model.animations.defaultAnimation = animation.name;
auto uid = animation.uid;
animations_insert(model, index, groupId, {std::make_shared<const Animation>(std::move(animation))});
return {uid};
}
}
Uids animations_remove(Model& model, const std::set<int>& indices, const std::set<int>& groupIds)
{
Uids animations_remove(Model& model, const std::set<int>& indices, const std::set<int>& groupIds)
{
animations_take(model, indices, {});
animation_groups_remove(model, groupIds);
return {};
}
}
// Moves animations and whole groups beside a target animation or group; animations dropped on their own join the
// target's group (or the group dropped into).
Uids animations_move(Model& model, const std::set<int>& indices, const std::set<int>& groupIds,
AnimationTarget target)
{
// Moves animations and whole groups beside a target animation or group. Animations dropped on their own join the
// target's group (or the group dropped into).
Uids animations_move(Model& model, const std::set<int>& indices, const std::set<int>& groupIds, AnimationTarget target)
{
auto targetAnimation = model.animation_get(target.animationIndex);
auto targetUid = targetAnimation ? targetAnimation->uid : 0;
if (targetAnimation && groupIds.contains(model.animation_group_id_get(target.animationIndex))) return {};
if (targetAnimation && indices.contains(target.animationIndex)) return {};
if (!targetAnimation && groupIds.contains(target.groupId)) return {};
if (targetAnimation && groupIds.contains(model.animation_group_id_get(target.animationIndex)))
return {};
if (targetAnimation && indices.contains(target.animationIndex))
return {};
if (!targetAnimation && groupIds.contains(target.groupId))
return {};
auto taken = animations_take(model, indices, groupIds);
if (taken.animations.empty() && taken.groups.empty()) return {};
if (taken.animations.empty() && taken.groups.empty())
return {};
Uids uids = {};
for (auto& animation : taken.animations)
uids.push_back(animation->uid);
uids.push_back(animation->uid);
auto& entries = model.animations.entries;
auto topIndex = (int)entries.size();
if (targetUid)
{
auto place = animation_place_get(model, targetUid);
if (place.group)
place.group->animations.insert(place.group->animations.begin() + place.position + target.isAfter,
taken.animations.begin(), taken.animations.end());
else if (place.entry != -1)
entries.insert(entries.begin() + place.entry + target.isAfter, taken.animations.begin(),
taken.animations.end());
place = animation_place_get(model, targetUid);
if (place.entry != -1) topIndex = place.entry + (target.isAfter || place.group);
auto place = animation_place_get(model, targetUid);
if (place.group)
place.group->animations.insert(place.group->animations.begin() + place.position + target.isAfter,
taken.animations.begin(), taken.animations.end());
else if (place.entry != -1)
entries.insert(entries.begin() + place.entry + target.isAfter, taken.animations.begin(),
taken.animations.end());
place = animation_place_get(model, targetUid);
if (place.entry != -1)
topIndex = place.entry + (target.isAfter || place.group);
}
else if (auto entry = animation_group_entry_get(model, target.groupId); entry != -1)
{
auto& group = std::get<AnimationGroup>(entries[entry]);
if (target.isInto)
group.animations.insert(group.animations.end(), taken.animations.begin(), taken.animations.end());
else
entries.insert(entries.begin() + entry + target.isAfter, taken.animations.begin(), taken.animations.end());
if (!target.isInto && !target.isAfter) entry += (int)taken.animations.size();
topIndex = entry + (target.isAfter || target.isInto);
auto& group = std::get<AnimationGroup>(entries[entry]);
if (target.isInto)
group.animations.insert(group.animations.end(), taken.animations.begin(), taken.animations.end());
else
entries.insert(entries.begin() + entry + target.isAfter, taken.animations.begin(), taken.animations.end());
if (!target.isInto && !target.isAfter)
entry += (int)taken.animations.size();
topIndex = entry + (target.isAfter || target.isInto);
}
else
entries.insert(entries.end(), taken.animations.begin(), taken.animations.end());
entries.insert(entries.end(), taken.animations.begin(), taken.animations.end());
entries.insert(entries.begin() + std::clamp(topIndex, 0, (int)entries.size()),
std::make_move_iterator(taken.groups.begin()), std::make_move_iterator(taken.groups.end()));
return uids;
}
}
// Wraps ungrouped animations in a new group placed where the first of them was.
Uids animations_group(Model& model, const std::set<int>& indices, const std::string& name)
{
if (indices.empty()) return {};
// Wraps ungrouped animations in a new group placed where the first of them was.
Uids animations_group(Model& model, const std::set<int>& indices, const std::string& name)
{
if (indices.empty())
return {};
auto first = model.animation_get(*indices.begin());
if (!first) return {};
if (!first)
return {};
auto firstUid = first->uid;
auto entry = animation_place_get(model, firstUid).entry;
auto groupIds = animation_group_ids_get(model);
@@ -238,15 +251,16 @@
auto& entries = model.animations.entries;
entries.insert(entries.begin() + std::clamp(entry, 0, (int)entries.size()), std::move(group));
return {};
}
}
// Pastes clipboard animations (and groups, which get new ids) before the animation at `start`; lone animations join
// `targetGroupId` when no group came with them.
Uids animations_paste(Model& model, const std::string& text, int start, int targetGroupId, std::set<int>& groupIds,
std::string* errorString)
{
// Pastes clipboard animations (and groups, which get new ids) before the animation at `start`. Lone animations join
// `targetGroupId` when no group came with them.
Uids animations_paste(Model& model, const std::string& text, int start, int targetGroupId, std::set<int>& groupIds,
std::string* errorString)
{
auto entries = animations_from_string(text, errorString);
if (entries.empty()) return {};
if (entries.empty())
return {};
auto existingGroupIds = animation_group_ids_get(model);
auto nextGroupId = existingGroupIds.empty() ? 0 : *existingGroupIds.rbegin() + 1;
@@ -254,26 +268,26 @@
std::vector<AnimationPointer> loose;
std::vector<AnimationEntry> placed;
for (auto& entry : entries)
if (auto animation = std::get_if<AnimationPointer>(&entry))
{
uids.push_back((*animation)->uid);
loose.push_back(*animation);
placed.push_back(entry);
}
else
{
auto& group = std::get<AnimationGroup>(entry);
group.id = nextGroupId++;
groupIds.insert(group.id);
for (auto& animation : group.animations)
uids.push_back(animation->uid);
placed.push_back(std::move(entry));
}
if (auto animation = std::get_if<AnimationPointer>(&entry))
{
uids.push_back((*animation)->uid);
loose.push_back(*animation);
placed.push_back(entry);
}
else
{
auto& group = std::get<AnimationGroup>(entry);
group.id = nextGroupId++;
groupIds.insert(group.id);
for (auto& animation : group.animations)
uids.push_back(animation->uid);
placed.push_back(std::move(entry));
}
if (groupIds.empty() && targetGroupId != -1 && animation_group_find(model, targetGroupId))
{
animations_insert(model, start, targetGroupId, std::move(loose));
return uids;
animations_insert(model, start, targetGroupId, std::move(loose));
return uids;
}
auto before = model.animation_get(start);
@@ -281,146 +295,145 @@
model.animations.entries.insert(model.animations.entries.begin() + position,
std::make_move_iterator(placed.begin()), std::make_move_iterator(placed.end()));
return uids;
}
}
static void track_merge(Track& destination, const Track& source, Merge type)
{
static void track_merge(Track& destination, const Track& source, Merge type)
{
std::vector<Frame> frames;
for (auto& frame : source.frames)
frames.push_back(frame_clone(frame));
frames.push_back(frame_clone(frame));
switch (type)
{
case MERGE_APPEND:
destination.frames.insert(destination.frames.end(), frames.begin(), frames.end());
break;
case MERGE_PREPEND:
destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end());
break;
case MERGE_REPLACE:
if (destination.frames.size() < frames.size()) destination.frames.resize(frames.size());
std::ranges::copy(frames, destination.frames.begin());
break;
default:
break;
case MERGE_APPEND:
destination.frames.insert(destination.frames.end(), frames.begin(), frames.end());
break;
case MERGE_PREPEND:
destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end());
break;
case MERGE_REPLACE:
if (destination.frames.size() < frames.size())
destination.frames.resize(frames.size());
std::ranges::copy(frames, destination.frames.begin());
break;
default:
break;
}
}
}
// Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id
// within their group (else are added).
static void track_entries_merge(std::vector<TrackEntry>& destination, const std::vector<TrackEntry>& source,
Merge type)
{
// Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id
// within their group (else are added).
static void track_entries_merge(std::vector<TrackEntry>& destination, const std::vector<TrackEntry>& source, Merge type)
{
std::map<int, int> groupRemap;
std::set<int> matchedGroupIds;
int nextGroupId = 0;
groups_each(destination, [&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); });
groups_each(source,
[&](const TrackGroup& sourceGroup)
{
TrackGroup* matched = nullptr;
groups_each(destination,
[&](TrackGroup& group)
{
if (!matched && group.name == sourceGroup.name && !matchedGroupIds.contains(group.id))
matched = &group;
});
if (matched)
track_merge(matched->root, sourceGroup.root, type);
else
{
TrackGroup group{.id = nextGroupId++,
.name = sourceGroup.name,
.isExpanded = sourceGroup.isExpanded,
.isVisible = sourceGroup.isVisible,
.root = track_clone(sourceGroup.root),
.extras = sourceGroup.extras};
destination.emplace_back(std::move(group));
matched = &std::get<TrackGroup>(destination.back());
}
groupRemap[sourceGroup.id] = matched->id;
matchedGroupIds.insert(matched->id);
});
groups_each(source, [&](const TrackGroup& sourceGroup) {
TrackGroup* matched = nullptr;
groups_each(destination, [&](TrackGroup& group) {
if (!matched && group.name == sourceGroup.name && !matchedGroupIds.contains(group.id))
matched = &group;
});
if (matched)
track_merge(matched->root, sourceGroup.root, type);
else
{
TrackGroup group{.id = nextGroupId++,
.name = sourceGroup.name,
.isExpanded = sourceGroup.isExpanded,
.isVisible = sourceGroup.isVisible,
.root = track_clone(sourceGroup.root),
.extras = sourceGroup.extras};
destination.emplace_back(std::move(group));
matched = &std::get<TrackGroup>(destination.back());
}
groupRemap[sourceGroup.id] = matched->id;
matchedGroupIds.insert(matched->id);
});
tracks_each(source,
[&](const Track& sourceTrack, const TrackGroup* sourceGroup)
{
TrackGroup* group = nullptr;
if (sourceGroup)
groups_each(destination,
[&](TrackGroup& candidate)
{
if (candidate.id == groupRemap[sourceGroup->id]) group = &candidate;
});
Track* existing = nullptr;
if (group)
{
for (auto& track : group->tracks)
if (track.id == sourceTrack.id) existing = &track;
}
else
for (auto& entry : destination)
if (auto track = std::get_if<Track>(&entry); track && track->id == sourceTrack.id)
existing = track;
tracks_each(source, [&](const Track& sourceTrack, const TrackGroup* sourceGroup) {
TrackGroup* group = nullptr;
if (sourceGroup)
groups_each(destination, [&](TrackGroup& candidate) {
if (candidate.id == groupRemap[sourceGroup->id])
group = &candidate;
});
Track* existing = nullptr;
if (group)
{
for (auto& track : group->tracks)
if (track.id == sourceTrack.id)
existing = &track;
}
else
for (auto& entry : destination)
if (auto track = std::get_if<Track>(&entry); track && track->id == sourceTrack.id)
existing = track;
if (existing)
track_merge(*existing, sourceTrack, type);
else if (group)
group->tracks.push_back(track_clone(sourceTrack));
else
destination.emplace_back(track_clone(sourceTrack));
});
}
if (existing)
track_merge(*existing, sourceTrack, type);
else if (group)
group->tracks.push_back(track_clone(sourceTrack));
else
destination.emplace_back(track_clone(sourceTrack));
});
}
// Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting
// the sources; `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid.
Uids animations_merge(Model& model, int target, std::set<int> sources, Merge type, bool isDeleteAfter,
const std::set<int>& ungroupIds)
{
if (!model.animation_get(target)) return {};
// Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting
// the sources. `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid.
Uids animations_merge(Model& model, int target, std::set<int> sources, Merge type, bool isDeleteAfter,
const std::set<int>& ungroupIds)
{
if (!model.animation_get(target))
return {};
auto isMerge = sources.size() > 1 || !sources.contains(target);
if (isMerge)
{
auto& merged = *model.animation_edit(target);
if (!merged.name.ends_with(ANIMATION_MERGED_SUFFIX)) merged.name += std::string(ANIMATION_MERGED_SUFFIX);
// Triggers are placed by time, so whichever animation ends up second has its triggers moved past the first.
auto length = merged.frameNum;
for (auto index : sources)
{
if (index == target) continue;
auto source = model.animation_get(index);
if (!source) continue;
auto sourceCopy = *source;
auto& destination = *model.animation_edit(target);
if (type == MERGE_APPEND)
for (auto& trigger : sourceCopy.triggers.frames)
trigger.atFrame += length;
if (type == MERGE_PREPEND)
for (auto& trigger : destination.triggers.frames)
trigger.atFrame += sourceCopy.frameNum;
if (type == MERGE_APPEND || type == MERGE_PREPEND) length += sourceCopy.frameNum;
track_merge(destination.root, sourceCopy.root, type);
track_entries_merge(destination.layers, sourceCopy.layers, type);
track_entries_merge(destination.nulls, sourceCopy.nulls, type);
track_merge(destination.triggers, sourceCopy.triggers, type);
}
auto targetUid = model.animation_get(target)->uid;
if (isDeleteAfter)
{
sources.erase(target);
animations_take(model, sources, {});
}
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.animation_get(i)->uid == targetUid)
auto& merged = *model.animation_edit(target);
if (!merged.name.ends_with(ANIMATION_MERGED_SUFFIX))
merged.name += std::string(ANIMATION_MERGED_SUFFIX);
// Triggers are placed by time, so whichever animation ends up second has its triggers moved past the first.
auto length = merged.frameNum;
for (auto index : sources)
{
auto& finalAnimation = *model.animation_edit(i);
finalAnimation.frameNum = animation_length_get(finalAnimation);
target = i;
if (index == target)
continue;
auto source = model.animation_get(index);
if (!source)
continue;
auto sourceCopy = *source;
auto& destination = *model.animation_edit(target);
if (type == MERGE_APPEND)
for (auto& trigger : sourceCopy.triggers.frames)
trigger.atFrame += length;
if (type == MERGE_PREPEND)
for (auto& trigger : destination.triggers.frames)
trigger.atFrame += sourceCopy.frameNum;
if (type == MERGE_APPEND || type == MERGE_PREPEND)
length += sourceCopy.frameNum;
track_merge(destination.root, sourceCopy.root, type);
track_entries_merge(destination.layers, sourceCopy.layers, type);
track_entries_merge(destination.nulls, sourceCopy.nulls, type);
track_merge(destination.triggers, sourceCopy.triggers, type);
}
auto targetUid = model.animation_get(target)->uid;
if (isDeleteAfter)
{
sources.erase(target);
animations_take(model, sources, {});
}
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.animation_get(i)->uid == targetUid)
{
auto& finalAnimation = *model.animation_edit(i);
finalAnimation.frameNum = animation_length_get(finalAnimation);
target = i;
}
}
auto uid = model.animation_get(target)->uid;
animation_groups_remove(model, ungroupIds);
return {uid};
}
}
+409 -413
View File
@@ -6,538 +6,534 @@
#include "model/frames.h"
#include "model/xml.h"
std::string region_name_get(const std::string& format, int number)
{
std::string region_name_get(const std::string& format, int number)
{
try
{
return std::vformat(format, std::make_format_args(number));
return std::vformat(format, std::make_format_args(number));
}
catch (const std::format_error&)
{
return format;
return format;
}
}
}
static bool is_region_matched(const Region& region, const Frame& frame)
{
static bool is_region_matched(const Region& region, const Frame& frame)
{
return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) &&
glm::ivec2(region.pivot) == glm::ivec2(frame.pivot);
}
}
// Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id.
template <class Callback> static void layer_frames_each(Model& model, int animationIndex, Callback&& callback)
{
// Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id.
template <class Callback> static void layer_frames_each(Model& model, int animationIndex, Callback&& callback)
{
auto animation = model.animation_get(animationIndex);
if (!animation) return;
if (!animation)
return;
std::vector<std::pair<int, int>> tracks;
tracks_each(animation->layers,
[&](const Track& track, const TrackGroup* group)
{
if (model.layer_spritesheet_get(track.id)) tracks.emplace_back(track.id, group ? group->id : -1);
});
tracks_each(animation->layers, [&](const Track& track, const TrackGroup* group) {
if (model.layer_spritesheet_get(track.id))
tracks.emplace_back(track.id, group ? group->id : -1);
});
for (auto [id, groupId] : tracks)
{
auto spritesheetId = model.layer_spritesheet_get(id)->id;
auto track = model.track_edit({animationIndex, LAYER, id, -1, groupId == -1 ? NONE : LAYER, groupId});
for (auto& frame : track->frames)
callback(frame, spritesheetId);
auto spritesheetId = model.layer_spritesheet_get(id)->id;
auto track = model.track_edit({animationIndex, LAYER, id, -1, groupId == -1 ? NONE : LAYER, groupId});
for (auto& frame : track->frames)
callback(frame, spritesheetId);
}
}
}
// Makes a region for each distinct crop/size/pivot among the frames (and points frames at them when mapping is SET).
Uids regions_generate(Model& model, const std::set<int>& animationIndices, const std::set<Reference>& frames,
const std::string& format, RegionFrameMapping mapping)
{
// Makes a region for each distinct crop/size/pivot among the frames (and points frames at them when mapping is SET).
Uids regions_generate(Model& model, const std::set<int>& animationIndices, const std::set<Reference>& frames,
const std::string& format, RegionFrameMapping mapping)
{
std::unordered_map<int, int> regionNumbers;
auto frame_apply = [&](Frame& frame, int spritesheetId)
{
auto& regions = item_get(model.content.spritesheets, spritesheetId)->regions;
auto region =
std::ranges::find_if(regions, [&](const Region& region) { return is_region_matched(region, frame); });
if (region == regions.end())
{
regions.push_back({.id = item_next_id_get(regions),
.name = region_name_get(format, ++regionNumbers[spritesheetId]),
.crop = frame.crop,
.size = frame.size,
.pivot = frame.pivot});
region = regions.end() - 1;
}
if (mapping == RegionFrameMapping::SET) frame.regionId = region->id;
auto frame_apply = [&](Frame& frame, int spritesheetId) {
auto& regions = item_get(model.content.spritesheets, spritesheetId)->regions;
auto region =
std::ranges::find_if(regions, [&](const Region& region) { return is_region_matched(region, frame); });
if (region == regions.end())
{
regions.push_back({.id = item_next_id_get(regions),
.name = region_name_get(format, ++regionNumbers[spritesheetId]),
.crop = frame.crop,
.size = frame.size,
.pivot = frame.pivot});
region = regions.end() - 1;
}
if (mapping == RegionFrameMapping::SET)
frame.regionId = region->id;
};
for (auto index : animationIndices)
layer_frames_each(model, index, frame_apply);
layer_frames_each(model, index, frame_apply);
for (auto reference : frames)
{
auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr;
auto source = model.frame_get(reference);
if (spritesheet && source && source->regionId == -1) frame_apply(*model.frame_edit(reference), spritesheet->id);
auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr;
auto source = model.frame_get(reference);
if (spritesheet && source && source->regionId == -1)
frame_apply(*model.frame_edit(reference), spritesheet->id);
}
return {};
}
}
// Points frames without a region at a region of their spritesheet with the same crop/size/pivot.
Uids regions_scan(Model& model)
{
// Points frames without a region at a region of their spritesheet with the same crop/size/pivot.
Uids regions_scan(Model& model)
{
for (int i = 0; i < model.animations_count_get(); ++i)
layer_frames_each(model, i,
[&](Frame& frame, int spritesheetId)
{
if (frame.regionId != -1) return;
for (auto& region : item_get(model.content.spritesheets, spritesheetId)->regions)
if (is_region_matched(region, frame))
{
frame.regionId = region.id;
break;
}
});
layer_frames_each(model, i, [&](Frame& frame, int spritesheetId) {
if (frame.regionId != -1)
return;
for (auto& region : item_get(model.content.spritesheets, spritesheetId)->regions)
if (is_region_matched(region, frame))
{
frame.regionId = region.id;
break;
}
});
return {};
}
}
// Copies each layer frame's region crop/size/pivot onto it; frames pointing at a missing region lose it.
Uids region_frames_sync(Model& model)
{
// Copies each layer frame's region crop/size/pivot onto it. Frames pointing at a missing region lose it.
Uids region_frames_sync(Model& model)
{
for (int i = 0; i < model.animations_count_get(); ++i)
layer_frames_each(model, i,
[&](Frame& frame, int spritesheetId)
{
if (frame.regionId == -1) return;
auto region =
item_get(item_get(model.content.spritesheets, spritesheetId)->regions, frame.regionId);
if (!region)
{
frame.regionId = -1;
return;
}
frame.crop = region->crop;
frame.size = region->size;
frame.pivot = region->pivot;
});
layer_frames_each(model, i, [&](Frame& frame, int spritesheetId) {
if (frame.regionId == -1)
return;
auto region = item_get(item_get(model.content.spritesheets, spritesheetId)->regions, frame.regionId);
if (!region)
{
frame.regionId = -1;
return;
}
frame.crop = region->crop;
frame.size = region->size;
frame.pivot = region->pivot;
});
return {};
}
}
// Clears frame references to the spritesheet's unused regions, then removes them.
// Removes content items (regions of spritesheet `spritesheetId`) with what refers to them: a layer's or null's tracks
// in every animation, an event or sound from its triggers (dropping those left with neither), a shader from its
// frames (which go back to the default), a region from its frames (which keep its crop, size and pivot), a
// spritesheet's plain layers, and a library's layers, flattened into plain ones.
Uids content_remove(Model& model, ElementType type, const std::set<int>& ids, int spritesheetId,
const LibraryGet& library_get, const SpritesheetPathGet& path_get)
{
// Clears frame references to the spritesheet's unused regions, then removes them.
// Removes content items (regions of spritesheet `spritesheetId`) with what refers to them: a layer's or null's tracks
// in every animation, an event or sound from its triggers (dropping those left with neither), a shader from its
// frames (which go back to the default), a region from its frames (which keep its crop, size and pivot), a
// spritesheet's plain layers, and a library's layers, flattened into plain ones.
Uids content_remove(Model& model, ElementType type, const std::set<int>& ids, int spritesheetId,
const LibraryGet& library_get, const SpritesheetPathGet& path_get)
{
auto& content = model.content;
auto items_erase = [&](auto& items)
{ std::erase_if(items, [&](const auto& item) { return ids.contains(item.id); }); };
auto layer_ids_get = [&](auto&& is_removed)
{
std::set<int> layerIds;
for (auto& layer : content.layers)
if (is_removed(layer)) layerIds.insert(layer.id);
return layerIds;
auto items_erase = [&](auto& items) {
std::erase_if(items, [&](const auto& item) { return ids.contains(item.id); });
};
auto layer_ids_get = [&](auto&& is_removed) {
std::set<int> layerIds;
for (auto& layer : content.layers)
if (is_removed(layer))
layerIds.insert(layer.id);
return layerIds;
};
// Only the animations that refer to them are edited.
auto animations_edit = [&](auto&& edit)
{
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.uses_count(type, ids, spritesheetId, model.animation_get(i)) > 0) edit(*model.animation_edit(i), i);
auto animations_edit = [&](auto&& edit) {
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.uses_count(type, ids, spritesheetId, model.animation_get(i)) > 0)
edit(*model.animation_edit(i), i);
};
switch (type)
{
case ElementType::LIBRARY:
model =
animation_layers_flatten(std::move(model), library_get, path_get,
layer_ids_get([&](const Layer& layer) { return ids.contains(layer.libraryId); }));
items_erase(content.libraries);
break;
case ElementType::SPRITESHEET:
content_remove(model, ElementType::LAYER_ELEMENT,
layer_ids_get([&](const Layer& layer)
{ return !layer.is_animation() && ids.contains(layer.spritesheetId); }),
-1, library_get, path_get);
items_erase(content.spritesheets);
break;
case ElementType::LAYER_ELEMENT:
case ElementType::NULL_ELEMENT:
{
auto itemType = type == ElementType::LAYER_ELEMENT ? LAYER : NULL_;
animations_edit([&](Animation&, int index) { items_remove(model, index, {{itemType, ids}}, {}); });
if (type == ElementType::LAYER_ELEMENT)
items_erase(content.layers);
else
items_erase(content.nulls);
break;
}
case ElementType::EVENT_ELEMENT:
case ElementType::SOUND_ELEMENT:
animations_edit(
[&](Animation& animation, int)
{
std::erase_if(animation.triggers.frames,
[&](Frame& trigger)
{
auto& triggerIds =
type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds;
if (!std::erase_if(triggerIds, [&](int id) { return ids.contains(id); })) return false;
return trigger.eventIds.empty() && trigger.soundIds.empty();
});
case ElementType::LIBRARY:
model = animation_layers_flatten(
std::move(model), library_get, path_get,
layer_ids_get([&](const Layer& layer) { return ids.contains(layer.libraryId); }));
items_erase(content.libraries);
break;
case ElementType::SPRITESHEET:
content_remove(model, ElementType::LAYER_ELEMENT, layer_ids_get([&](const Layer& layer) {
return !layer.is_animation() && ids.contains(layer.spritesheetId);
}),
-1, library_get, path_get);
items_erase(content.spritesheets);
break;
case ElementType::LAYER_ELEMENT:
case ElementType::NULL_ELEMENT:
{
auto itemType = type == ElementType::LAYER_ELEMENT ? LAYER : NULL_;
animations_edit([&](Animation&, int index) { items_remove(model, index, {{itemType, ids}}, {}); });
if (type == ElementType::LAYER_ELEMENT)
items_erase(content.layers);
else
items_erase(content.nulls);
break;
}
case ElementType::EVENT_ELEMENT:
case ElementType::SOUND_ELEMENT:
animations_edit([&](Animation& animation, int) {
std::erase_if(animation.triggers.frames, [&](Frame& trigger) {
auto& triggerIds = type == ElementType::EVENT_ELEMENT ? trigger.eventIds : trigger.soundIds;
if (!std::erase_if(triggerIds, [&](int id) { return ids.contains(id); }))
return false;
return trigger.eventIds.empty() && trigger.soundIds.empty();
});
});
if (type == ElementType::EVENT_ELEMENT)
items_erase(content.events);
else
items_erase(content.sounds);
break;
case ElementType::SHADER:
animations_edit(
[&](Animation& animation, int)
{
animation_tracks_each(animation,
[&](Track& track)
{
for (auto& frame : track.frames)
if (ids.contains(frame.shaderId)) frame.shaderId = -1;
});
if (type == ElementType::EVENT_ELEMENT)
items_erase(content.events);
else
items_erase(content.sounds);
break;
case ElementType::SHADER:
animations_edit([&](Animation& animation, int) {
animation_tracks_each(animation, [&](Track& track) {
for (auto& frame : track.frames)
if (ids.contains(frame.shaderId))
frame.shaderId = -1;
});
});
items_erase(content.shaders);
break;
case ElementType::REGION:
animations_edit(
[&](Animation& animation, int)
{
tracks_each(animation.layers,
[&](Track& track, auto*)
{
auto layer = item_get(content.layers, track.id);
if (!layer || layer->spritesheetId != spritesheetId) return;
for (auto& frame : track.frames)
if (ids.contains(frame.regionId)) frame.regionId = -1;
});
items_erase(content.shaders);
break;
case ElementType::REGION:
animations_edit([&](Animation& animation, int) {
tracks_each(animation.layers, [&](Track& track, auto*) {
auto layer = item_get(content.layers, track.id);
if (!layer || layer->spritesheetId != spritesheetId)
return;
for (auto& frame : track.frames)
if (ids.contains(frame.regionId))
frame.regionId = -1;
});
});
if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) items_erase(spritesheet->regions);
break;
default:
break;
if (auto spritesheet = item_get(content.spritesheets, spritesheetId))
items_erase(spritesheet->regions);
break;
default:
break;
}
return {};
}
}
// Pastes regions into a spritesheet at a position; they get fresh ids after the existing ones.
Uids regions_paste(Model& model, int spritesheetId, const std::string& text, int insertIndex,
std::string* errorString)
{
// Pastes regions into a spritesheet at a position. They get fresh ids after the existing ones.
Uids regions_paste(Model& model, int spritesheetId, const std::string& text, int insertIndex, std::string* errorString)
{
auto spritesheet = item_get(model.content.spritesheets, spritesheetId);
if (!spritesheet) return {};
if (!spritesheet)
return {};
auto regions = items_from_string<Region>(text, errorString);
for (auto& region : regions)
region.id = item_next_id_get(spritesheet->regions) + (int)(&region - regions.data());
region.id = item_next_id_get(spritesheet->regions) + (int)(&region - regions.data());
insertIndex = std::clamp(insertIndex, 0, (int)spritesheet->regions.size());
spritesheet->regions.insert(spritesheet->regions.begin() + insertIndex, regions.begin(), regions.end());
return {};
}
}
// Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length.
Uids animation_grid_generate(Model& model, const std::vector<Reference>& tracks, const GridOptions& options)
{
// Appends grid frames to each layer track (optionally making a region per frame) and fits the animation length.
Uids animation_grid_generate(Model& model, const std::vector<Reference>& tracks, const GridOptions& options)
{
Uids uids = {};
for (auto reference : tracks)
{
if (!model.track_get(reference)) continue;
auto spritesheetId =
model.layer_spritesheet_get(reference.itemID) ? model.layer_spritesheet_get(reference.itemID)->id : -1;
auto& track = *model.track_edit(reference);
auto start = (int)track.frames.size();
frames_generate_from_grid(track, options.start, options.size, options.pivot, options.columns, options.count,
options.delay);
auto spritesheet = item_get(model.content.spritesheets, spritesheetId);
for (int i = start; i < (int)track.frames.size(); ++i)
{
auto& frame = track.frames[i];
uids.push_back(frame.uid);
if (!options.isMakeRegions || !spritesheet) continue;
auto& region =
spritesheet->regions.emplace_back(Region{.id = item_next_id_get(spritesheet->regions),
.name = region_name_get(options.regionNameFormat, i - start),
.crop = frame.crop,
.size = frame.size,
.pivot = frame.pivot});
frame.regionId = region.id;
}
auto& animation = *model.animation_edit(reference.animationIndex);
animation.frameNum = animation_length_get(animation);
if (!model.track_get(reference))
continue;
auto spritesheetId =
model.layer_spritesheet_get(reference.itemID) ? model.layer_spritesheet_get(reference.itemID)->id : -1;
auto& track = *model.track_edit(reference);
auto start = (int)track.frames.size();
frames_generate_from_grid(track, options.start, options.size, options.pivot, options.columns, options.count,
options.delay);
auto spritesheet = item_get(model.content.spritesheets, spritesheetId);
for (int i = start; i < (int)track.frames.size(); ++i)
{
auto& frame = track.frames[i];
uids.push_back(frame.uid);
if (!options.isMakeRegions || !spritesheet)
continue;
auto& region =
spritesheet->regions.emplace_back(Region{.id = item_next_id_get(spritesheet->regions),
.name = region_name_get(options.regionNameFormat, i - start),
.crop = frame.crop,
.size = frame.size,
.pivot = frame.pivot});
frame.regionId = region.id;
}
auto& animation = *model.animation_edit(reference.animationIndex);
animation.frameNum = animation_length_get(animation);
}
return uids;
}
}
// Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the
// given animations.
Uids frames_change_apply(Model& model, const ChangeTargets& targets, FrameChange change, ChangeType type)
{
// Applies a frame change to explicit frames, to whole tracks (frameIndex -1), and to every matching track of the
// given animations.
Uids frames_change_apply(Model& model, const ChangeTargets& targets, FrameChange change, ChangeType type)
{
std::map<Reference, std::set<int>> frames;
std::set<Reference> wholeTracks;
for (auto reference : targets.references)
{
auto index = std::exchange(reference.frameIndex, -1);
index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index);
auto index = std::exchange(reference.frameIndex, -1);
index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index);
}
auto is_animation_layer = [&](const Track& track)
{
auto layer = track.type == ItemType::LAYER ? item_get(model.content.layers, track.id) : nullptr;
return layer && layer->is_animation();
auto is_animation_layer = [&](const Track& track) {
auto layer = track.type == ItemType::LAYER ? item_get(model.content.layers, track.id) : nullptr;
return layer && layer->is_animation();
};
auto whole_apply = [&](Track& track)
{
std::set<int> indices;
for (int i = 0; i < (int)track.frames.size(); ++i)
indices.insert(i);
frames_change(track, change, track.type, type, indices, is_animation_layer(track));
auto whole_apply = [&](Track& track) {
std::set<int> indices;
for (int i = 0; i < (int)track.frames.size(); ++i)
indices.insert(i);
frames_change(track, change, track.type, type, indices, is_animation_layer(track));
};
for (auto& [reference, indices] : frames)
if (auto track = model.track_edit(reference))
frames_change(*track, change, track->type, type, indices, is_animation_layer(*track));
if (auto track = model.track_edit(reference))
frames_change(*track, change, track->type, type, indices, is_animation_layer(*track));
for (auto reference : wholeTracks)
if (auto track = model.track_edit(reference)) whole_apply(*track);
if (auto track = model.track_edit(reference))
whole_apply(*track);
for (auto index : targets.animations)
{
auto animation = model.animation_edit(index);
if (!animation) continue;
if (targets.isRoot) whole_apply(animation->root);
if (targets.isLayers) tracks_each(animation->layers, [&](Track& track, auto*) { whole_apply(track); });
if (targets.isNulls) tracks_each(animation->nulls, [&](Track& track, auto*) { whole_apply(track); });
auto animation = model.animation_edit(index);
if (!animation)
continue;
if (targets.isRoot)
whole_apply(animation->root);
if (targets.isLayers)
tracks_each(animation->layers, [&](Track& track, auto*) { whole_apply(track); });
if (targets.isNulls)
tracks_each(animation->nulls, [&](Track& track, auto*) { whole_apply(track); });
}
return {};
}
}
// Merges another anm2 file: content matched by name (or path for sounds) is replaced unless appending as new,
// animations are added, replaced, or merged track by track depending on the preset.
bool file_merge(Model& model, const std::filesystem::path& path, const std::filesystem::path& directory,
FileMergePreset preset)
{
// Merges another anm2 file: content matched by name (or path for sounds) is replaced unless appending as new,
// animations are added, replaced, or merged track by track depending on the preset.
bool file_merge(Model& model, const std::filesystem::path& path, const std::filesystem::path& directory,
FileMergePreset preset)
{
Model source = {};
if (!model_load(source, path) || !source.isValid) return false;
if (!model_load(source, path) || !source.isValid)
return false;
auto isAppendAsNew = preset == FILE_MERGE_PRESET_APPEND_AS_NEW;
std::map<ElementType, std::unordered_map<int, int>> remaps;
auto& content = model.content;
auto path_remap = [&](const std::filesystem::path& original)
{
if (directory.empty() || original.empty()) return original;
std::error_code ec;
auto absolute =
original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec);
if (ec) absolute = path.parent_path() / original;
auto relative = std::filesystem::relative(absolute, directory, ec);
return ec ? original : relative;
auto path_remap = [&](const std::filesystem::path& original) {
if (directory.empty() || original.empty())
return original;
std::error_code ec;
auto absolute =
original.is_absolute() ? original : std::filesystem::weakly_canonical(path.parent_path() / original, ec);
if (ec)
absolute = path.parent_path() / original;
auto relative = std::filesystem::relative(absolute, directory, ec);
return ec ? original : relative;
};
auto id_remap = [&](ElementType type, int id)
{
auto it = remaps[type].find(id);
return it == remaps[type].end() ? -1 : it->second;
auto id_remap = [&](ElementType type, int id) {
auto it = remaps[type].find(id);
return it == remaps[type].end() ? -1 : it->second;
};
auto name_find = [](auto& items, const std::string& name)
{
auto it = std::ranges::find_if(items, [&](const auto& item) { return item.name == name; });
return it == items.end() ? nullptr : &*it;
auto name_find = [](auto& items, const std::string& name) {
auto it = std::ranges::find_if(items, [&](const auto& item) { return item.name == name; });
return it == items.end() ? nullptr : &*it;
};
auto name_unique_get = [&](auto& items, const std::string& name)
{
auto candidate = name;
for (int i = 2; name_find(items, candidate); ++i)
candidate = std::format("{} {}", name, i);
return candidate;
auto name_unique_get = [&](auto& items, const std::string& name) {
auto candidate = name;
for (int i = 2; name_find(items, candidate); ++i)
candidate = std::format("{} {}", name, i);
return candidate;
};
auto named_merge = [&](auto& items, auto item)
{
auto existing = isAppendAsNew ? nullptr : name_find(items, item.name);
if (existing)
{
item.id = existing->id;
item.uid = existing->uid;
*existing = item;
auto named_merge = [&](auto& items, auto item) {
auto existing = isAppendAsNew ? nullptr : name_find(items, item.name);
if (existing)
{
item.id = existing->id;
item.uid = existing->uid;
*existing = item;
return item.id;
}
item.id = item_next_id_get(items);
if (isAppendAsNew)
item.name = name_unique_get(items, item.name);
items.push_back(item);
return item.id;
}
item.id = item_next_id_get(items);
if (isAppendAsNew) item.name = name_unique_get(items, item.name);
items.push_back(item);
return item.id;
};
auto spritesheet_import = [&](int sourceId)
{
auto& remap = remaps[ElementType::SPRITESHEET];
if (remap.contains(sourceId)) return remap[sourceId];
auto spritesheet = item_get(source.content.spritesheets, sourceId);
if (sourceId < 0 || !spritesheet) return -1;
auto imported = *spritesheet;
imported.id = item_next_id_get(content.spritesheets);
imported.path = path_remap(imported.path);
content.spritesheets.push_back(imported);
return remap[sourceId] = imported.id;
auto spritesheet_import = [&](int sourceId) {
auto& remap = remaps[ElementType::SPRITESHEET];
if (remap.contains(sourceId))
return remap[sourceId];
auto spritesheet = item_get(source.content.spritesheets, sourceId);
if (sourceId < 0 || !spritesheet)
return -1;
auto imported = *spritesheet;
imported.id = item_next_id_get(content.spritesheets);
imported.path = path_remap(imported.path);
content.spritesheets.push_back(imported);
return remap[sourceId] = imported.id;
};
// Sounds and libraries are matched by path.
auto paths_merge = [&](auto& items, const auto& sourceItems, ElementType type)
{
for (auto item : sourceItems)
{
auto sourceId = item.id;
item.path = path_remap(item.path);
auto existing = isAppendAsNew
? items.end()
: std::ranges::find_if(items, [&](const auto& other) { return other.path == item.path; });
item.id = existing != items.end() ? existing->id : item_next_id_get(items);
if (existing != items.end())
*existing = item;
else
items.push_back(item);
remaps[type][sourceId] = item.id;
}
auto paths_merge = [&](auto& items, const auto& sourceItems, ElementType type) {
for (auto item : sourceItems)
{
auto sourceId = item.id;
item.path = path_remap(item.path);
auto existing =
isAppendAsNew ? items.end()
: std::ranges::find_if(items, [&](const auto& other) { return other.path == item.path; });
item.id = existing != items.end() ? existing->id : item_next_id_get(items);
if (existing != items.end())
*existing = item;
else
items.push_back(item);
remaps[type][sourceId] = item.id;
}
};
paths_merge(content.sounds, source.content.sounds, ElementType::SOUND_ELEMENT);
paths_merge(content.libraries, source.content.libraries, ElementType::LIBRARY);
for (auto layer : source.content.layers)
{
auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name);
auto sourceId = layer.id;
layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId);
layer.libraryId = id_remap(ElementType::LIBRARY, layer.libraryId);
remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer);
auto existing = isAppendAsNew ? nullptr : name_find(content.layers, layer.name);
auto sourceId = layer.id;
layer.spritesheetId = existing ? existing->spritesheetId : spritesheet_import(layer.spritesheetId);
layer.libraryId = id_remap(ElementType::LIBRARY, layer.libraryId);
remaps[ElementType::LAYER_ELEMENT][sourceId] = named_merge(content.layers, layer);
}
for (auto null : source.content.nulls)
remaps[ElementType::NULL_ELEMENT][null.id] = named_merge(content.nulls, null);
remaps[ElementType::NULL_ELEMENT][null.id] = named_merge(content.nulls, null);
for (auto event : source.content.events)
remaps[ElementType::EVENT_ELEMENT][event.id] = named_merge(content.events, event);
remaps[ElementType::EVENT_ELEMENT][event.id] = named_merge(content.events, event);
auto track_remap = [&](Track& track)
{
for (auto& frame : track.frames)
{
for (auto& soundId : frame.soundIds)
soundId = id_remap(ElementType::SOUND_ELEMENT, soundId);
for (auto& eventId : frame.eventIds)
eventId = id_remap(ElementType::EVENT_ELEMENT, eventId);
}
};
auto entries_remap = [&](std::vector<TrackEntry>& entries, ElementType type)
{
std::vector<TrackEntry> result;
auto track_keep = [&](Track& track)
{
track.id = id_remap(type, track.id);
if (track.id < 0) return false;
track_remap(track);
return true;
};
for (auto& entry : entries)
if (auto track = std::get_if<Track>(&entry))
auto track_remap = [&](Track& track) {
for (auto& frame : track.frames)
{
if (track_keep(*track)) result.push_back(std::move(entry));
for (auto& soundId : frame.soundIds)
soundId = id_remap(ElementType::SOUND_ELEMENT, soundId);
for (auto& eventId : frame.eventIds)
eventId = id_remap(ElementType::EVENT_ELEMENT, eventId);
}
else
{
auto& group = std::get<TrackGroup>(entry);
std::erase_if(group.tracks, [&](Track& groupTrack) { return !track_keep(groupTrack); });
result.push_back(std::move(entry));
}
entries = std::move(result);
};
auto animation_build = [&](const Animation& incoming)
{
auto animation = animation_clone(incoming);
animation.extras = animation.layersExtras = animation.nullsExtras = {};
track_remap(animation.root);
track_remap(animation.triggers);
entries_remap(animation.layers, ElementType::LAYER_ELEMENT);
entries_remap(animation.nulls, ElementType::NULL_ELEMENT);
return animation;
auto entries_remap = [&](std::vector<TrackEntry>& entries, ElementType type) {
std::vector<TrackEntry> result;
auto track_keep = [&](Track& track) {
track.id = id_remap(type, track.id);
if (track.id < 0)
return false;
track_remap(track);
return true;
};
for (auto& entry : entries)
if (auto track = std::get_if<Track>(&entry))
{
if (track_keep(*track))
result.push_back(std::move(entry));
}
else
{
auto& group = std::get<TrackGroup>(entry);
std::erase_if(group.tracks, [&](Track& groupTrack) { return !track_keep(groupTrack); });
result.push_back(std::move(entry));
}
entries = std::move(result);
};
auto animation_find = [&](const std::string& name) -> int
{
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.animation_get(i)->name == name) return i;
return -1;
auto animation_build = [&](const Animation& incoming) {
auto animation = animation_clone(incoming);
animation.extras = animation.layersExtras = animation.nullsExtras = {};
track_remap(animation.root);
track_remap(animation.triggers);
entries_remap(animation.layers, ElementType::LAYER_ELEMENT);
entries_remap(animation.nulls, ElementType::NULL_ELEMENT);
return animation;
};
auto animation_find = [&](const std::string& name) -> int {
for (int i = 0; i < model.animations_count_get(); ++i)
if (model.animation_get(i)->name == name)
return i;
return -1;
};
std::string defaultAnimationName;
for (auto [index, incoming] : source.animations_get())
{
auto processed = animation_build(*incoming);
auto destination = animation_find(processed.name);
if (isAppendAsNew)
{
auto candidate = processed.name;
for (int i = 2; animation_find(candidate) != -1; ++i)
candidate = std::format("{} {}", processed.name, i);
processed.name = candidate;
}
if (incoming->name == source.animations.defaultAnimation) defaultAnimationName = processed.name;
if (destination == -1 || isAppendAsNew)
{
model.animations.entries.emplace_back(std::make_shared<const Animation>(std::move(processed)));
continue;
}
auto& target = *model.animation_edit(destination);
if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING)
{
processed.uid = target.uid;
target = std::move(processed);
continue;
}
target.isLoop = processed.isLoop;
if (!processed.root.frames.empty()) target.root = processed.root;
if (!processed.triggers.frames.empty()) target.triggers = processed.triggers;
for (auto [targetEntries, sourceEntries] :
{std::pair{&target.layers, &processed.layers}, std::pair{&target.nulls, &processed.nulls}})
{
auto nextGroupId = 0;
groups_each(*targetEntries,
[&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); });
for (auto& entry : *sourceEntries)
auto processed = animation_build(*incoming);
auto destination = animation_find(processed.name);
if (isAppendAsNew)
{
if (auto group = std::get_if<TrackGroup>(&entry))
{
auto copy = *group;
copy.id = nextGroupId++;
std::erase_if(copy.tracks,
[&](const Track& track)
{
auto existing = animation_track_get(target, (int)track.type, track.id);
if (existing && !track.frames.empty()) *existing = track;
return existing != nullptr;
});
targetEntries->push_back(std::move(copy));
continue;
}
auto& track = std::get<Track>(entry);
if (auto existing = animation_track_get(target, (int)track.type, track.id))
{
if (!track.frames.empty()) *existing = track;
}
else
targetEntries->push_back(track);
auto candidate = processed.name;
for (int i = 2; animation_find(candidate) != -1; ++i)
candidate = std::format("{} {}", processed.name, i);
processed.name = candidate;
}
}
if (incoming->name == source.animations.defaultAnimation)
defaultAnimationName = processed.name;
target.frameNum = std::max({target.frameNum, processed.frameNum, animation_length_get(target)});
if (destination == -1 || isAppendAsNew)
{
model.animations.entries.emplace_back(std::make_shared<const Animation>(std::move(processed)));
continue;
}
auto& target = *model.animation_edit(destination);
if (preset == FILE_MERGE_PRESET_REPLACE_MATCHING)
{
processed.uid = target.uid;
target = std::move(processed);
continue;
}
target.isLoop = processed.isLoop;
if (!processed.root.frames.empty())
target.root = processed.root;
if (!processed.triggers.frames.empty())
target.triggers = processed.triggers;
for (auto [targetEntries, sourceEntries] :
{std::pair{&target.layers, &processed.layers}, std::pair{&target.nulls, &processed.nulls}})
{
auto nextGroupId = 0;
groups_each(*targetEntries,
[&](const TrackGroup& group) { nextGroupId = std::max(nextGroupId, group.id + 1); });
for (auto& entry : *sourceEntries)
{
if (auto group = std::get_if<TrackGroup>(&entry))
{
auto copy = *group;
copy.id = nextGroupId++;
std::erase_if(copy.tracks, [&](const Track& track) {
auto existing = animation_track_get(target, (int)track.type, track.id);
if (existing && !track.frames.empty())
*existing = track;
return existing != nullptr;
});
targetEntries->push_back(std::move(copy));
continue;
}
auto& track = std::get<Track>(entry);
if (auto existing = animation_track_get(target, (int)track.type, track.id))
{
if (!track.frames.empty())
*existing = track;
}
else
targetEntries->push_back(track);
}
}
target.frameNum = std::max({target.frameNum, processed.frameNum, animation_length_get(target)});
}
if (model.animations.defaultAnimation.empty() && !source.animations.defaultAnimation.empty())
model.animations.defaultAnimation =
defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName;
model.animations.defaultAnimation =
defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName;
return true;
}
}
+68 -72
View File
@@ -13,28 +13,28 @@
#include "model/model.h"
// Document edits as plain functions of the model. Each returns the uids of the elements it created or changed that
// the caller may want to select (the first one is the focus); selection itself stays with the UI.
using Uids = std::vector<std::uint64_t>;
using ImageGet = std::function<const Image*(int)>;
// the caller may want to select (the first one is the focus). Selection itself stays with the UI.
using Uids = std::vector<std::uint64_t>;
using ImageGet = std::function<const Image*(int)>;
struct RowTarget
{
struct RowTarget
{
bool isGroup = false;
int type = NONE;
int id = -1;
int groupId = -1;
};
};
struct RootBakeOptions
{
struct RootBakeOptions
{
bool isRoundScale = false;
bool isRoundRotation = false;
bool isMatchRootInterpolation = false;
bool isUseRootPivot = false;
};
};
struct GridOptions
{
struct GridOptions
{
glm::ivec2 start{};
glm::ivec2 size{};
glm::vec2 pivot{};
@@ -43,28 +43,28 @@
int delay = 0;
bool isMakeRegions = false;
std::string regionNameFormat;
};
};
struct ChangeTargets
{
struct ChangeTargets
{
std::set<Reference> references;
std::set<int> animations;
bool isRoot = false;
bool isLayers = false;
bool isNulls = false;
};
};
struct AnimationTarget
{
struct AnimationTarget
{
int animationIndex = -1;
int groupId = -1;
bool isAfter = false;
bool isInto = false;
};
};
// Frame properties that can be copied on their own.
enum class FrameProperty
{
// Frame properties that can be copied on their own.
enum class FrameProperty
{
POSITION,
SCALE,
ROTATION,
@@ -85,61 +85,57 @@
EVENT,
SOUNDS,
COUNT
};
};
bool is_frame_property_valid(FrameProperty, ItemType);
void frame_property_copy(Frame&, const Frame&, FrameProperty);
Uids frames_property_set(Model&, const std::set<Reference>&, FrameProperty, const Frame&);
bool is_frame_property_valid(FrameProperty, ItemType);
void frame_property_copy(Frame&, const Frame&, FrameProperty);
Uids frames_property_set(Model&, const std::set<Reference>&, FrameProperty, const Frame&);
std::map<Reference, std::set<int>> frames_by_track_get(const std::set<Reference>&);
std::map<Reference, std::set<int>> frames_by_track_get(const std::set<Reference>&);
Uids frame_insert(Model&, Reference, int);
Uids frames_delete(Model&, const std::set<Reference>&);
Uids frames_duplicate(Model&, const std::set<Reference>&, Reference);
Uids frames_reverse(Model&, const std::set<Reference>&);
Uids frames_bake(Model&, const std::set<Reference>&, int, bool, bool);
Uids frame_split(Model&, Reference, int);
Uids frames_split(Model&, const std::set<Reference>&, int);
Uids frames_move(Model&, const std::set<Reference>&, Reference, int);
Uids frame_durations_set(Model&, const std::map<Reference, int>&);
Uids trigger_at_frame_set(Model&, Reference, int);
Uids frames_paste(Model&, Reference, const std::set<Reference>&, const std::string&, int, std::string*);
Uids root_bake_into(Model&, const std::set<Reference>&, const std::set<Reference>&, RootBakeOptions);
Uids frame_insert(Model&, Reference, int);
Uids frames_delete(Model&, const std::set<Reference>&);
Uids frames_duplicate(Model&, const std::set<Reference>&, Reference);
Uids frames_reverse(Model&, const std::set<Reference>&);
Uids frames_bake(Model&, const std::set<Reference>&, int, bool, bool);
Uids frame_split(Model&, Reference, int);
Uids frames_split(Model&, const std::set<Reference>&, int);
Uids frames_move(Model&, const std::set<Reference>&, Reference, int);
Uids frame_durations_set(Model&, const std::map<Reference, int>&);
Uids trigger_at_frame_set(Model&, Reference, int);
Uids frames_paste(Model&, Reference, const std::set<Reference>&, const std::string&, int, std::string*);
Uids root_bake_into(Model&, const std::set<Reference>&, const std::set<Reference>&, RootBakeOptions);
Uids items_remove(Model&, int, const std::map<int, std::set<int>>&, const std::map<int, std::set<int>>&);
Uids items_group(Model&, int, int, const std::set<int>&, const std::string&);
Uids items_move(Model&, int, int, const std::set<int>&, const std::set<int>&, RowTarget, bool, bool);
Uids animation_length_fit(Model&, int);
int item_add(Model&, ItemType, int, int, Layer, Null, int, Destination);
Uids items_remove(Model&, int, const std::map<int, std::set<int>>&, const std::map<int, std::set<int>>&);
Uids items_group(Model&, int, int, const std::set<int>&, const std::string&);
Uids items_move(Model&, int, int, const std::set<int>&, const std::set<int>&, RowTarget, bool, bool);
Uids animation_length_fit(Model&, int);
int item_add(Model&, ItemType, int, int, Layer, Null, int, Destination);
std::set<int> animation_group_ids_get(const Model&);
std::set<int> animation_group_indices_get(const Model&, int);
void animation_groups_remove(Model&, const std::set<int>&);
Uids animation_add(Model&, int, int, int, const std::string&);
Uids animations_remove(Model&, const std::set<int>&, const std::set<int>&);
Uids animations_move(Model&, const std::set<int>&, const std::set<int>&, AnimationTarget);
Uids animations_group(Model&, const std::set<int>&, const std::string&);
Uids animations_paste(Model&, const std::string&, int, int, std::set<int>&, std::string*);
Uids animations_merge(Model&, int, std::set<int>, Merge, bool, const std::set<int>&);
std::set<int> animation_group_ids_get(const Model&);
std::set<int> animation_group_indices_get(const Model&, int);
void animation_groups_remove(Model&, const std::set<int>&);
Uids animation_add(Model&, int, int, int, const std::string&);
Uids animations_remove(Model&, const std::set<int>&, const std::set<int>&);
Uids animations_move(Model&, const std::set<int>&, const std::set<int>&, AnimationTarget);
Uids animations_group(Model&, const std::set<int>&, const std::string&);
Uids animations_paste(Model&, const std::string&, int, int, std::set<int>&, std::string*);
Uids animations_merge(Model&, int, std::set<int>, Merge, bool, const std::set<int>&);
std::string region_name_get(const std::string&, int);
Uids regions_generate(Model&, const std::set<int>&, const std::set<Reference>&, const std::string&,
RegionFrameMapping);
Uids regions_scan(Model&);
Uids region_frames_sync(Model&);
Uids regions_paste(Model&, int, const std::string&, int, std::string*);
Uids animation_grid_generate(Model&, const std::vector<Reference>&, const GridOptions&);
Uids frames_change_apply(Model&, const ChangeTargets&, FrameChange, ChangeType);
bool regions_trim(Model&, int, const std::set<int>&, const Image&);
std::optional<Image> spritesheet_pack(Model&, int, const Image&, int);
std::optional<Image> spritesheets_merge(Model&, const std::set<int>&, const ImageGet&, bool, bool,
bool, Origin);
std::string region_name_get(const std::string&, int);
Uids regions_generate(Model&, const std::set<int>&, const std::set<Reference>&, const std::string&, RegionFrameMapping);
Uids regions_scan(Model&);
Uids region_frames_sync(Model&);
Uids regions_paste(Model&, int, const std::string&, int, std::string*);
Uids animation_grid_generate(Model&, const std::vector<Reference>&, const GridOptions&);
Uids frames_change_apply(Model&, const ChangeTargets&, FrameChange, ChangeType);
bool regions_trim(Model&, int, const std::set<int>&, const Image&);
std::optional<Image> spritesheet_pack(Model&, int, const Image&, int);
std::optional<Image> spritesheets_merge(Model&, const std::set<int>&, const ImageGet&, bool, bool, bool, Origin);
// Where a spritesheet path of a document (this one, or a library) points, from this document.
using SpritesheetPathGet = std::function<std::filesystem::path(const Model&, const std::filesystem::path&)>;
Model animation_layers_flatten(Model, const LibraryGet&, const SpritesheetPathGet&,
const std::set<int>& = {});
Uids content_remove(Model&, ElementType, const std::set<int>&, int, const LibraryGet&,
const SpritesheetPathGet&);
Model isaac_bridge(Model);
bool file_merge(Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset);
// Where a spritesheet path of a document (this one, or a library) points, from this document.
using SpritesheetPathGet = std::function<std::filesystem::path(const Model&, const std::filesystem::path&)>;
Model animation_layers_flatten(Model, const LibraryGet&, const SpritesheetPathGet&, const std::set<int>& = {});
Uids content_remove(Model&, ElementType, const std::set<int>&, int, const LibraryGet&, const SpritesheetPathGet&);
Model isaac_bridge(Model);
bool file_merge(Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset);
+121 -112
View File
@@ -7,10 +7,10 @@
#include "math_util.h"
#include "model/frames.h"
// A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and
// rotation. Skew has no place in a plain frame, and is dropped.
static Frame draw_frame_bake(const Draw& draw)
{
// A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and
// rotation. Skew has no place in a plain frame, and is dropped.
static Frame draw_frame_bake(const Draw& draw)
{
auto frame = draw.frame;
auto size = glm::max(frame.size, glm::vec2(1.0f));
auto model = draw.parent * draw_quad_model_get(draw);
@@ -28,133 +28,142 @@
frame.interpolation = Interpolation::NONE;
frame.isVisible = true;
return frame;
}
}
static bool is_frame_baked_equal(Frame a, const Frame& b)
{
static bool is_frame_baked_equal(Frame a, const Frame& b)
{
a.uid = b.uid;
a.duration = b.duration;
return a == b;
}
}
// The game's copy of a document: each animation layer's track (or only those of `layerIds`) becomes plain layer
// tracks (one per layer its child animation draws), baked a frame at a time. A library's spritesheets join the copy,
// at paths from `path_get`.
Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get,
const std::set<int>& layerIds)
{
// The game's copy of a document: each animation layer's track (or only those of `layerIds`) becomes plain layer
// tracks (one per layer its child animation draws), baked a frame at a time. A library's spritesheets join the copy,
// at paths from `path_get`.
Model animation_layers_flatten(Model model, const LibraryGet& library_get, const SpritesheetPathGet& path_get,
const std::set<int>& layerIds)
{
auto& content = model.content;
auto is_flattened = [&](const Layer& layer)
{ return layer.is_animation() && (layerIds.empty() || layerIds.contains(layer.id)); };
if (std::ranges::none_of(content.layers, is_flattened)) return model;
auto is_flattened = [&](const Layer& layer) {
return layer.is_animation() && (layerIds.empty() || layerIds.contains(layer.id));
};
if (std::ranges::none_of(content.layers, is_flattened))
return model;
std::map<std::pair<const Model*, int>, int> spritesheetIds;
auto spritesheet_id_get = [&](const Model* source, int id)
{
if (source == &model) return id;
auto [it, isNew] = spritesheetIds.try_emplace({source, id});
if (!isNew) return it->second;
auto spritesheet = item_get(source->content.spritesheets, id);
it->second = item_next_id_get(content.spritesheets);
content.spritesheets.push_back(
{.id = it->second, .path = spritesheet ? path_get(*source, spritesheet->path) : std::filesystem::path{}});
return it->second;
auto spritesheet_id_get = [&](const Model* source, int id) {
if (source == &model)
return id;
auto [it, isNew] = spritesheetIds.try_emplace({source, id});
if (!isNew)
return it->second;
auto spritesheet = item_get(source->content.spritesheets, id);
it->second = item_next_id_get(content.spritesheets);
content.spritesheets.push_back(
{.id = it->second, .path = spritesheet ? path_get(*source, spritesheet->path) : std::filesystem::path{}});
return it->second;
};
// (animation layer, source, source layer) -> the plain layer standing in for it.
std::map<std::tuple<int, const Model*, int>, int> plainIds;
auto layer_id_get = [&](const Draw& draw)
{
auto [it, isNew] = plainIds.try_emplace({draw.id, draw.source, draw.sourceId});
if (!isNew) return it->second;
auto parent = item_get(content.layers, draw.id);
auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId);
it->second = item_next_id_get(content.layers);
content.layers.push_back({.id = it->second,
.name = parent->name + "/" + (sourceLayer ? sourceLayer->name : std::string{}),
.spritesheetId = spritesheet_id_get(draw.source, draw.spritesheetId)});
return it->second;
auto layer_id_get = [&](const Draw& draw) {
auto [it, isNew] = plainIds.try_emplace({draw.id, draw.source, draw.sourceId});
if (!isNew)
return it->second;
auto parent = item_get(content.layers, draw.id);
auto sourceLayer = item_get(draw.source->content.layers, draw.sourceId);
it->second = item_next_id_get(content.layers);
content.layers.push_back({.id = it->second,
.name = parent->name + "/" + (sourceLayer ? sourceLayer->name : std::string{}),
.spritesheetId = spritesheet_id_get(draw.source, draw.spritesheetId)});
return it->second;
};
for (int index = 0; index < model.animations_count_get(); ++index)
{
// Drawn as stored, so an animation layer playing its own animation is still caught.
auto& source = *model.animation_get(index);
auto tracks_flatten = [&](const Track& track)
{
auto layer = item_get(content.layers, track.id);
if (!layer || !is_flattened(*layer)) return std::vector{track};
std::map<int, std::vector<Frame>> frames;
std::vector<int> order;
for (int time = 0; time < source.frameNum; ++time)
for (auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get}))
{
if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2()) continue;
auto id = layer_id_get(draw);
auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false});
if (isNew) order.push_back(id);
it->second[time] = draw_frame_bake(draw);
}
std::vector<Track> tracks;
for (auto id : order)
{
auto& baked = tracks.emplace_back(Track{.type = ItemType::LAYER, .id = id, .isVisible = track.isVisible});
for (auto& frame : frames[id])
if (!baked.frames.empty() && is_frame_baked_equal(frame, baked.frames.back()))
++baked.frames.back().duration;
else
baked.frames.push_back(frame);
}
return tracks;
};
std::vector<TrackEntry> entries;
for (auto& entry : source.layers)
if (auto track = std::get_if<Track>(&entry))
for (auto& flat : tracks_flatten(*track))
entries.emplace_back(std::move(flat));
else
{
auto group = std::get<TrackGroup>(entry);
group.tracks.clear();
for (auto& groupTrack : std::get<TrackGroup>(entry).tracks)
for (auto& flat : tracks_flatten(groupTrack))
group.tracks.push_back(std::move(flat));
entries.emplace_back(std::move(group));
}
// The flattened children's triggers join the animation's own, on the frames they fire (their events found by
// name).
auto triggers = source.triggers;
for (int time = 0; time < source.frameNum; ++time)
{
std::vector<int> eventIds;
for (auto& fire : animation_triggers_get(model, source, time, library_get))
{
auto layer = item_get(content.layers, fire.layerId);
if (!layer || !is_flattened(*layer)) continue;
for (auto eventId : fire.trigger.eventIds)
if (auto event = item_get(fire.source->content.events, eventId))
// Drawn as stored, so an animation layer playing its own animation is still caught.
auto& source = *model.animation_get(index);
auto tracks_flatten = [&](const Track& track) {
auto layer = item_get(content.layers, track.id);
if (!layer || !is_flattened(*layer))
return std::vector{track};
std::map<int, std::vector<Frame>> frames;
std::vector<int> order;
for (int time = 0; time < source.frameNum; ++time)
for (auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get}))
{
if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2())
continue;
auto id = layer_id_get(draw);
auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false});
if (isNew)
order.push_back(id);
it->second[time] = draw_frame_bake(draw);
}
std::vector<Track> tracks;
for (auto id : order)
{
auto existing = std::ranges::find(content.events, event->name, &Event::name);
eventIds.push_back(
existing != content.events.end()
? existing->id
: content.events.emplace_back(Event{.id = item_next_id_get(content.events), .name = event->name})
.id);
auto& baked =
tracks.emplace_back(Track{.type = ItemType::LAYER, .id = id, .isVisible = track.isVisible});
for (auto& frame : frames[id])
if (!baked.frames.empty() && is_frame_baked_equal(frame, baked.frames.back()))
++baked.frames.back().duration;
else
baked.frames.push_back(frame);
}
}
if (eventIds.empty()) continue;
auto trigger = std::ranges::find(triggers.frames, time, &Frame::atFrame);
if (trigger == triggers.frames.end())
trigger = triggers.frames.insert(triggers.frames.end(), Frame{.atFrame = time});
trigger->eventIds.insert(trigger->eventIds.end(), eventIds.begin(), eventIds.end());
}
frames_sort_by_at_frame(triggers);
return tracks;
};
auto flattened = model.animation_edit(index);
flattened->layers = std::move(entries);
flattened->triggers = std::move(triggers);
std::vector<TrackEntry> entries;
for (auto& entry : source.layers)
if (auto track = std::get_if<Track>(&entry))
for (auto& flat : tracks_flatten(*track))
entries.emplace_back(std::move(flat));
else
{
auto group = std::get<TrackGroup>(entry);
group.tracks.clear();
for (auto& groupTrack : std::get<TrackGroup>(entry).tracks)
for (auto& flat : tracks_flatten(groupTrack))
group.tracks.push_back(std::move(flat));
entries.emplace_back(std::move(group));
}
// The flattened children's triggers join the animation's own, on the frames they fire (their events found by
// name).
auto triggers = source.triggers;
for (int time = 0; time < source.frameNum; ++time)
{
std::vector<int> eventIds;
for (auto& fire : animation_triggers_get(model, source, time, library_get))
{
auto layer = item_get(content.layers, fire.layerId);
if (!layer || !is_flattened(*layer))
continue;
for (auto eventId : fire.trigger.eventIds)
if (auto event = item_get(fire.source->content.events, eventId))
{
auto existing = std::ranges::find(content.events, event->name, &Event::name);
eventIds.push_back(
existing != content.events.end()
? existing->id
: content.events
.emplace_back(Event{.id = item_next_id_get(content.events), .name = event->name})
.id);
}
}
if (eventIds.empty())
continue;
auto trigger = std::ranges::find(triggers.frames, time, &Frame::atFrame);
if (trigger == triggers.frames.end())
trigger = triggers.frames.insert(triggers.frames.end(), Frame{.atFrame = time});
trigger->eventIds.insert(trigger->eventIds.end(), eventIds.begin(), eventIds.end());
}
frames_sort_by_at_frame(triggers);
auto flattened = model.animation_edit(index);
flattened->layers = std::move(entries);
flattened->triggers = std::move(triggers);
}
std::erase_if(content.layers, is_flattened);
return model;
}
}
+300 -273
View File
@@ -7,38 +7,40 @@
#include "model/frames.h"
#include "model/xml.h"
std::map<Reference, std::set<int>> frames_by_track_get(const std::set<Reference>& frames)
{
std::map<Reference, std::set<int>> frames_by_track_get(const std::set<Reference>& frames)
{
std::map<Reference, std::set<int>> result;
for (auto frame : frames)
{
auto index = std::exchange(frame.frameIndex, -1);
result[frame].insert(index);
auto index = std::exchange(frame.frameIndex, -1);
result[frame].insert(index);
}
return result;
}
}
static Uids frames_uids_get(const Track& track, int start, int count)
{
static Uids frames_uids_get(const Track& track, int start, int count)
{
Uids uids = {};
for (int i = std::max(start, 0); i < std::min(start + count, (int)track.frames.size()); ++i)
uids.push_back(track.frames[i].uid);
uids.push_back(track.frames[i].uid);
return uids;
}
}
Uids frame_insert(Model& model, Reference reference, int time)
{
Uids frame_insert(Model& model, Reference reference, int time)
{
auto track = model.track_edit(reference);
if (!track) return {};
if (!track)
return {};
if (track->type == ItemType::TRIGGER)
{
if (std::ranges::any_of(track->frames, [&](const Frame& trigger) { return trigger.atFrame == time; })) return {};
Frame trigger = {};
trigger.atFrame = time;
track->frames.push_back(trigger);
frames_sort_by_at_frame(*track);
return {trigger.uid};
if (std::ranges::any_of(track->frames, [&](const Frame& trigger) { return trigger.atFrame == time; }))
return {};
Frame trigger = {};
trigger.atFrame = time;
track->frames.push_back(trigger);
frames_sort_by_at_frame(*track);
return {trigger.uid};
}
auto count = (int)track->frames.size();
@@ -49,286 +51,306 @@
auto index = isSource ? reference.frameIndex + 1 : count;
track->frames.insert(track->frames.begin() + index, frame);
return {frame.uid};
}
}
Uids frames_delete(Model& model, const std::set<Reference>& frames)
{
Uids frames_delete(Model& model, const std::set<Reference>& frames)
{
for (auto& [trackReference, indices] : frames_by_track_get(frames))
if (auto track = model.track_edit(trackReference))
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
if (*it >= 0 && *it < (int)track->frames.size()) track->frames.erase(track->frames.begin() + *it);
if (auto track = model.track_edit(trackReference))
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
if (*it >= 0 && *it < (int)track->frames.size())
track->frames.erase(track->frames.begin() + *it);
return {};
}
}
Uids frames_duplicate(Model& model, const std::set<Reference>& frames, Reference focus)
{
Uids frames_duplicate(Model& model, const std::set<Reference>& frames, Reference focus)
{
Uids uids = {};
std::uint64_t focusUid = 0;
for (auto& [trackReference, indices] : frames_by_track_get(frames))
{
auto track = model.track_edit(trackReference);
if (!track) continue;
auto track = model.track_edit(trackReference);
if (!track)
continue;
std::vector<Frame> copies;
int lastIndex = -1;
for (auto index : indices)
{
if (index < 0 || index >= (int)track->frames.size()) continue;
copies.push_back(frame_clone(track->frames[index]));
lastIndex = index;
auto focusTrack = focus;
focusTrack.frameIndex = -1;
if (focusTrack == trackReference && index == focus.frameIndex) focusUid = copies.back().uid;
}
if (copies.empty()) continue;
std::vector<Frame> copies;
int lastIndex = -1;
for (auto index : indices)
{
if (index < 0 || index >= (int)track->frames.size())
continue;
copies.push_back(frame_clone(track->frames[index]));
lastIndex = index;
auto focusTrack = focus;
focusTrack.frameIndex = -1;
if (focusTrack == trackReference && index == focus.frameIndex)
focusUid = copies.back().uid;
}
if (copies.empty())
continue;
for (auto& copy : copies)
uids.push_back(copy.uid);
track->frames.insert(track->frames.begin() + lastIndex + 1, copies.begin(), copies.end());
for (auto& copy : copies)
uids.push_back(copy.uid);
track->frames.insert(track->frames.begin() + lastIndex + 1, copies.begin(), copies.end());
}
if (auto it = std::ranges::find(uids, focusUid); focusUid && it != uids.end())
std::rotate(uids.begin(), it, it + 1);
std::rotate(uids.begin(), it, it + 1);
return uids;
}
}
// Reverses the selected frames of each track as one block placed where the first of them was.
Uids frames_reverse(Model& model, const std::set<Reference>& frames)
{
// Reverses the selected frames of each track as one block placed where the first of them was.
Uids frames_reverse(Model& model, const std::set<Reference>& frames)
{
for (auto& [trackReference, indices] : frames_by_track_get(frames))
{
auto track = model.track_edit(trackReference);
if (!track || indices.size() < 2) continue;
auto track = model.track_edit(trackReference);
if (!track || indices.size() < 2)
continue;
std::vector<Frame> reversed;
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
if (*it >= 0 && *it < (int)track->frames.size())
{
reversed.push_back(std::move(track->frames[*it]));
track->frames.erase(track->frames.begin() + *it);
}
auto index = std::min(*indices.begin(), (int)track->frames.size());
track->frames.insert(track->frames.begin() + index, reversed.begin(), reversed.end());
std::vector<Frame> reversed;
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
if (*it >= 0 && *it < (int)track->frames.size())
{
reversed.push_back(std::move(track->frames[*it]));
track->frames.erase(track->frames.begin() + *it);
}
auto index = std::min(*indices.begin(), (int)track->frames.size());
track->frames.insert(track->frames.begin() + index, reversed.begin(), reversed.end());
}
return {};
}
}
Uids frames_bake(Model& model, const std::set<Reference>& frames, int interval, bool isRoundScale,
bool isRoundRotation)
{
Uids frames_bake(Model& model, const std::set<Reference>& frames, int interval, bool isRoundScale, bool isRoundRotation)
{
Uids uids = {};
for (auto& [trackReference, indices] : frames_by_track_get(frames))
{
auto track = model.track_edit(trackReference);
if (!track) continue;
auto track = model.track_edit(trackReference);
if (!track)
continue;
int inserted = 0;
for (auto originalIndex : indices)
{
auto index = originalIndex + inserted;
if (index < 0 || index >= (int)track->frames.size()) continue;
auto duration = track->frames[index].duration;
auto count = duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)duration / interval);
frame_bake(*track, index, interval, isRoundScale, isRoundRotation);
uids.append_range(frames_uids_get(*track, index, count));
inserted += count - 1;
}
int inserted = 0;
for (auto originalIndex : indices)
{
auto index = originalIndex + inserted;
if (index < 0 || index >= (int)track->frames.size())
continue;
auto duration = track->frames[index].duration;
auto count = duration <= FRAME_DURATION_MIN ? 1 : (int)std::ceil((float)duration / interval);
frame_bake(*track, index, interval, isRoundScale, isRoundRotation);
uids.append_range(frames_uids_get(*track, index, count));
inserted += count - 1;
}
}
return uids;
}
}
Uids frame_split(Model& model, Reference reference, int time)
{
Uids frame_split(Model& model, Reference reference, int time)
{
auto source = model.frame_get(reference);
if (!source || reference.itemType == TRIGGER || source->duration <= 1) return {};
if (!source || reference.itemType == TRIGGER || source->duration <= 1)
return {};
auto duration = source->duration;
auto firstDuration =
time - (int)std::round(frame_time_from_index_get(*model.track_get(reference), reference.frameIndex)) + 1;
if (firstDuration <= 0 || firstDuration >= duration) return {};
if (firstDuration <= 0 || firstDuration >= duration)
return {};
auto& track = *model.track_edit(reference);
auto& frame = track.frames[reference.frameIndex];
auto split = frame_clone(frame);
split.duration = duration - firstDuration;
if (reference.frameIndex + 1 < (int)track.frames.size() && frame.interpolation != Interpolation::NONE)
frame_mix(split, track.frames[reference.frameIndex + 1],
interpolation_factor(frame.interpolation, (float)firstDuration / (float)duration));
frame_mix(split, track.frames[reference.frameIndex + 1],
interpolation_factor(frame.interpolation, (float)firstDuration / (float)duration));
frame.duration = firstDuration;
auto uid = frame.uid;
track.frames.insert(track.frames.begin() + reference.frameIndex + 1, split);
return {uid};
}
}
// Splits each of the frames that spans the time (last first, so earlier references stay valid).
Uids frames_split(Model& model, const std::set<Reference>& references, int time)
{
// Splits each of the frames that spans the time (last first, so earlier references stay valid).
Uids frames_split(Model& model, const std::set<Reference>& references, int time)
{
Uids uids = {};
for (auto it = references.rbegin(); it != references.rend(); ++it)
std::ranges::copy(frame_split(model, *it, time), std::back_inserter(uids));
std::ranges::copy(frame_split(model, *it, time), std::back_inserter(uids));
return uids;
}
}
// Moves frames (from any tracks) into one track before the frame at the given index.
Uids frames_move(Model& model, const std::set<Reference>& frames, Reference target, int insertIndex)
{
// Moves frames (from any tracks) into one track before the frame at the given index.
Uids frames_move(Model& model, const std::set<Reference>& frames, Reference target, int insertIndex)
{
target.frameIndex = -1;
auto targetTrack = model.track_get(target);
if (!targetTrack) return {};
if (!targetTrack)
return {};
auto targetUid = targetTrack->uid;
insertIndex = std::clamp(insertIndex, 0, (int)targetTrack->frames.size());
std::vector<Frame> moved;
for (auto& [trackReference, indices] : frames_by_track_get(frames))
{
auto track = model.track_edit(trackReference);
if (!track) continue;
std::vector<Frame> trackMoved;
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
{
if (*it < 0 || *it >= (int)track->frames.size()) continue;
trackMoved.insert(trackMoved.begin(), std::move(track->frames[*it]));
track->frames.erase(track->frames.begin() + *it);
if (track->uid == targetUid && *it < insertIndex) --insertIndex;
}
moved.append_range(trackMoved);
auto track = model.track_edit(trackReference);
if (!track)
continue;
std::vector<Frame> trackMoved;
for (auto it = indices.rbegin(); it != indices.rend(); ++it)
{
if (*it < 0 || *it >= (int)track->frames.size())
continue;
trackMoved.insert(trackMoved.begin(), std::move(track->frames[*it]));
track->frames.erase(track->frames.begin() + *it);
if (track->uid == targetUid && *it < insertIndex)
--insertIndex;
}
moved.append_range(trackMoved);
}
if (moved.empty()) return {};
if (moved.empty())
return {};
auto& destination = *model.track_edit(target);
insertIndex = std::clamp(insertIndex, 0, (int)destination.frames.size());
destination.frames.insert(destination.frames.begin() + insertIndex, moved.begin(), moved.end());
return frames_uids_get(destination, insertIndex, (int)moved.size());
}
}
// Triggers have an event and sounds; layer frames add a pivot, crop, size, region and shader to the others' transform.
bool is_frame_property_valid(FrameProperty property, ItemType type)
{
if (type == ItemType::TRIGGER) return property == FrameProperty::EVENT || property == FrameProperty::SOUNDS;
if (property == FrameProperty::EVENT || property == FrameProperty::SOUNDS) return false;
// Triggers have an event and sounds. Layer frames add a pivot, crop, size, region and shader to the others' transform.
bool is_frame_property_valid(FrameProperty property, ItemType type)
{
if (type == ItemType::TRIGGER)
return property == FrameProperty::EVENT || property == FrameProperty::SOUNDS;
if (property == FrameProperty::EVENT || property == FrameProperty::SOUNDS)
return false;
auto isLayerOnly = property == FrameProperty::PIVOT || property == FrameProperty::CROP ||
property == FrameProperty::SIZE || property == FrameProperty::REGION ||
property == FrameProperty::SHADER || property == FrameProperty::DEPTH ||
property == FrameProperty::BLUR || property == FrameProperty::CHILD;
return type == ItemType::LAYER || !isLayerOnly;
}
}
void frame_property_copy(Frame& target, const Frame& source, FrameProperty property)
{
void frame_property_copy(Frame& target, const Frame& source, FrameProperty property)
{
switch (property)
{
case FrameProperty::POSITION:
target.position = source.position;
break;
case FrameProperty::SCALE:
target.scale = source.scale;
break;
case FrameProperty::ROTATION:
target.rotation = source.rotation;
break;
case FrameProperty::SKEW:
target.skew = source.skew;
break;
case FrameProperty::PIVOT:
target.pivot = source.pivot;
break;
case FrameProperty::CROP:
target.crop = source.crop;
break;
case FrameProperty::SIZE:
target.size = source.size;
break;
case FrameProperty::REGION:
target.regionId = source.regionId;
target.crop = source.crop;
target.size = source.size;
target.pivot = source.pivot;
break;
case FrameProperty::TINT:
target.tint = source.tint;
break;
case FrameProperty::COLOR_OFFSET:
target.colorOffset = source.colorOffset;
break;
case FrameProperty::VISIBLE:
target.isVisible = source.isVisible;
break;
case FrameProperty::INTERPOLATION:
target.interpolation = source.interpolation;
break;
case FrameProperty::DURATION:
target.duration = source.duration;
break;
case FrameProperty::SHADER:
target.shaderId = source.shaderId;
break;
case FrameProperty::DEPTH:
target.depth = source.depth;
break;
case FrameProperty::BLUR:
target.blur = source.blur;
break;
case FrameProperty::CHILD:
target.childAnimation = source.childAnimation;
target.childMode = source.childMode;
target.childStart = source.childStart;
target.isChildStartRandom = source.isChildStartRandom;
target.isChildRestart = source.isChildRestart;
break;
case FrameProperty::EVENT:
target.eventIds = source.eventIds;
break;
case FrameProperty::SOUNDS:
target.soundIds = source.soundIds;
break;
default:
break;
case FrameProperty::POSITION:
target.position = source.position;
break;
case FrameProperty::SCALE:
target.scale = source.scale;
break;
case FrameProperty::ROTATION:
target.rotation = source.rotation;
break;
case FrameProperty::SKEW:
target.skew = source.skew;
break;
case FrameProperty::PIVOT:
target.pivot = source.pivot;
break;
case FrameProperty::CROP:
target.crop = source.crop;
break;
case FrameProperty::SIZE:
target.size = source.size;
break;
case FrameProperty::REGION:
target.regionId = source.regionId;
target.crop = source.crop;
target.size = source.size;
target.pivot = source.pivot;
break;
case FrameProperty::TINT:
target.tint = source.tint;
break;
case FrameProperty::COLOR_OFFSET:
target.colorOffset = source.colorOffset;
break;
case FrameProperty::VISIBLE:
target.isVisible = source.isVisible;
break;
case FrameProperty::INTERPOLATION:
target.interpolation = source.interpolation;
break;
case FrameProperty::DURATION:
target.duration = source.duration;
break;
case FrameProperty::SHADER:
target.shaderId = source.shaderId;
break;
case FrameProperty::DEPTH:
target.depth = source.depth;
break;
case FrameProperty::BLUR:
target.blur = source.blur;
break;
case FrameProperty::CHILD:
target.childAnimation = source.childAnimation;
target.childMode = source.childMode;
target.childStart = source.childStart;
target.isChildStartRandom = source.isChildStartRandom;
target.isChildRestart = source.isChildRestart;
break;
case FrameProperty::EVENT:
target.eventIds = source.eventIds;
break;
case FrameProperty::SOUNDS:
target.soundIds = source.soundIds;
break;
default:
break;
}
}
}
// Sets one property of the frames that have it from a source frame (a default frame clears it).
Uids frames_property_set(Model& model, const std::set<Reference>& references, FrameProperty property,
const Frame& source)
{
// Sets one property of the frames that have it from a source frame (a default frame clears it).
Uids frames_property_set(Model& model, const std::set<Reference>& references, FrameProperty property,
const Frame& source)
{
Uids uids = {};
for (auto reference : references)
if (is_frame_property_valid(property, (ItemType)reference.itemType))
if (auto frame = model.frame_edit(reference))
{
frame_property_copy(*frame, source, property);
uids.push_back(frame->uid);
}
if (is_frame_property_valid(property, (ItemType)reference.itemType))
if (auto frame = model.frame_edit(reference))
{
frame_property_copy(*frame, source, property);
uids.push_back(frame->uid);
}
return uids;
}
}
Uids frame_durations_set(Model& model, const std::map<Reference, int>& durations)
{
Uids frame_durations_set(Model& model, const std::map<Reference, int>& durations)
{
for (auto [reference, duration] : durations)
if (auto frame = model.frame_edit(reference))
frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX);
if (auto frame = model.frame_edit(reference))
frame->duration = std::clamp(duration, FRAME_DURATION_MIN, FRAME_DURATION_MAX);
return {};
}
}
// Places a trigger at a frame, stepping it back past any other trigger already there.
Uids trigger_at_frame_set(Model& model, Reference reference, int atFrame)
{
// Places a trigger at a frame, stepping it back past any other trigger already there.
Uids trigger_at_frame_set(Model& model, Reference reference, int atFrame)
{
auto trigger = model.frame_edit(reference);
if (!trigger) return {};
if (!trigger)
return {};
trigger->atFrame = atFrame;
for (auto& other : model.track_get(reference)->frames)
if (&other != trigger && other.atFrame == trigger->atFrame) trigger->atFrame--;
if (&other != trigger && other.atFrame == trigger->atFrame)
trigger->atFrame--;
return {};
}
}
// Pastes clipboard frames after the track's selected frames (or its current frame); triggers go at `time`, stepping
// past occupied frames. Frames lose regions that do not exist on the target layer.
Uids frames_paste(Model& model, Reference reference, const std::set<Reference>& selection, const std::string& text,
int time, std::string* errorString)
{
// Pastes clipboard frames after the track's selected frames (or its current frame). Triggers go at `time`, stepping
// past occupied frames. Frames lose regions that do not exist on the target layer.
Uids frames_paste(Model& model, Reference reference, const std::set<Reference>& selection, const std::string& text,
int time, std::string* errorString)
{
auto source = model.track_get(reference);
if (!source) return {};
if (!source)
return {};
auto frames = frames_from_string(text, source->type, errorString);
if (frames.empty()) return {};
if (frames.empty())
return {};
auto trackReference = reference;
trackReference.frameIndex = -1;
@@ -336,108 +358,113 @@
auto count = (int)source->frames.size();
auto insertIndex = count;
if (auto it = selected.find(trackReference); it != selected.end() && !it->second.empty())
insertIndex = std::min(count, *it->second.rbegin() + 1);
insertIndex = std::min(count, *it->second.rbegin() + 1);
else if (reference.frameIndex >= 0 && reference.frameIndex < count)
insertIndex = reference.frameIndex + 1;
insertIndex = reference.frameIndex + 1;
auto spritesheet = reference.itemType == LAYER ? model.layer_spritesheet_get(reference.itemID) : nullptr;
for (auto& frame : frames)
if (reference.itemType != LAYER && reference.itemType != TRIGGER)
{
frame.regionId = -1;
frame.crop = frame.size = frame.pivot = {};
}
else if (frame.regionId != -1 && (!spritesheet || !item_get(spritesheet->regions, frame.regionId)))
frame.regionId = -1;
if (reference.itemType != LAYER && reference.itemType != TRIGGER)
{
frame.regionId = -1;
frame.crop = frame.size = frame.pivot = {};
}
else if (frame.regionId != -1 && (!spritesheet || !item_get(spritesheet->regions, frame.regionId)))
frame.regionId = -1;
auto& track = *model.track_edit(reference);
Uids uids = {};
if (track.type != ItemType::TRIGGER)
{
track.frames.insert(track.frames.begin() + insertIndex, frames.begin(), frames.end());
return frames_uids_get(track, insertIndex, (int)frames.size());
track.frames.insert(track.frames.begin() + insertIndex, frames.begin(), frames.end());
return frames_uids_get(track, insertIndex, (int)frames.size());
}
for (int i = 0; i < (int)frames.size(); ++i)
{
auto& trigger = frames[i];
trigger.atFrame = time + i;
while (frame_index_from_at_frame_get(track, trigger.atFrame) != -1)
++trigger.atFrame;
uids.push_back(trigger.uid);
track.frames.push_back(trigger);
auto& trigger = frames[i];
trigger.atFrame = time + i;
while (frame_index_from_at_frame_get(track, trigger.atFrame) != -1)
++trigger.atFrame;
uids.push_back(trigger.uid);
track.frames.push_back(trigger);
}
frames_sort_by_at_frame(track);
return uids;
}
}
// Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root
// frames to a default frame spanning the same time.
Uids root_bake_into(Model& model, const std::set<Reference>& rootFrames, const std::set<Reference>& targets,
RootBakeOptions options)
{
// Applies the selected root frames' transforms to the target tracks' frames under them, then resets those root
// frames to a default frame spanning the same time.
Uids root_bake_into(Model& model, const std::set<Reference>& rootFrames, const std::set<Reference>& targets,
RootBakeOptions options)
{
auto byTrack = frames_by_track_get(rootFrames);
if (byTrack.size() != 1 || targets.empty()) return {};
if (byTrack.size() != 1 || targets.empty())
return {};
auto& [rootReference, rootIndices] = *byTrack.begin();
auto rootTrack = model.track_get(rootReference);
if (!rootTrack) return {};
if (!rootTrack)
return {};
auto root = *rootTrack;
std::vector<std::pair<int, int>> spans;
for (auto index : rootIndices)
if (index >= 0 && index < (int)root.frames.size())
{
auto start = (int)frame_time_from_index_get(root, index);
spans.emplace_back(start, start + root.frames[index].duration);
}
if (spans.empty()) return {};
auto is_spanned = [&](int time)
{ return std::ranges::any_of(spans, [&](auto span) { return time >= span.first && time < span.second; }); };
if (index >= 0 && index < (int)root.frames.size())
{
auto start = (int)frame_time_from_index_get(root, index);
spans.emplace_back(start, start + root.frames[index].duration);
}
if (spans.empty())
return {};
auto is_spanned = [&](int time) {
return std::ranges::any_of(spans, [&](auto span) { return time >= span.first && time < span.second; });
};
for (auto target : targets)
{
auto track = model.track_edit(target);
if (!track) continue;
auto track = model.track_edit(target);
if (!track)
continue;
if (options.isMatchRootInterpolation)
for (int index = (int)track->frames.size() - 1; index >= 0; --index)
if (is_spanned((int)frame_time_from_index_get(*track, index)))
frame_bake(*track, index, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation);
if (options.isMatchRootInterpolation)
for (int index = (int)track->frames.size() - 1; index >= 0; --index)
if (is_spanned((int)frame_time_from_index_get(*track, index)))
frame_bake(*track, index, FRAME_DURATION_MIN, options.isRoundScale, options.isRoundRotation);
for (int index = 0; index < (int)track->frames.size(); ++index)
{
auto start = (int)frame_time_from_index_get(*track, index);
if (is_spanned(start))
frame_root_transform_apply(track->frames[index], frame_generate(root, (float)start), options.isRoundScale,
options.isRoundRotation, options.isUseRootPivot);
}
for (int index = 0; index < (int)track->frames.size(); ++index)
{
auto start = (int)frame_time_from_index_get(*track, index);
if (is_spanned(start))
frame_root_transform_apply(track->frames[index], frame_generate(root, (float)start),
options.isRoundScale, options.isRoundRotation, options.isUseRootPivot);
}
}
Uids uids = {};
std::vector<Frame> rewritten;
int defaultDuration = 0;
auto default_push = [&]()
{
if (defaultDuration <= 0) return;
Frame frame = {};
frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN);
uids.push_back(frame.uid);
rewritten.push_back(frame);
defaultDuration = 0;
auto default_push = [&]() {
if (defaultDuration <= 0)
return;
Frame frame = {};
frame.duration = std::max(defaultDuration, FRAME_DURATION_MIN);
uids.push_back(frame.uid);
rewritten.push_back(frame);
defaultDuration = 0;
};
for (int index = 0; index < (int)root.frames.size(); ++index)
{
if (rootIndices.contains(index))
{
defaultDuration += root.frames[index].duration;
continue;
}
default_push();
rewritten.push_back(root.frames[index]);
if (rootIndices.contains(index))
{
defaultDuration += root.frames[index].duration;
continue;
}
default_push();
rewritten.push_back(root.frames[index]);
}
default_push();
model.track_edit(rootReference)->frames = std::move(rewritten);
return uids;
}
}
+91 -86
View File
@@ -7,108 +7,113 @@
#include "math_util.h"
#include "model/frames.h"
// An alpha offset joins the alpha tint: exact on opaque pixels, which the offset can only fade.
static void alpha_offsets_bridge(Model& model)
{
auto is_offset = [](const Frame& frame) { return float_to_uint8(frame.colorOffset.a) != 0; };
// An alpha offset joins the alpha tint: exact on opaque pixels, which the offset can only fade.
static void alpha_offsets_bridge(Model& model)
{
auto is_offset = [](const Frame& frame) {
return float_to_uint8(frame.colorOffset.a) != 0;
};
for (int i = 0; i < model.animations_count_get(); ++i)
{
auto isUsed = false;
animation_tracks_each(*model.animation_get(i),
[&](const Track& track) { isUsed |= std::ranges::any_of(track.frames, is_offset); });
if (!isUsed) continue;
animation_tracks_each(*model.animation_edit(i),
[&](Track& track)
{
if (track.type == ItemType::TRIGGER) return;
for (auto& frame : track.frames)
{
frame.tint.a = std::clamp(frame.tint.a + frame.colorOffset.a, 0.0f, 1.0f);
frame.colorOffset.a = 0.0f;
}
});
auto isUsed = false;
animation_tracks_each(*model.animation_get(i),
[&](const Track& track) { isUsed |= std::ranges::any_of(track.frames, is_offset); });
if (!isUsed)
continue;
animation_tracks_each(*model.animation_edit(i), [&](Track& track) {
if (track.type == ItemType::TRIGGER)
return;
for (auto& frame : track.frames)
{
frame.tint.a = std::clamp(frame.tint.a + frame.colorOffset.a, 0.0f, 1.0f);
frame.colorOffset.a = 0.0f;
}
});
}
}
}
// A layer frame's depth becomes a copy of its layer, named for the depth, standing where the editor draws it (the
// layer at the copy's place + depth, past the layer already there), and showing only the frames at that depth; the
// layer itself shows the rest. Groups can't stand apart in the game, so their roots go into their tracks first.
static void depths_bridge(Model& model)
{
// A layer frame's depth becomes a copy of its layer, named for the depth, standing where the editor draws it (the
// layer at the copy's place + depth, past the layer already there), and showing only the frames at that depth. The
// layer itself shows the rest. Groups can't stand apart in the game, so their roots go into their tracks first.
static void depths_bridge(Model& model)
{
auto& content = model.content;
std::map<std::pair<int, int>, int> copyIds;
auto copy_id_get = [&](int layerId, int depth)
{
auto [it, isNew] = copyIds.try_emplace({layerId, depth});
if (!isNew) return it->second;
auto layer = item_get(content.layers, layerId) ? *item_get(content.layers, layerId) : Layer{};
layer.id = item_next_id_get(content.layers);
layer.name = std::format("{} (depth {:+})", layer.name, depth);
content.layers.push_back(layer);
return it->second = layer.id;
auto copy_id_get = [&](int layerId, int depth) {
auto [it, isNew] = copyIds.try_emplace({layerId, depth});
if (!isNew)
return it->second;
auto layer = item_get(content.layers, layerId) ? *item_get(content.layers, layerId) : Layer{};
layer.id = item_next_id_get(content.layers);
layer.name = std::format("{} (depth {:+})", layer.name, depth);
content.layers.push_back(layer);
return it->second = layer.id;
};
auto is_depth = [](const Frame& frame) {
return frame.depth != 0;
};
auto is_depth = [](const Frame& frame) { return frame.depth != 0; };
for (int i = 0; i < model.animations_count_get(); ++i)
{
auto isUsed = false;
tracks_each(model.animation_get(i)->layers,
[&](const Track& track, auto*) { isUsed |= std::ranges::any_of(track.frames, is_depth); });
if (!isUsed) continue;
auto& animation = *model.animation_edit(i);
auto isUsed = false;
tracks_each(model.animation_get(i)->layers,
[&](const Track& track, auto*) { isUsed |= std::ranges::any_of(track.frames, is_depth); });
if (!isUsed)
continue;
auto& animation = *model.animation_edit(i);
std::vector<Track> tracks;
for (auto& entry : animation.layers)
if (auto track = std::get_if<Track>(&entry))
tracks.push_back(std::move(*track));
else
{
auto& group = std::get<TrackGroup>(entry);
for (auto& groupTrack : group.tracks)
{
track_group_root_bake(groupTrack, group.root, animation.frameNum);
groupTrack.isVisible = groupTrack.isVisible && group.isVisible;
tracks.push_back(std::move(groupTrack));
}
}
std::vector<Track> tracks;
for (auto& entry : animation.layers)
if (auto track = std::get_if<Track>(&entry))
tracks.push_back(std::move(*track));
else
{
auto& group = std::get<TrackGroup>(entry);
for (auto& groupTrack : group.tracks)
{
track_group_root_bake(groupTrack, group.root, animation.frameNum);
groupTrack.isVisible = groupTrack.isVisible && group.isVisible;
tracks.push_back(std::move(groupTrack));
}
}
// Each track's place in drawing order: (its position + depth, depth), kept in position order when equal.
std::vector<std::pair<std::pair<int, int>, Track>> placed;
auto shown_set = [](Track& track, int depth)
{
for (auto& frame : track.frames)
// Each track's place in drawing order: (its position + depth, depth), kept in position order when equal.
std::vector<std::pair<std::pair<int, int>, Track>> placed;
auto shown_set = [](Track& track, int depth) {
for (auto& frame : track.frames)
{
frame.isVisible = frame.isVisible && frame.depth == depth;
frame.depth = 0;
}
};
for (int position = 0; position < (int)tracks.size(); ++position)
{
frame.isVisible = frame.isVisible && frame.depth == depth;
frame.depth = 0;
auto& track = tracks[position];
std::set<int> depths;
for (auto& frame : track.frames)
if (frame.depth != 0)
depths.insert(frame.depth);
for (auto depth : depths)
{
auto copy = track;
copy.id = copy_id_get(track.id, depth);
shown_set(copy, depth);
placed.push_back({{position + depth, depth}, std::move(copy)});
}
shown_set(track, 0);
placed.push_back({{position, 0}, std::move(track)});
}
};
for (int position = 0; position < (int)tracks.size(); ++position)
{
auto& track = tracks[position];
std::set<int> depths;
for (auto& frame : track.frames)
if (frame.depth != 0) depths.insert(frame.depth);
for (auto depth : depths)
{
auto copy = track;
copy.id = copy_id_get(track.id, depth);
shown_set(copy, depth);
placed.push_back({{position + depth, depth}, std::move(copy)});
}
shown_set(track, 0);
placed.push_back({{position, 0}, std::move(track)});
}
std::ranges::stable_sort(placed, {}, &std::pair<std::pair<int, int>, Track>::first);
animation.layers.clear();
for (auto& [order, track] : placed)
animation.layers.emplace_back(std::move(track));
std::ranges::stable_sort(placed, {}, &std::pair<std::pair<int, int>, Track>::first);
animation.layers.clear();
for (auto& [order, track] : placed)
animation.layers.emplace_back(std::move(track));
}
}
}
// The game's copy with what the game can't show worked around (Convert and Save).
Model isaac_bridge(Model model)
{
// The game's copy with what the game can't show worked around (Convert and Save).
Model isaac_bridge(Model model)
{
alpha_offsets_bridge(model);
depths_bridge(model);
return model;
}
}
+125 -115
View File
@@ -10,110 +10,117 @@
#include "path.h"
// Spritesheet pixel edits: the model changes in place, and a new image is returned for the document to store.
bool regions_trim(Model& model, int spritesheetId, const std::set<int>& ids, const Image& source)
{
bool regions_trim(Model& model, int spritesheetId, const std::set<int>& ids, const Image& source)
{
auto spritesheet = item_get(model.content.spritesheets, spritesheetId);
if (!spritesheet || !source.is_valid() || source.pixels.empty()) return false;
if (!spritesheet || !source.is_valid() || source.pixels.empty())
return false;
bool isChanged = false;
for (auto id : ids)
{
auto region = item_get(spritesheet->regions, id);
if (!region) continue;
auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0));
auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), source.size);
auto contentMin = glm::ivec2(std::numeric_limits<int>::max());
auto contentMax = glm::ivec2(std::numeric_limits<int>::min());
for (int y = minPoint.y; y < maxPoint.y; ++y)
for (int x = minPoint.x; x < maxPoint.x; ++x)
{
auto index = ((std::size_t)y * source.size.x + x) * IMAGE_CHANNELS;
if (index + IMAGE_CHANNELS > source.pixels.size()) continue;
if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + IMAGE_CHANNELS,
[](auto channel) { return channel == 0; }))
auto region = item_get(spritesheet->regions, id);
if (!region)
continue;
contentMin = glm::min(contentMin, glm::ivec2(x, y));
contentMax = glm::max(contentMax, glm::ivec2(x, y));
}
if (contentMin.x == std::numeric_limits<int>::max()) continue;
auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0));
auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), source.size);
auto contentMin = glm::ivec2(std::numeric_limits<int>::max());
auto contentMax = glm::ivec2(std::numeric_limits<int>::min());
auto newCrop = glm::vec2(contentMin);
auto newSize = glm::vec2(contentMax - contentMin + 1);
if (region->crop == newCrop && region->size == newSize) continue;
for (int y = minPoint.y; y < maxPoint.y; ++y)
for (int x = minPoint.x; x < maxPoint.x; ++x)
{
auto index = ((std::size_t)y * source.size.x + x) * IMAGE_CHANNELS;
if (index + IMAGE_CHANNELS > source.pixels.size())
continue;
if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + IMAGE_CHANNELS,
[](auto channel) { return channel == 0; }))
continue;
contentMin = glm::min(contentMin, glm::ivec2(x, y));
contentMax = glm::max(contentMax, glm::ivec2(x, y));
}
auto previousCrop = region->crop;
region->crop = newCrop;
region->size = newSize;
if (region->origin == Origin::TOP_LEFT)
region->pivot = {};
else if (region->origin == Origin::CENTER)
region->pivot = region->size * 0.5f;
else
region->pivot -= region->crop - previousCrop;
isChanged = true;
if (contentMin.x == std::numeric_limits<int>::max())
continue;
auto newCrop = glm::vec2(contentMin);
auto newSize = glm::vec2(contentMax - contentMin + 1);
if (region->crop == newCrop && region->size == newSize)
continue;
auto previousCrop = region->crop;
region->crop = newCrop;
region->size = newSize;
if (region->origin == Origin::TOP_LEFT)
region->pivot = {};
else if (region->origin == Origin::CENTER)
region->pivot = region->size * 0.5f;
else
region->pivot -= region->crop - previousCrop;
isChanged = true;
}
return isChanged;
}
}
std::optional<Image> spritesheet_pack(Model& model, int id, const Image& sheet, int padding)
{
std::optional<Image> spritesheet_pack(Model& model, int id, const Image& sheet, int padding)
{
struct PackItem
{
int regionId = -1;
glm::ivec2 source{};
glm::ivec2 size{};
int regionId = -1;
glm::ivec2 source{};
glm::ivec2 size{};
};
auto spritesheet = item_get(model.content.spritesheets, id);
if (!spritesheet || !sheet.is_valid() || sheet.pixels.empty()) return {};
if (!spritesheet || !sheet.is_valid() || sheet.pixels.empty())
return {};
padding = std::max(0, padding);
std::vector<PackItem> items;
for (auto& region : spritesheet->regions)
{
auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size));
auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size));
items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))});
auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size));
auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size));
items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))});
}
std::sort(items.begin(), items.end(),
[](const PackItem& a, const PackItem& b)
{
auto areaA = a.size.x * a.size.y;
auto areaB = b.size.x * b.size.y;
return areaA != areaB ? areaA > areaB : a.regionId < b.regionId;
});
std::sort(items.begin(), items.end(), [](const PackItem& a, const PackItem& b) {
auto areaA = a.size.x * a.size.y;
auto areaB = b.size.x * b.size.y;
return areaA != areaB ? areaA > areaB : a.regionId < b.regionId;
});
std::vector<glm::ivec2> sizes{};
for (auto& item : items)
sizes.push_back(item.size + padding * 2);
sizes.push_back(item.size + padding * 2);
glm::ivec2 packedSize{};
std::vector<glm::ivec2> positions{};
if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return {};
if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0)
return {};
std::vector<ImagePart> parts;
for (int i = 0; i < (int)items.size(); ++i)
parts.push_back({&sheet, items[i].source, items[i].size, positions[i] + padding});
parts.push_back({&sheet, items[i].source, items[i].size, positions[i] + padding});
for (auto& region : spritesheet->regions)
for (int i = 0; i < (int)items.size(); ++i)
if (items[i].regionId == region.id) region.crop = parts[i].destination;
for (int i = 0; i < (int)items.size(); ++i)
if (items[i].regionId == region.id)
region.crop = parts[i].destination;
return Image::compose(parts, packedSize, sheet.is_vector());
}
}
// Appends sheets to the first, right or below. The result is an SVG (holding any PNG sheets as images) when any of
// them is one; the first sheet's path takes the result's extension.
std::optional<Image> spritesheets_merge(Model& model, const std::set<int>& ids, const ImageGet& image_get,
bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion,
Origin origin)
{
if (ids.size() < 2) return {};
// Appends sheets to the first, right or below. The result is an SVG (holding any PNG sheets as images) when any of
// them is one. The first sheet's path takes the result's extension.
std::optional<Image> spritesheets_merge(Model& model, const std::set<int>& ids, const ImageGet& image_get,
bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, Origin origin)
{
if (ids.size() < 2)
return {};
for (auto id : ids)
if (!item_get(model.content.spritesheets, id) || !image_get(id) || !image_get(id)->is_valid()) return {};
if (!item_get(model.content.spritesheets, id) || !image_get(id) || !image_get(id)->is_valid())
return {};
auto baseId = *ids.begin();
auto base = item_get(model.content.spritesheets, baseId);
@@ -121,67 +128,70 @@
std::vector<ImagePart> parts{{image_get(baseId), {}, mergedSize, {}}};
std::unordered_map<int, std::unordered_map<int, int>> regionIdMap;
auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size)
{
auto source = item_get(model.content.spritesheets, sourceId);
Region region = {};
region.id = item_next_id_get(base->regions);
auto stem = path_to_utf8(source->path.stem());
region.name = stem.empty() ? std::format("#{}", sourceId) : stem;
region.crop = crop;
region.size = size;
region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2();
region.origin = origin;
base->regions.push_back(region);
auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) {
auto source = item_get(model.content.spritesheets, sourceId);
Region region = {};
region.id = item_next_id_get(base->regions);
auto stem = path_to_utf8(source->path.stem());
region.name = stem.empty() ? std::format("#{}", sourceId) : stem;
region.crop = crop;
region.size = size;
region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2();
region.origin = origin;
base->regions.push_back(region);
};
if (isMakeRegions && isMakePrimaryRegion) location_region_add(baseId, {}, mergedSize);
if (isMakeRegions && isMakePrimaryRegion)
location_region_add(baseId, {}, mergedSize);
for (auto id : ids)
{
if (id == baseId) continue;
auto texture = image_get(id);
auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y);
mergedSize = isAppendRight ? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y))
: glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y);
parts.push_back({texture, {}, texture->size, offset});
if (!isMakeRegions) continue;
if (id == baseId)
continue;
auto texture = image_get(id);
auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y);
mergedSize = isAppendRight
? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y))
: glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y);
parts.push_back({texture, {}, texture->size, offset});
if (!isMakeRegions)
continue;
location_region_add(id, offset, texture->size);
for (auto sourceRegion : item_get(model.content.spritesheets, id)->regions)
{
auto sourceRegionId = sourceRegion.id;
sourceRegion.id = item_next_id_get(base->regions);
sourceRegion.uid = uid_next();
sourceRegion.crop += offset;
base->regions.push_back(sourceRegion);
regionIdMap[id][sourceRegionId] = sourceRegion.id;
}
location_region_add(id, offset, texture->size);
for (auto sourceRegion : item_get(model.content.spritesheets, id)->regions)
{
auto sourceRegionId = sourceRegion.id;
sourceRegion.id = item_next_id_get(base->regions);
sourceRegion.uid = uid_next();
sourceRegion.crop += offset;
base->regions.push_back(sourceRegion);
regionIdMap[id][sourceRegionId] = sourceRegion.id;
}
}
std::unordered_map<int, int> layerSpritesheetBefore;
for (auto& layer : model.content.layers)
if (ids.contains(layer.spritesheetId))
{
layerSpritesheetBefore[layer.id] = layer.spritesheetId;
layer.spritesheetId = baseId;
}
if (ids.contains(layer.spritesheetId))
{
layerSpritesheetBefore[layer.id] = layer.spritesheetId;
layer.spritesheetId = baseId;
}
for (int i = 0; i < model.animations_count_get(); ++i)
tracks_each(model.animation_edit(i)->layers,
[&](Track& track, auto*)
{
auto before = layerSpritesheetBefore.find(track.id);
if (before == layerSpritesheetBefore.end() || before->second == baseId) return;
auto& remap = regionIdMap[before->second];
for (auto& frame : track.frames)
if (frame.regionId != -1)
frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1;
});
tracks_each(model.animation_edit(i)->layers, [&](Track& track, auto*) {
auto before = layerSpritesheetBefore.find(track.id);
if (before == layerSpritesheetBefore.end() || before->second == baseId)
return;
auto& remap = regionIdMap[before->second];
for (auto& frame : track.frames)
if (frame.regionId != -1)
frame.regionId = remap.contains(frame.regionId) ? remap.at(frame.regionId) : -1;
});
auto isVector = std::ranges::any_of(parts, [](const ImagePart& part) { return part.image->is_vector(); });
if (isVector != is_path_extension(base->path, SVG_EXTENSION))
base->path.replace_extension(isVector ? SVG_EXTENSION : PNG_EXTENSION);
std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet)
{ return spritesheet.id != baseId && ids.contains(spritesheet.id); });
base->path.replace_extension(isVector ? SVG_EXTENSION : PNG_EXTENSION);
std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet) {
return spritesheet.id != baseId && ids.contains(spritesheet.id);
});
return Image::compose(parts, mergedSize, isVector);
}
}
+134 -128
View File
@@ -1,42 +1,44 @@
#include "edit/edit.h"
static std::vector<TrackEntry>* track_entries_edit(Model& model, int animationIndex, int type)
{
if (type != LAYER && type != NULL_) return nullptr;
static std::vector<TrackEntry>* track_entries_edit(Model& model, int animationIndex, int type)
{
if (type != LAYER && type != NULL_)
return nullptr;
auto animation = model.animation_edit(animationIndex);
return animation ? &animation_entries_get(*animation, type) : nullptr;
}
}
Uids items_remove(Model& model, int animationIndex, const std::map<int, std::set<int>>& ids,
const std::map<int, std::set<int>>& groupIds)
{
Uids items_remove(Model& model, int animationIndex, const std::map<int, std::set<int>>& ids,
const std::map<int, std::set<int>>& groupIds)
{
for (auto type : {LAYER, NULL_})
{
auto typeIds = ids.contains(type) ? ids.at(type) : std::set<int>{};
auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set<int>{};
if (typeIds.empty() && typeGroupIds.empty()) continue;
auto entries = track_entries_edit(model, animationIndex, type);
if (!entries) continue;
auto typeIds = ids.contains(type) ? ids.at(type) : std::set<int>{};
auto typeGroupIds = groupIds.contains(type) ? groupIds.at(type) : std::set<int>{};
if (typeIds.empty() && typeGroupIds.empty())
continue;
auto entries = track_entries_edit(model, animationIndex, type);
if (!entries)
continue;
std::erase_if(*entries,
[&](TrackEntry& entry)
{
if (auto group = std::get_if<TrackGroup>(&entry))
{
std::erase_if(group->tracks, [&](const Track& track) { return typeIds.contains(track.id); });
return typeGroupIds.contains(group->id);
}
return typeIds.contains(std::get<Track>(entry).id);
});
std::erase_if(*entries, [&](TrackEntry& entry) {
if (auto group = std::get_if<TrackGroup>(&entry))
{
std::erase_if(group->tracks, [&](const Track& track) { return typeIds.contains(track.id); });
return typeGroupIds.contains(group->id);
}
return typeIds.contains(std::get<Track>(entry).id);
});
}
return {};
}
}
// Wraps ungrouped tracks in a new group placed where the first of them was.
Uids items_group(Model& model, int animationIndex, int type, const std::set<int>& ids, const std::string& name)
{
// Wraps ungrouped tracks in a new group placed where the first of them was.
Uids items_group(Model& model, int animationIndex, int type, const std::set<int>& ids, const std::string& name)
{
auto entries = track_entries_edit(model, animationIndex, type);
if (!entries) return {};
if (!entries)
return {};
int nextId = 0;
groups_each(*entries, [&](const TrackGroup& group) { nextId = std::max(nextId, group.id + 1); });
@@ -45,153 +47,157 @@
auto insertIndex = -1;
for (int i = 0; i < (int)entries->size(); ++i)
{
auto track = std::get_if<Track>(&(*entries)[i]);
if (!track || !ids.contains(track->id)) continue;
if (insertIndex == -1) insertIndex = i;
group.tracks.push_back(std::move(*track));
entries->erase(entries->begin() + i--);
auto track = std::get_if<Track>(&(*entries)[i]);
if (!track || !ids.contains(track->id))
continue;
if (insertIndex == -1)
insertIndex = i;
group.tracks.push_back(std::move(*track));
entries->erase(entries->begin() + i--);
}
if (insertIndex == -1) return {};
if (insertIndex == -1)
return {};
auto uid = group.uid;
entries->insert(entries->begin() + insertIndex, std::move(group));
return {uid};
}
}
// Moves tracks and whole groups next to (or into) a target row. Layers are listed bottom-up, so for them "after" on
// screen is "before" in the file.
Uids items_move(Model& model, int animationIndex, int type, const std::set<int>& ids, const std::set<int>& groupIds,
RowTarget target, bool isDropAfter, bool isDropIntoGroup)
{
if (target.groupId != -1 && groupIds.contains(target.groupId)) return {};
if (target.isGroup && groupIds.contains(target.id)) return {};
// Moves tracks and whole groups next to (or into) a target row. Layers are listed bottom-up, so for them "after" on
// screen is "before" in the file.
Uids items_move(Model& model, int animationIndex, int type, const std::set<int>& ids, const std::set<int>& groupIds,
RowTarget target, bool isDropAfter, bool isDropIntoGroup)
{
if (target.groupId != -1 && groupIds.contains(target.groupId))
return {};
if (target.isGroup && groupIds.contains(target.id))
return {};
auto entries = track_entries_edit(model, animationIndex, type);
if (!entries) return {};
if (!entries)
return {};
std::vector<Track> movedTracks;
std::vector<TrackEntry> movedGroups;
std::erase_if(*entries,
[&](TrackEntry& entry)
{
if (auto group = std::get_if<TrackGroup>(&entry))
{
if (groupIds.contains(group->id))
{
movedGroups.push_back(std::move(entry));
return true;
}
std::erase_if(group->tracks,
[&](Track& track)
{
if (!ids.contains(track.id)) return false;
movedTracks.push_back(std::move(track));
return true;
});
return false;
}
auto& track = std::get<Track>(entry);
if (!ids.contains(track.id)) return false;
movedTracks.push_back(std::move(track));
return true;
});
if (movedTracks.empty() && movedGroups.empty()) return {};
std::erase_if(*entries, [&](TrackEntry& entry) {
if (auto group = std::get_if<TrackGroup>(&entry))
{
if (groupIds.contains(group->id))
{
movedGroups.push_back(std::move(entry));
return true;
}
std::erase_if(group->tracks, [&](Track& track) {
if (!ids.contains(track.id))
return false;
movedTracks.push_back(std::move(track));
return true;
});
return false;
}
auto& track = std::get<Track>(entry);
if (!ids.contains(track.id))
return false;
movedTracks.push_back(std::move(track));
return true;
});
if (movedTracks.empty() && movedGroups.empty())
return {};
auto isAfter = type == LAYER ? !isDropAfter : isDropAfter;
auto group_find = [&](int groupId)
{
return std::ranges::find_if(*entries,
[&](const TrackEntry& entry)
{
auto group = std::get_if<TrackGroup>(&entry);
return group && group->id == groupId;
});
auto group_find = [&](int groupId) {
return std::ranges::find_if(*entries, [&](const TrackEntry& entry) {
auto group = std::get_if<TrackGroup>(&entry);
return group && group->id == groupId;
});
};
// Where top-level items go: beside the target row, or beside the group that holds it.
auto topIndex = (int)entries->size();
if (target.isGroup || target.groupId != -1)
{
auto group = group_find(target.isGroup ? target.id : target.groupId);
if (group != entries->end()) topIndex = (int)(group - entries->begin()) + isAfter;
auto group = group_find(target.isGroup ? target.id : target.groupId);
if (group != entries->end())
topIndex = (int)(group - entries->begin()) + isAfter;
}
else if (target.type == type)
{
auto track = std::ranges::find_if(*entries,
[&](const TrackEntry& entry)
{
auto track = std::get_if<Track>(&entry);
return track && track->id == target.id;
});
if (track != entries->end()) topIndex = (int)(track - entries->begin()) + isAfter;
auto track = std::ranges::find_if(*entries, [&](const TrackEntry& entry) {
auto track = std::get_if<Track>(&entry);
return track && track->id == target.id;
});
if (track != entries->end())
topIndex = (int)(track - entries->begin()) + isAfter;
}
auto intoGroupId = target.isGroup && isDropIntoGroup ? target.id : !target.isGroup ? target.groupId : -1;
auto intoGroup = intoGroupId == -1 ? entries->end() : group_find(intoGroupId);
if (intoGroup != entries->end())
{
// Into a group header lands just under it on screen; beside a grouped track lands beside it.
auto& tracks = std::get<TrackGroup>(*intoGroup).tracks;
auto beside = std::ranges::find_if(tracks, [&](const Track& track) { return track.id == target.id; });
auto position = target.isGroup ? (type == LAYER ? tracks.end() : tracks.begin())
: beside != tracks.end() ? beside + isAfter
: tracks.end();
tracks.insert(position, std::make_move_iterator(movedTracks.begin()), std::make_move_iterator(movedTracks.end()));
movedTracks.clear();
// Into a group header lands just under it on screen. Beside a grouped track lands beside it.
auto& tracks = std::get<TrackGroup>(*intoGroup).tracks;
auto beside = std::ranges::find_if(tracks, [&](const Track& track) { return track.id == target.id; });
auto position = target.isGroup ? (type == LAYER ? tracks.end() : tracks.begin())
: beside != tracks.end() ? beside + isAfter
: tracks.end();
tracks.insert(position, std::make_move_iterator(movedTracks.begin()),
std::make_move_iterator(movedTracks.end()));
movedTracks.clear();
}
std::vector<TrackEntry> topMoved;
for (auto& track : movedTracks)
topMoved.emplace_back(std::move(track));
topMoved.emplace_back(std::move(track));
topMoved.insert(topMoved.end(), std::make_move_iterator(movedGroups.begin()),
std::make_move_iterator(movedGroups.end()));
entries->insert(entries->begin() + std::clamp(topIndex, 0, (int)entries->size()),
std::make_move_iterator(topMoved.begin()), std::make_move_iterator(topMoved.end()));
return {};
}
}
Uids animation_length_fit(Model& model, int animationIndex)
{
if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = animation_length_get(*animation);
Uids animation_length_fit(Model& model, int animationIndex)
{
if (auto animation = model.animation_edit(animationIndex))
animation->frameNum = animation_length_get(*animation);
return {};
}
}
// Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation.
// Adds track `id` (a new item, from `layer` or `null`, at -1) to an animation or all of them.
int item_add(Model& model, ItemType type, int animationIndex, int id, Layer layer, Null null, int insertBeforeId,
Destination destination)
{
// Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation.
// Adds track `id` (a new item, from `layer` or `null`, at -1) to an animation or all of them.
int item_add(Model& model, ItemType type, int animationIndex, int id, Layer layer, Null null, int insertBeforeId,
Destination destination)
{
auto& content = model.content;
auto item_insert = [&](auto& items, auto item)
{
if (id == -1) id = item_next_id_get(items);
if (item_get(items, id)) return;
item.id = id;
items.push_back(item);
auto item_insert = [&](auto& items, auto item) {
if (id == -1)
id = item_next_id_get(items);
if (item_get(items, id))
return;
item.id = id;
items.push_back(item);
};
if (!item_get(content.spritesheets, layer.spritesheetId)) layer.spritesheetId = 0;
if (!item_get(content.spritesheets, layer.spritesheetId))
layer.spritesheetId = 0;
if (type == ItemType::LAYER)
item_insert(content.layers, layer);
item_insert(content.layers, layer);
else if (type == ItemType::NULL_)
item_insert(content.nulls, null);
item_insert(content.nulls, null);
else
return -1;
return -1;
auto add = [&](int index)
{
if (model.track_get({index, (int)type, id})) return;
auto& entries = animation_entries_get(*model.animation_edit(index), (int)type);
auto before = std::ranges::find_if(entries,
[&](const TrackEntry& entry)
{
auto track = std::get_if<Track>(&entry);
return track && track->id == insertBeforeId;
});
entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id});
auto add = [&](int index) {
if (model.track_get({index, (int)type, id}))
return;
auto& entries = animation_entries_get(*model.animation_edit(index), (int)type);
auto before = std::ranges::find_if(entries, [&](const TrackEntry& entry) {
auto track = std::get_if<Track>(&entry);
return track && track->id == insertBeforeId;
});
entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id});
};
if (destination == DESTINATION_ALL)
for (int i = 0; i < model.animations_count_get(); ++i)
add(i);
for (int i = 0; i < model.animations_count_get(); ++i)
add(i);
else if (model.animation_get(animationIndex))
add(animationIndex);
add(animationIndex);
return id;
}
}