载入中...
搜索中...
未找到
AnimationClipEditor.cpp
浏览该文件的文档.
2#include "common/Assert.h"
3
4#if defined(EVE_ANIMATION_EDITOR_RUNTIME)
8#endif
11
12#include <algorithm>
13#include <cmath>
14#include <cstdint>
15#include <numbers>
16#include <set>
17#include <utility>
18
20namespace {
21
22template <class T = void>
24 std::string message) {
25 return eve::editing::failed<T>(status, animation_editing::RuleId(std::move(rule)), std::move(message));
26}
27
28animation_editing::EditorValue keyValue(const char* id, double time, double px, double py, double pz) {
30 {"id", std::string(id)}, {"time", time}, {"px", px}, {"py", py}, {"pz", pz},
31 {"rx", 0.0}, {"ry", 0.0}, {"rz", 0.0}, {"rw", 1.0}, {"sx", 1.0},
32 {"sy", 1.0}, {"sz", 1.0}};
33}
34
35animation_editing::EditorValue trackValue(const char* id, const char* bone,
38 {"id", std::string(id)}, {"bone", std::string(bone)}, {"keys", std::move(keys)}};
39}
40
41} // namespace
42
44 : target_(std::move(targetId)), authority_(&target_), transactions_(&authority_) {
45 initializePreview();
46 skeleton_ = {{"Hips", {}}, {"Spine", "Hips"}, {"Chest", "Spine"}, {"Head", "Chest"},
47 {"LeftArm", "Chest"}, {"RightArm", "Chest"}};
48 seedPreviewClip();
49 auto previewed = refreshPreview();
50 if (!previewed.ok())
51 previewed.ignore("animation clip editor keeps an empty overlay when the seeded preview is rejected");
52}
53
54#if defined(EVE_ANIMATION_EDITOR_RUNTIME)
57 if (skeleton.getBoneCount() <= 0 || clip.getDuration() <= 0.0f)
58 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.runtime-source",
59 "Runtime skeleton and clip must contain bones and a positive duration");
61 std::vector<SkeletonBone> candidateSkeleton;
63 for (int bone = 0; bone < skeleton.getBoneCount(); ++bone) {
64 const std::string name = skeleton.getBoneName(bone);
65 const int parent = skeleton.getParent(bone);
66 candidateSkeleton.push_back({name, parent >= 0 ? skeleton.getBoneName(parent) : std::string{}});
67 std::set<double> times;
68 for (int key = 0; key < clip.getPositionKeyCount(bone); ++key) times.insert(clip.getPositionKeyTime(bone, key));
69 for (int key = 0; key < clip.getRotationKeyCount(bone); ++key) times.insert(clip.getRotationKeyTime(bone, key));
70 for (int key = 0; key < clip.getScaleKeyCount(bone); ++key) times.insert(clip.getScaleKeyTime(bone, key));
71 if (times.empty()) times.insert(0.0);
73 int keyIndex = 0;
74 for (const double time : times) {
75 clip.sample(static_cast<float>(time), &pose, &skeleton);
77 {"id", "runtime-key:" + std::to_string(bone) + ":" + std::to_string(keyIndex++)},
78 {"time", time},
79 {"px", static_cast<double>(pose.getLocalPositionX(bone))},
80 {"py", static_cast<double>(pose.getLocalPositionY(bone))},
81 {"pz", static_cast<double>(pose.getLocalPositionZ(bone))},
82 {"rx", static_cast<double>(pose.getLocalRotationX(bone))},
83 {"ry", static_cast<double>(pose.getLocalRotationY(bone))},
84 {"rz", static_cast<double>(pose.getLocalRotationZ(bone))},
85 {"rw", static_cast<double>(pose.getLocalRotationW(bone))},
86 {"sx", static_cast<double>(pose.getLocalScaleX(bone))},
87 {"sy", static_cast<double>(pose.getLocalScaleY(bone))},
88 {"sz", static_cast<double>(pose.getLocalScaleZ(bone))}});
89 }
90 tracks.push_back(trackValue(("runtime-track:" + std::to_string(bone)).c_str(), name.c_str(), std::move(keys)));
91 }
93 root["schemaVersion"] = std::int64_t{1};
94 root["settings"] = animation_editing::EditorValue::Object{{"duration", static_cast<double>(clip.getDuration())},
95 {"sampleRate", static_cast<double>(clip.getSampleRate())},
96 {"loop", clip.getLoop()}};
97 root["tracks"] = std::move(tracks); root["events"] = animation_editing::EditorValue::Array{};
99 auto loaded = target_.loadSnapshot(animation_editing::EditorValue(std::move(root)));
100 if (!loaded.ok()) return loaded;
101 skeleton_ = std::move(candidateSkeleton);
102 selectedBone_ = skeleton_.front().name; selectedKeyId_ = animation_editing::StableId();
103 playhead_ = 0.0; playing_ = false;
104 return refreshPreview();
105}
106
107animation_editing::Result<void> AnimationClipEditor::writeRuntimeClip(
108 animation::AnimClip& clip, const animation::AnimSkeleton& skeleton) const {
109 animation_editing::AnimationClipRuntimeBuilder builder;
110 auto built = builder.build(target_, &skeleton);
111 if (!built.ok()) return animation_editing::Result<void>::failure(built.status());
112 std::unique_ptr<animation::AnimClip> candidate(std::move(built).takeValue());
113 clip.adopt(*candidate);
114 return eve::editing::applied<void>();
115}
116#endif
117
118void AnimationClipEditor::seedPreviewClip() {
120 tracks.push_back(trackValue("hips-track", "Hips",
121 {keyValue("hips-start", 0.0, 0.0, 0.0, 0.0),
122 keyValue("hips-end", 2.0, 2.0, 0.0, 0.0)}));
123 tracks.push_back(trackValue("spine-track", "Spine",
124 {keyValue("spine-start", 0.0, 0.0, 1.0, 0.0),
125 keyValue("spine-end", 2.0, 2.0, 1.2, 0.0)}));
126 tracks.push_back(trackValue("chest-track", "Chest", {keyValue("chest-start", 0.0, 0.0, 1.7, 0.0), keyValue("chest-end", 2.0, 2.0, 1.8, 0.0)}));
127 tracks.push_back(trackValue("head-track", "Head", {keyValue("head-start", 0.0, 0.0, 2.25, 0.0), keyValue("head-end", 2.0, 2.0, 2.3, 0.0)}));
128 tracks.push_back(trackValue("left-arm-track", "LeftArm", {keyValue("left-arm-start", 0.0, -0.55, 1.75, 0.0), keyValue("left-arm-end", 2.0, 1.45, 1.65, 0.0)}));
129 tracks.push_back(trackValue("right-arm-track", "RightArm", {keyValue("right-arm-start", 0.0, 0.55, 1.75, 0.0), keyValue("right-arm-end", 2.0, 2.55, 1.85, 0.0)}));
131 events.emplace_back(animation_editing::EditorValue::Object{{"id", std::string("footstep")},
132 {"time", 0.5},
133 {"name", std::string("footstep")},
134 {"payload", std::string("left")}});
136 masks.emplace_back(animation_editing::EditorValue::Object{{"bone", std::string("Hips")}, {"weight", 1.0}});
137 masks.emplace_back(animation_editing::EditorValue::Object{{"bone", std::string("Spine")}, {"weight", 1.0}});
139 root["schemaVersion"] = std::int64_t{1};
140 root["settings"] =
141 animation_editing::EditorValue::Object{{"duration", 2.0}, {"sampleRate", 30.0}, {"loop", true}};
142 root["tracks"] = std::move(tracks);
143 root["events"] = std::move(events);
144 root["masks"] = std::move(masks);
145 auto loaded = target_.loadSnapshot(animation_editing::EditorValue(std::move(root)));
146 if (!loaded.ok())
147 loaded.ignore("animation clip editor keeps defaults when the preview snapshot is rejected");
148}
149
150std::vector<std::string> AnimationClipEditor::skeletonBones() const {
151 std::vector<std::string> result; result.reserve(skeleton_.size());
152 for (const auto& bone : skeleton_) result.push_back(bone.name);
153 return result;
154}
155
156std::string AnimationClipEditor::skeletonParent(const std::string& bone) const {
157 for (const auto& entry : skeleton_) if (entry.name == bone) return entry.parent;
158 return {};
159}
160
162 editor::EditorWorkspace& workspace) const {
163 editor::EditorWorkspace candidate = workspace;
164 struct Panel {
165 const char* id;
166 const char* title;
167 const char* region;
168 const char* context;
169 int order;
170 };
171 constexpr Panel panels[] = {
172 {"animation.skeleton", "Skeleton", "left", "list", 100},
173 {"animation.preview", "Pose Preview", "center", "preview", 100},
174 {"animation.inspector", "Clip Inspector", "right", "inspector", 100},
175 {"animation.timeline", "Dope / Curve", "bottom", "timeline", 100},
176 };
177 for (const auto& panel : panels) {
178 if (!candidate.registerPanel(panel.id, panel.title, panel.region, panel.order) ||
179 !candidate.setPanelCapability(panel.id, "animation.clip") ||
180 !candidate.setPanelContext(panel.id, panel.context))
181 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.workspace-conflict",
182 "Could not install the animation clip workspace composition");
183 }
184 if (!candidate.activatePanel("animation.timeline"))
185 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.workspace-activate",
186 "Could not activate the animation timeline panel");
187 workspace = std::move(candidate);
188 return eve::editing::applied<void>();
189}
190
192 float labelWidth) {
193 if (!std::isfinite(width) || !std::isfinite(rowHeight) || !std::isfinite(labelWidth) || width < 8.0f ||
194 rowHeight < 8.0f || labelWidth < 0.0f || labelWidth >= width)
195 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.viewport",
196 "Dope-sheet viewport width, row height and label width are invalid");
197 viewportWidth_ = width;
198 rowHeight_ = rowHeight;
199 labelWidth_ = labelWidth;
200 return eve::editing::applied<void>();
201}
202
204 if (!std::isfinite(seconds))
205 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.seek",
206 "Seek time must be finite");
207 const double duration = target_.duration();
208 playhead_ = duration <= 0.0 ? 0.0 : std::clamp(seconds, 0.0, duration);
209 return refreshPreview();
210}
211
213 if (!std::isfinite(x))
214 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.seek-x",
215 "Dope-sheet seek requires a finite x");
216 return seekSeconds(xToTime(x));
217}
218
220 if (!std::isfinite(x) || !std::isfinite(y))
221 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.pointer",
222 "Pointer coordinates must be finite");
223 const auto tracks = target_.tracks();
224 if (tracks.empty()) return seekX(x);
225 const int row = static_cast<int>(std::floor(y / rowHeight_));
226 if (x < labelWidth_ && row >= 0 && static_cast<std::size_t>(row) < tracks.size())
227 return selectBone(tracks[static_cast<std::size_t>(row)].bone);
228
229 const auto keys = flattenKeys();
230 int best = -1;
231 float bestDistance = 8.0f;
232 for (int i = 0; i < static_cast<int>(keys.size()); ++i) {
233 const float dx = x - timeToX(keys[static_cast<std::size_t>(i)].time);
234 const float dy = y - (static_cast<float>(keys[static_cast<std::size_t>(i)].row) * rowHeight_ + rowHeight_ * 0.5f);
235 const float distance = std::hypot(dx, dy);
236 if (distance < bestDistance) {
237 bestDistance = distance;
238 best = i;
239 }
240 }
241 if (best >= 0) {
242 selectedKeyTrack_ = keys[static_cast<std::size_t>(best)].trackId;
243 selectedKeyId_ = target_.tracks()[static_cast<std::size_t>(keys[static_cast<std::size_t>(best)].row)]
244 .keys[static_cast<std::size_t>(keys[static_cast<std::size_t>(best)].keyIndex)]
245 .id;
246 return selectBone(keys[static_cast<std::size_t>(best)].bone);
247 }
248 selectedKeyId_ = animation_editing::StableId();
249 return seekX(x);
250}
251
253 if (bone.empty())
254 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.select-bone",
255 "Bone name must not be empty");
256 selectedBone_ = std::move(bone);
257 return refreshPreview();
258}
259
261 return commit(target_.makeSetMask({selectedBone_, weight}), "Set mask " + selectedBone_);
262}
263
265 return commit(target_.makeSetSettings(duration, target_.sampleRate(), target_.isLooping()), "Set clip duration");
266}
267
269 return commit(target_.makeSetSettings(target_.duration(), sampleRate, target_.isLooping()), "Set clip sample rate");
270}
271
273 return commit(target_.makeSetSettings(target_.duration(), target_.sampleRate(), loop), "Set clip loop");
274}
275
277 if (selectedKeyId_.empty())
278 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.no-selected-key",
279 "No key is selected");
280 if (!std::isfinite(time) || time < 0.0 || time > target_.duration())
281 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.key-time",
282 "Key time must lie inside the clip duration");
283 auto tracks = target_.tracks();
284 for (auto& track : tracks) {
285 if (track.id != selectedKeyTrack_) continue;
286 const auto key = std::find_if(track.keys.begin(), track.keys.end(),
287 [&](const auto& candidate) { return candidate.id == selectedKeyId_; });
288 if (key == track.keys.end()) continue;
289 key->time = time;
290 return commit(target_.makeSetTrack(track), "Move key");
291 }
292 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.track-missing",
293 "Selected key track was not found");
294}
295
296animation_editing::AnimationTransformKey AnimationClipEditor::sampledSelectedTransform() const {
298 result.time = playhead_;
299 const auto sampled = target_.preview(playhead_);
300 for (const auto& bone : sampled.bones) {
301 if (bone.bone != selectedBone_) continue;
302 result.positionX = bone.positionX; result.positionY = bone.positionY; result.positionZ = bone.positionZ;
303 result.rotationX = bone.rotationX; result.rotationY = bone.rotationY; result.rotationZ = bone.rotationZ; result.rotationW = bone.rotationW;
304 result.scaleX = bone.scaleX; result.scaleY = bone.scaleY; result.scaleZ = bone.scaleZ;
305 break;
306 }
307 return result;
308}
309
311 auto tracks = target_.tracks();
312 for (auto& track : tracks) {
313 if (track.bone != selectedBone_) continue;
314 auto key = std::find_if(track.keys.begin(), track.keys.end(), [&](const auto& candidate) {
315 return std::abs(candidate.time - playhead_) < 1e-6;
316 });
317 if (key == track.keys.end()) {
318 auto inserted = sampledSelectedTransform();
319 inserted.id = animation_editing::StableId("key." + selectedBone_ + "." + std::to_string(++txSequence_));
320 track.keys.push_back(std::move(inserted));
321 selectedKeyId_ = track.keys.back().id;
322 } else {
323 selectedKeyId_ = key->id;
324 }
325 selectedKeyTrack_ = track.id;
326 return commit(target_.makeSetTrack(track), "Key " + selectedBone_);
327 }
328 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.track-missing",
329 "Selected bone has no editable transform track");
330}
331
333 if (selectedKeyId_.empty())
334 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.no-selected-key", "No key is selected");
335 auto tracks = target_.tracks();
336 for (auto& track : tracks) {
337 if (track.id != selectedKeyTrack_) continue;
338 const auto before = track.keys.size();
339 std::erase_if(track.keys, [&](const auto& key) { return key.id == selectedKeyId_; });
340 if (track.keys.size() == before) break;
341 selectedKeyId_ = animation_editing::StableId();
342 return commit(target_.makeSetTrack(track), "Delete key");
343 }
344 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.key-missing", "Selected key no longer exists");
345}
346
347animation_editing::Result<void> AnimationClipEditor::updateSelectedTransform(
349 auto tracks = target_.tracks();
350 for (auto& track : tracks) {
351 if (track.bone != selectedBone_) continue;
352 auto key = std::find_if(track.keys.begin(), track.keys.end(), [&](const auto& candidate) {
353 return std::abs(candidate.time - playhead_) < 1e-6;
354 });
355 if (key == track.keys.end()) {
356 auto inserted = value;
357 inserted.id = animation_editing::StableId("key." + selectedBone_ + "." + std::to_string(++txSequence_));
358 inserted.time = playhead_;
359 track.keys.push_back(std::move(inserted));
360 selectedKeyId_ = track.keys.back().id;
361 } else {
362 auto replacement = value; replacement.id = key->id; replacement.time = key->time; *key = replacement;
363 selectedKeyId_ = key->id;
364 }
365 selectedKeyTrack_ = track.id;
366 return commit(target_.makeSetTrack(track), std::move(label));
367 }
368 return editorError(animation_editing::EditorStatus::NotFound, "editor.animation.track-missing", "Selected bone has no editable transform track");
369}
370
372 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
373 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.position", "Position must be finite");
374 auto value = sampledSelectedTransform(); value.positionX = x; value.positionY = y; value.positionZ = z;
375 return updateSelectedTransform(value, "Set position " + selectedBone_);
376}
377
379 if (!std::isfinite(xd) || !std::isfinite(yd) || !std::isfinite(zd))
380 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.rotation", "Rotation must be finite");
381 const double k = std::numbers::pi / 360.0;
382 const double cx = std::cos(xd*k), sx = std::sin(xd*k), cy = std::cos(yd*k), sy = std::sin(yd*k), cz = std::cos(zd*k), sz = std::sin(zd*k);
383 auto value = sampledSelectedTransform();
384 value.rotationW = cx*cy*cz + sx*sy*sz; value.rotationX = sx*cy*cz - cx*sy*sz;
385 value.rotationY = cx*sy*cz + sx*cy*sz; value.rotationZ = cx*cy*sz - sx*sy*cz;
386 return updateSelectedTransform(value, "Set rotation " + selectedBone_);
387}
388
390 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z) || x <= 0.0 || y <= 0.0 || z <= 0.0)
391 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.scale", "Scale must be positive and finite");
392 auto value = sampledSelectedTransform(); value.scaleX = x; value.scaleY = y; value.scaleZ = z;
393 return updateSelectedTransform(value, "Set scale " + selectedBone_);
394}
395
396animation_editing::Result<void> AnimationClipEditor::commit(
398 if (!operation.ok())
401 spec.id = editor::TransactionId("animation.clip.tx." + std::to_string(++txSequence_));
402 spec.label = std::move(label);
403 spec.target = editor::TargetId(target_.targetId());
404 spec.baseRevision = target_.revision();
405 auto begun = transactions_.begin(std::move(spec));
406 if (!begun.ok())
407 return editorError(begun.code(), "editor.animation.begin", "Could not begin the animation clip transaction");
408 auto appended = transactions_.append(std::move(operation).takeValue());
409 if (!appended.ok()) {
410 auto discarded = transactions_.discard();
411 if (!discarded.ok()) discarded.ignore("pending animation clip transaction already inactive");
412 return animation_editing::Result<void>::failure(appended.status());
413 }
414 auto committed = transactions_.commit();
415 if (!committed.ok())
417 return refreshPreview();
418}
419
421 auto result = transactions_.undo();
422 if (!result.ok()) return result;
423 auto previewed = refreshPreview();
424 if (!previewed.ok())
426 return result;
427}
428
430 auto result = transactions_.redo();
431 if (!result.ok()) return result;
432 auto previewed = refreshPreview();
433 if (!previewed.ok())
435 return result;
436}
437
438void AnimationClipEditor::play() noexcept { playing_ = true; }
439void AnimationClipEditor::pause() noexcept { playing_ = false; }
441 playing_ = false;
442 playhead_ = 0.0;
443 previewDirty_ = true;
444 auto cancelled = cancelPreview();
445 if (!cancelled.ok()) EV_ASSERT(false, "Owned preview cancellation must succeed");
446}
447
449 auto previewed = pollPreview();
450 if (!previewed.ok()) return previewed;
451 const auto previousTime = playhead_;
452 if (playing_) {
453 if (!std::isfinite(deltaSeconds) || deltaSeconds < 0.0)
454 return editorError(animation_editing::EditorStatus::Rejected, "editor.animation.dt",
455 "Playback delta must be a non-negative finite time");
456 playhead_ += deltaSeconds;
457 const double duration = target_.duration();
458 if (duration <= 0.0) {
459 playhead_ = 0.0;
460 } else if (target_.isLooping()) {
461 playhead_ = std::fmod(playhead_, duration);
462 if (playhead_ < 0.0) playhead_ += duration;
463 } else if (playhead_ >= duration) {
464 playhead_ = duration;
465 playing_ = false;
466 }
467 }
468 if (playhead_ != previousTime || previewDirty_) return refreshPreview();
469 return editing::noOp();
470}
471
472animation_editing::Result<void> AnimationClipEditor::refreshPreview() {
473 const auto phase = previewState().phase;
475 return requestPreview();
476}
477
478float AnimationClipEditor::layoutHeight() const noexcept {
479 return static_cast<float>(target_.tracks().size()) * rowHeight_ + 28.0f;
480}
481
482float AnimationClipEditor::playheadX() const noexcept { return timeToX(playhead_); }
483
485 const auto sampled = target_.preview(playhead_);
486 for (const auto& sample : sampled.bones)
487 if (sample.bone == selectedBone_) return sample.maskWeight;
488 return 1.0;
489}
490
492 for (const auto& track : target_.tracks()) for (const auto& key : track.keys) if (key.id == selectedKeyId_) return key.time;
493 return playhead_;
494}
495
496double AnimationClipEditor::selectedPositionX() const { return sampledSelectedTransform().positionX; }
497double AnimationClipEditor::selectedPositionY() const { return sampledSelectedTransform().positionY; }
498double AnimationClipEditor::selectedPositionZ() const { return sampledSelectedTransform().positionZ; }
499double AnimationClipEditor::selectedScaleX() const { return sampledSelectedTransform().scaleX; }
500double AnimationClipEditor::selectedScaleY() const { return sampledSelectedTransform().scaleY; }
501double AnimationClipEditor::selectedScaleZ() const { return sampledSelectedTransform().scaleZ; }
502double AnimationClipEditor::selectedRotationX() const { const auto q=sampledSelectedTransform(); return std::atan2(2*(q.rotationW*q.rotationX+q.rotationY*q.rotationZ),1-2*(q.rotationX*q.rotationX+q.rotationY*q.rotationY))*180/std::numbers::pi; }
503double AnimationClipEditor::selectedRotationY() const { const auto q=sampledSelectedTransform(); return std::asin(std::clamp(2*(q.rotationW*q.rotationY-q.rotationZ*q.rotationX),-1.0,1.0))*180/std::numbers::pi; }
504double AnimationClipEditor::selectedRotationZ() const { const auto q=sampledSelectedTransform(); return std::atan2(2*(q.rotationW*q.rotationZ+q.rotationX*q.rotationY),1-2*(q.rotationY*q.rotationY+q.rotationZ*q.rotationZ))*180/std::numbers::pi; }
505int AnimationClipEditor::boneCount() const noexcept { return static_cast<int>(skeletonBones().size()); }
506std::string AnimationClipEditor::boneName(int index) const { const auto bones=skeletonBones(); return index >= 0 && static_cast<std::size_t>(index) < bones.size() ? bones[static_cast<std::size_t>(index)] : std::string{}; }
507std::string AnimationClipEditor::boneParent(int index) const { return skeletonParent(boneName(index)); }
508
509int AnimationClipEditor::trackCount() const { return static_cast<int>(target_.tracks().size()); }
510
511std::string AnimationClipEditor::trackBone(int index) const {
512 const auto tracks = target_.tracks();
513 if (index < 0 || static_cast<std::size_t>(index) >= tracks.size()) return {};
514 return tracks[static_cast<std::size_t>(index)].bone;
515}
516
517std::string AnimationClipEditor::trackId(int index) const {
518 const auto tracks = target_.tracks();
519 if (index < 0 || static_cast<std::size_t>(index) >= tracks.size()) return {};
520 return tracks[static_cast<std::size_t>(index)].id.value();
521}
522
523bool AnimationClipEditor::isTrackSelected(int index) const { return trackBone(index) == selectedBone_; }
524
525int AnimationClipEditor::keyCount() const { return static_cast<int>(flattenKeys().size()); }
526
528 const auto keys = flattenKeys();
529 if (index < 0 || static_cast<std::size_t>(index) >= keys.size()) return 0.0f;
530 return timeToX(keys[static_cast<std::size_t>(index)].time);
531}
532
534 const auto keys = flattenKeys();
535 if (index < 0 || static_cast<std::size_t>(index) >= keys.size()) return 0.0f;
536 return static_cast<float>(keys[static_cast<std::size_t>(index)].row) * rowHeight_ + rowHeight_ * 0.5f;
537}
538
540 const auto keys = flattenKeys();
541 if (index < 0 || static_cast<std::size_t>(index) >= keys.size()) return false;
542 const auto& key = keys[static_cast<std::size_t>(index)];
543 const auto tracks = target_.tracks();
544 return selectedKeyTrack_ == key.trackId && tracks[static_cast<std::size_t>(key.row)].keys[static_cast<std::size_t>(key.keyIndex)].id == selectedKeyId_;
545}
546
547int AnimationClipEditor::eventCount() const { return static_cast<int>(target_.events().size()); }
548
550 const auto events = target_.events();
551 if (index < 0 || static_cast<std::size_t>(index) >= events.size()) return 0.0f;
552 return timeToX(events[static_cast<std::size_t>(index)].time);
553}
554
555std::string AnimationClipEditor::eventName(int index) const {
556 const auto events = target_.events();
557 if (index < 0 || static_cast<std::size_t>(index) >= events.size()) return {};
558 return events[static_cast<std::size_t>(index)].name;
559}
560
561int AnimationClipEditor::primitiveCount() const { return static_cast<int>(overlay_.primitives.size()); }
562
564 const auto* primitive = primitiveAt(index);
565 return primitive ? primitive->kind : std::string{};
566}
567
569 const auto* primitive = primitiveAt(index);
570 return primitive ? static_cast<float>(primitive->position[0]) : 0.0f;
571}
572
574 const auto* primitive = primitiveAt(index);
575 return primitive ? static_cast<float>(primitive->position[1]) : 0.0f;
576}
577
579 const auto* primitive = primitiveAt(index);
580 return primitive ? static_cast<float>(primitive->direction[0]) : 0.0f;
581}
582
584 const auto* primitive = primitiveAt(index);
585 return primitive ? static_cast<float>(primitive->direction[1]) : 0.0f;
586}
587
589 const auto* primitive = primitiveAt(index);
590 return primitive ? static_cast<float>(primitive->length) : 0.0f;
591}
592
594 const auto* primitive = primitiveAt(index);
595 return primitive ? static_cast<float>(primitive->radius) : 0.0f;
596}
597
599 const auto* primitive = primitiveAt(index);
600 return primitive ? static_cast<float>(primitive->color[0]) : 0.0f;
601}
602
604 const auto* primitive = primitiveAt(index);
605 return primitive ? static_cast<float>(primitive->color[1]) : 0.0f;
606}
607
609 const auto* primitive = primitiveAt(index);
610 return primitive ? static_cast<float>(primitive->color[2]) : 0.0f;
611}
612
613float AnimationClipEditor::timeToX(double time) const {
614 const double duration = target_.duration();
615 const float usable = std::max(1.0f, viewportWidth_ - labelWidth_);
616 if (duration <= 0.0) return labelWidth_;
617 return labelWidth_ + static_cast<float>(std::clamp(time / duration, 0.0, 1.0)) * usable;
618}
619
620double AnimationClipEditor::xToTime(float x) const {
621 const float usable = std::max(1.0f, viewportWidth_ - labelWidth_);
622 const float t = std::clamp((x - labelWidth_) / usable, 0.0f, 1.0f);
623 return static_cast<double>(t) * target_.duration();
624}
625
626const eve::editing::GizmoPrimitive* AnimationClipEditor::primitiveAt(int index) const {
627 if (index < 0 || static_cast<std::size_t>(index) >= overlay_.primitives.size()) return nullptr;
628 return &overlay_.primitives[static_cast<std::size_t>(index)];
629}
630
631std::vector<AnimationClipEditor::TimelineKey> AnimationClipEditor::flattenKeys() const {
632 std::vector<TimelineKey> keys;
633 const auto tracks = target_.tracks();
634 for (int row = 0; row < static_cast<int>(tracks.size()); ++row) {
635 const auto& track = tracks[static_cast<std::size_t>(row)];
636 for (int i = 0; i < static_cast<int>(track.keys.size()); ++i) {
637 TimelineKey key;
638 key.trackId = track.id;
639 key.bone = track.bone;
640 key.keyIndex = i;
641 key.time = track.keys[static_cast<std::size_t>(i)].time;
642 key.row = row;
643 keys.push_back(std::move(key));
644 }
645 }
646 return keys;
647}
648
649} // namespace eve::animation_editor
double z
double y
double x
ActionParameterOperation operation
LogicalId trackId
int root
Definition AnimSmr.cpp:119
UI-neutral animation clip editor: workspace, pose scrub, dope sheet, undo.
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
eve::EntitySpatialPose pose
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
std::string title
bool committed
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
ScriptFieldRegion region
std::string message
wgpu::PopErrorScopeStatus status
glm::vec4 clip
std::array< double, 10 > q
std::vector< Colorf > px
std::uint32_t width
const ColourScope * parent
std::vector< Track > tracks
std::vector< Bone > bones
std::uint32_t bone
std::string label
std::string id
std::shared_ptr< std::atomic< bool > > cancelled
Poco::JSON::Object::Ptr result
float distance
std::vector< std::int32_t > order
glm::dvec3 dx
std::vector< particles::ParticleRecordEvent > events
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::uint32_t targetId
Object::Ptr value
float t
std::string string
float dy
Definition Shadow.cpp:151
float phase
std::map< Cell, int > best
double weight
uint32_t index
const VegetationPresetContext & context
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Definition Result.h:571
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
bool empty() const noexcept
True when no compatibility spelling has been assigned.
Definition Identity.h:377
Keyframed skeletal animation clip (local TRS tracks per bone). Script type: AnimClip.
Definition AnimClip.h:145
Evaluated local (and optional world) pose for an AnimSkeleton. Script type: AnimPose.
Definition AnimPose.h:17
3D bone hierarchy + bind-pose local TRS for skeletal animation. Independent of ik::Skeleton3D (FABRIK...
int getBoneCount() const
Returns the bone count.
int getParent(int boneIndex) const
Returns the parent.
std::string getBoneName(int boneIndex) const
Returns the bone name.
double sampleRate() const noexcept
Authored sample rate.
Result< DomainOperation > makeSetSettings(double duration, double sampleRate, bool loop) const override
Make set settings.
TargetId targetId() const override
Target id.
Result< DomainOperation > makeSetMask(const AnimationMaskEntry &mask) const override
Make set mask.
AnimationClipPreview preview(double time, const std::vector< std::string > &skeletonBones={}) const
Sample the authored clip without mutating a runtime asset.
double duration() const noexcept
Clip duration in seconds.
std::vector< AnimationEventRecord > events() const
Return event markers ordered by time then stable id.
Result< void > loadSnapshot(const EditorValue &snapshot)
Atomically load deterministic schema-version-one clip data.
bool isLooping() const noexcept
Whether preview time wraps.
std::vector< AnimationBoneTrack > tracks() const
Return tracks ordered by stable id.
Result< DomainOperation > makeSetTrack(const AnimationBoneTrack &track) const override
Make set track.
animation_editing::Result< void > setDuration(double duration)
Commit clip duration through the document transaction path.
animation_editing::Result< void > update(double deltaSeconds)
Advance playhead by injected dt and refresh pose/overlay.
animation_editing::Result< void > setMaskWeight(double weight)
std::string trackId(int index) const
Track id.
double selectedScaleX() const
Selected scale x.
float primitiveX(int index) const
Primitive x.
float primitiveG(int index) const
Primitive g.
double duration() const noexcept
Duration.
double selectedRotationX() const
Selected rotation x.
animation_editing::Result< void > pollPreview()
Publish the current completed preview atomically; Pending while work runs, NoOp when idle....
bool isTrackSelected(int index) const
True when track selected.
animation_editing::Result< void > loadRuntimeClip(const animation::AnimSkeleton &skeleton, const animation::AnimClip &clip)
Atomically replace the editor document from a real runtime skeleton and clip.
float primitiveY(int index) const
Primitive y.
bool isKeySelected(int index) const
True when key selected.
std::string eventName(int index) const
Event name.
std::string primitiveKind(int index) const
Primitive kind.
double selectedScaleY() const
Selected scale y.
std::string boneParent(int index) const
Bone parent.
animation_editing::Result< void > cancelPreview()
Cancel pending publication while keeping the last valid preview; a new explicit request may resume.
animation_editing::Result< void > setSelectedScale(double x, double y, double z)
Replace the selected bone scale at the playhead and create a key when needed.
animation_editing::Result< void > setSelectedRotation(double xDegrees, double yDegrees, double zDegrees)
Replace the selected bone Euler rotation in degrees and create a key when needed.
std::string boneName(int index) const
Bone name.
AnimationClipEditor(std::string targetId)
Construct a seeded two-bone preview clip.
animation_editing::Result< void > seekSeconds(double seconds)
animation_editing::Result< void > writeRuntimeClip(animation::AnimClip &clip, const animation::AnimSkeleton &skeleton) const
Replace a runtime clip with the current authoritative editor document.
double sampleRate() const noexcept
Sample rate.
float primitiveDirX(int index) const
Primitive dir x.
double selectedPositionY() const
Selected position y.
float primitiveLength(int index) const
Primitive length.
animation_editing::Result< void > deleteSelectedKey()
Delete the selected transform key.
float layoutHeight() const noexcept
Layout height.
animation_editing::Result< void > moveSelectedKey(double time)
float primitiveRadius(int index) const
Primitive radius.
animation_editing::Result< void > seekX(float x)
float playheadX() const noexcept
Playhead x.
animation_editing::Result< void > selectBone(std::string bone)
animation_editing::Result< editor::TransactionReceipt > undo()
animation_editing::Result< void > setLoop(bool loop)
Commit looping through the document transaction path.
double selectedRotationY() const
Selected rotation y.
std::string trackBone(int index) const
Track bone.
double selectedPositionX() const
Selected position x.
double selectedRotationZ() const
Selected rotation z.
animation_editing::Result< void > setSampleRate(double sampleRate)
Commit authored sample rate through the document transaction path.
double selectedKeyTime() const
Selected key time.
double selectedScaleZ() const
Selected scale z.
float primitiveB(int index) const
Primitive b.
animation_editing::Result< void > keySelectedBone()
Insert or replace a transform key for the selected bone at the playhead.
animation_editing::Result< void > configureWorkspace(editor::EditorWorkspace &workspace) const
Install Skeleton / Pose Preview / Inspector / Dope panels.
animation_editing::Result< void > setViewport(float width, float rowHeight, float labelWidth)
Configure dope-sheet pixel layout.
animation_editing::Result< void > requestPreview()
Queue a preview of the current domain inputs; accepted work returns Pending. @cost Copies the PCM/cli...
float primitiveDirY(int index) const
Primitive dir y.
animation_editing::Result< void > setSelectedPosition(double x, double y, double z)
Replace the selected bone position at the playhead and create a key when needed.
animation_editing::Result< void > pointerDown(float x, float y)
double selectedPositionZ() const
Selected position z.
float primitiveR(int index) const
Primitive r.
editor::PreviewState previewState() const noexcept
Observe request sequence, provider generation and phase without copying preview payloads.
animation_editing::Result< editor::TransactionReceipt > redo()
std::uint64_t revision() const override
Return the current revision.
Deterministic owning value tree shared by authoring hosts.
std::vector< Value > Array
std::map< std::string, Value > Object
Composition model shared by project-specific developer and runtime editors.
bool setPanelContext(const std::string &id, const std::string &context)
Attach a semantic input context such as scene, graph, or timeline.
Result< WorkspacePanelDescriptor > registerPanel(WorkspacePanelDescriptor descriptor)
Register a checked owning panel descriptor.
Result< WorkspacePanelDescriptor > activatePanel(const StableId &id)
Activate a visible panel with structured not-found/rejected results.
bool setPanelCapability(const std::string &id, const std::string &capability)
Attach a capability requirement used by the host when filtering panels.
Result< TransactionReceipt > commit() override
Preflight and commit all active operations through the authority.
Result< TransactionId > begin(TransactionSpec specification) override
Begin a transaction with a stable id and base revision.
Result< TransactionReceipt > undo() override
Compensate the most recent committed transaction.
Result< void > discard() override
Discard the active, not-yet-committed operation list.
Result< TransactionReceipt > redo() override
Reapply the most recently compensated transaction.
Result< void > append(DomainOperation operation) override
Append an operation to the active transaction without applying it.
editing::StableId StableId
Result< void > noOp(std::vector< Diagnostic > diagnostics={})
Construct a successful void result for an operation that made no change.
eve::editing::TargetId TargetId
Definition EditorIds.h:29
eve::editing::TransactionId TransactionId
Definition EditorIds.h:34
void keys(const Value &value, std::initializer_list< const char * > names)
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
One stable transform key used by the animation timeline.
Renderer-neutral wire primitive for authoring viewport overlays.
std::vector< GizmoPrimitive > primitives
TransactionSpec public API.