Blender V5.3
world_space_copy.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include "BLI_bounds.hh"
6#include "BLI_listbase.hh"
9#include "BLI_path_utils.hh"
10#include "BLI_string.hh"
11
12#include "BKE_action.hh"
13#include "BKE_appdir.hh"
14#include "BKE_armature.hh"
16#include "BKE_blendfile.hh"
17#include "BKE_context.hh"
18#include "BKE_fcurve.hh"
19#include "BKE_scene.hh"
20
21#include "DEG_depsgraph.hh"
24
25#include "RNA_access.hh"
26#include "RNA_define.hh"
27
28#include "WM_api.hh"
29#include "WM_types.hh"
30
32#include "ED_screen.hh"
33
34#include "ANIM_action.hh"
35#include "ANIM_animdata.hh"
36#include "ANIM_rna.hh"
37
38#include "anim_intern.hh"
39
40namespace blender::ed::animrig {
41
42constexpr const char *clipboard_name = "world_space_buffer.blend";
43
44/* Maps the name of the entity as stored in the clipboard to the 12 FCurves that make the world
45 * space matrix. */
47/* For each transformable, maps to an entity name on the clipboard to read FCurves from. */
49
50/* Stores which other AnimTransformables have to be applied before it. */
53 /* Other transformable_relations that need to be applied before this. */
55 /* Indicates that this data has been processed. */
56 bool done = false;
57
59 {
60 for (TransformableRelations *ancestor : ancestors) {
61 if (!ancestor->done) {
62 /* All ancestors must be applied before this transformable. */
63 return false;
64 }
65 }
66 return true;
67 }
68};
69
70/* Uniquely Identifies a component of the depsgraph. */
72 ID *id = nullptr;
75
76 bool operator==(const DegComponentIdentifier &other) const
77 {
78 return id == other.id && type == other.type && name == other.name;
79 }
80
81 uint64_t hash() const
82 {
83 return get_default_hash(id, type, name);
84 }
85};
86
88 FCurve *fcurve = nullptr;
89 /* Store info if that FCurve was created by this code. If yes, we can potentially remove it if
90 * the keys are all on the same value after pasting. */
91 bool created_on_paste = false;
92 /* The index into the bezt array from which to start pasting. */
94};
95
111
118
119static void matrix_to_fcurves(const float4x4 &matrix,
120 Span<FCurve *> fcurves,
121 const int frame,
122 const int key_index)
123{
124 /* Using IndexRange(3) because the last row is always 0/0/0/1 which means we don't need to
125 * store it. */
126 for (const int y : IndexRange(3)) {
127 for (const int x : IndexRange(4)) {
128 FPoint &fpt = fcurves[y * 4 + x]->fpt[key_index];
129 fpt.vec[0] = frame;
130 fpt.vec[1] = matrix[x][y];
131 }
132 }
133}
134
135static float4x4 fcurves_to_matrix(const Span<const FCurve *> fcurves, const int key_index)
136{
138 for (const int y : IndexRange(3)) {
139 for (const int x : IndexRange(4)) {
140 FPoint &fpt = fcurves[y * 4 + x]->fpt[key_index];
141 mat[x][y] = fpt.vec[1];
142 }
143 }
144 return mat;
145}
146
148{
149 /* We need the ID pointers to build the depsgraph, but every ID in the Vector
150 * should be unique. */
151 Vector<ID *> ids;
152 Set<ID *> added_ids;
153 for (const AnimTransformable *transformable : transformables) {
154 if (added_ids.add(transformable->owner_id())) {
155 ids.append(transformable->owner_id());
156 }
157 }
158 return ids;
159}
160
162{
163 /* We need the ID pointers to build the depsgraph, but every ID in the Vector
164 * should be unique. */
165 Vector<ID *> ids;
166 Set<ID *> added_ids;
167 for (const AnimTransformable &transformable : transformables) {
168 if (added_ids.add(transformable.owner_id())) {
169 ids.append(transformable.owner_id());
170 }
171 }
172 return ids;
173}
174
176 const AnimTransformable &transformable)
177{
178 switch (transformable.type()) {
180 return {transformable.owner_id(), transformable.name(), DEG_OB_COMP_BONE};
181
183 return {transformable.owner_id(), "", DEG_OB_COMP_TRANSFORM};
184 }
185
187 return {transformable.owner_id(), "", DEG_OB_COMP_TRANSFORM};
188}
189
191 const Depsgraph *depsgraph, const MutableSpan<AnimTransformable *> transformables)
192{
193 Array<TransformableRelations> transformable_relations(transformables.size());
195
196 for (const int i : transformables.index_range()) {
197 AnimTransformable &transformable = *transformables[i];
198 transformable_relations[i].transformable = &transformable;
199 transformable_relations[i].done = false;
200 component_map.add(transformable_to_deg_identifier(transformable), &transformable_relations[i]);
201 }
202
203 for (const DegComponentIdentifier &deg_identifier : component_map.keys()) {
204 TransformableRelations *transformable_relation = component_map.lookup(deg_identifier);
206 depsgraph,
207 deg_identifier.id,
208 deg_identifier.type,
209 deg_identifier.name,
210 [&](ID *other_id, eDepsObjectComponentType type, StringRef component_name) {
211 if (!ELEM(type, DEG_OB_COMP_TRANSFORM, DEG_OB_COMP_BONE)) {
212 return true;
213 }
214 DegComponentIdentifier dependent_deg_id(other_id, component_name, type);
215 if (dependent_deg_id == deg_identifier) {
216 /* Skip self. */
217 return true;
218 }
219 TransformableRelations *dependent = component_map.lookup_default(dependent_deg_id,
220 nullptr);
221 if (!dependent) {
222 return true;
223 }
224 dependent->ancestors.append(transformable_relation);
225 if (dependent->done) {
226 /* This is used as an optimization. If we already visited that component for a previous
227 * transformable, the dependency of that branch is already recorded and we can stop
228 * iterating into it. */
229 return false;
230 }
231 dependent->done = true;
232 return true;
233 });
234 }
235 for (TransformableRelations &relation : transformable_relations) {
236 /* Resetting the bool for the next use. */
237 relation.done = false;
238 }
239 return transformable_relations;
240}
241
243 const Depsgraph *depsgraph, const MutableSpan<AnimTransformable *> transformables)
244{
246 depsgraph, transformables);
247 Vector<AnimTransformable *> sorted_transformables;
248
249 while (true) {
250 bool inserted_any = false;
251 for (TransformableRelations &relations : transformable_relations) {
252 if (relations.done || !relations.all_ancestors_done()) {
253 continue;
254 }
255 sorted_transformables.append(relations.transformable);
256 inserted_any = true;
257 relations.done = true;
258 }
259 if (!inserted_any) {
260 /* There are 2 cases in which this can happen. Either we applied all transforms, or there
261 * is a dependency cycle where 2 transformable_relations have each other in their
262 * ancestors. In the latter case the returned Vector will not contain those transformables
263 * with a cycle.*/
264 break;
265 }
266 }
267
268 return sorted_transformables;
269}
270
274static void ensure_baked_fcurves(Main &bmain,
275 const AnimTransformable &transformable,
279 const Bounds<int> range)
280{
281 namespace ar = blender::animrig;
282
283 bool has_key_on_frame = false;
284 const StringRefNull group_name = transformable.fcurve_group_name();
285 /* Ensuring all FCurves exist. */
286 for (const int i : fcus.index_range()) {
287 PasteFCurve &paste_fcu = fcus[i];
288 if (!paste_fcu.fcurve) {
289 FCurve &fcurve = channelbag.fcurve_ensure(&bmain,
290 {rna_path, i, PROP_FLOAT, PROP_NONE, group_name});
291 paste_fcu.fcurve = &fcurve;
292 paste_fcu.created_on_paste = true;
293 }
294 if (paste_fcu.fcurve->fpt) {
295 /* Avoid crashes with sampled FCurves. */
296 continue;
297 }
298 ar::bake_fcurve(
299 paste_fcu.fcurve, {range.min, range.max - 1}, 1, ar::BakeCurveRemove::IN_RANGE);
301 paste_fcu.fcurve->bezt, range.min, paste_fcu.fcurve->totvert, &has_key_on_frame);
302 BLI_assert(has_key_on_frame);
303 }
304}
305
309static bool is_fcurve_flat(FCurve &fcurve)
310{
311 if (!fcurve.modifiers.is_empty()) {
312 /* Any modifiers count as potentially modifying values over time. */
313 return false;
314 }
315 if (fcurve.totvert == 0) {
316 return true;
317 }
318
319 if (!fcurve.bezt) {
320 /* FPoint is not yet supported. */
321 return false;
322 }
323
324 if (fcurve.totvert == 1) {
325 if (fcurve.extend == FCURVE_EXTRAPOLATE_CONSTANT) {
326 /* Handles don't matter in this case. */
327 return true;
328 }
329 const BezTriple &key = fcurve.bezt[0];
330 return key.vec[1][1] == key.vec[0][1] && key.vec[1][1] == key.vec[2][1];
331 }
332
333 constexpr float threshold = 0.0001f;
334 const float reference_value = fcurve.bezt[0].vec[1][1];
335 for (int i = 0; i < fcurve.totvert; i++) {
336 if (fabsf(reference_value - fcurve.bezt[i].vec[1][1]) > threshold) {
337 return false;
338 }
339 if (fcurve.bezt[i].ipo != BEZT_IPO_BEZ) {
340 /* Handles have no effect. */
341 continue;
342 }
343 if (fabsf(reference_value - fcurve.bezt[i].vec[0][1]) > threshold) {
344 return false;
345 }
346 if (fabsf(reference_value - fcurve.bezt[i].vec[2][1]) > threshold) {
347 return false;
348 }
349 }
350 return true;
351}
352
353/* Remove any FCurves that have been created for pasting and remain static after pasting. */
354static void clean_baked_fcurves(AnimTransformable &transformable,
358{
359 /* When we delete FCurves we have to flush the values to the transformable.
360 * Otherwise they are lost. */
361 TransformFloats values = transformable.get_property(property_type);
362 for (PasteFCurve &paste_fcurve : fcurves) {
363 if (!paste_fcurve.created_on_paste) {
364 continue;
365 }
366 if (is_fcurve_flat(*paste_fcurve.fcurve)) {
367 BLI_assert(paste_fcurve.fcurve->bezt != nullptr);
368 values[paste_fcurve.fcurve->array_index] = paste_fcurve.fcurve->bezt[0].vec[1][1];
369 channelbag.fcurve_remove(*paste_fcurve.fcurve);
370 paste_fcurve.fcurve = nullptr;
371 }
372 }
373 transformable.set_property(property_type, values, AxisMutable::AXIS_MUTABLE_ALL);
374}
375
377{
378 for (PasteFCurve &paste_fcurve : fcurves) {
379 if (paste_fcurve.fcurve) {
380 BKE_fcurve_handles_recalc(*paste_fcurve.fcurve);
381 }
382 }
383}
384
386 const float4x4 &matrix,
387 const Rotation &reference_rotation,
388 const int paste_index)
389{
390 float3 location;
392 Rotation rotation_quat;
393 rotation_quat.mode = ROT_MODE_QUAT;
394 rotation_quat.values.reinitialize(4);
395 mat4_decompose(location, rotation_quat.values.data(), scale, matrix.ptr());
396
397 const Rotation rotation = rotation_quat.converted_to_mode(t_fcus.rotation_mode,
398 &reference_rotation);
399
400 for (const int i : t_fcus.location.index_range()) {
401 PasteFCurve &pfcu = t_fcus.location[i];
402 BLI_assert(pfcu.paste_start_index + paste_index < pfcu.fcurve->totvert);
403 if (!pfcu.fcurve->bezt) {
404 continue;
405 }
406 const int bezt_index = pfcu.paste_start_index + paste_index;
407 BezTriple &key = pfcu.fcurve->bezt[bezt_index];
409 }
410
411 for (const int i : t_fcus.rotation.index_range()) {
412 PasteFCurve &pfcu = t_fcus.rotation[i];
413 BLI_assert(pfcu.paste_start_index + paste_index < pfcu.fcurve->totvert);
414 if (!pfcu.fcurve->bezt) {
415 continue;
416 }
417 const int bezt_index = pfcu.paste_start_index + paste_index;
418 BezTriple &key = pfcu.fcurve->bezt[bezt_index];
419 BKE_fcurve_keyframe_move_value_with_handles(&key, rotation.values[i]);
420 }
421
422 for (const int i : t_fcus.scale.index_range()) {
423 PasteFCurve &pfcu = t_fcus.scale[i];
424 BLI_assert(pfcu.paste_start_index + paste_index < pfcu.fcurve->totvert);
425 if (!pfcu.fcurve->bezt) {
426 continue;
427 }
428 const int bezt_index = pfcu.paste_start_index + paste_index;
429 BezTriple &key = pfcu.fcurve->bezt[bezt_index];
431 }
432 return rotation;
433}
434
435/* -------------------------------------------------------------------- */
438
442static void copy_world_space(Main &bmain,
443 Scene &scene,
444 ViewLayer &view_layer,
445 ReportList &reports,
446 const Span<AnimTransformable> transformables,
447 const Bounds<int> range)
448{
449 namespace ar = blender::animrig;
450 namespace bf = bke::blendfile;
451 bf::PartialWriteContext copybuffer{bmain};
452 bAction *dna_action = reinterpret_cast<bAction *>(
453 copybuffer.id_create(ID_AC,
454 "world_space_copy",
455 nullptr,
456 {(bf::PartialWriteContext::IDAddOperations::SET_FAKE_USER |
457 bf::PartialWriteContext::IDAddOperations::SET_CLIPBOARD_MARK)}));
458
459 /* Using the frame start and end of the action to store the range of the copied keys. */
460 dna_action->frame_start = range.min;
461 dna_action->frame_end = range.max;
462 ar::Action &action = dna_action->wrap();
463 action.layer_keystrip_ensure();
464 ar::StripKeyframeData &strip_data = action.layer(0)->strip(0)->data<ar::StripKeyframeData>(
465 action);
466 ar::Slot &slot = action.slot_add();
467 ar::Channelbag &channelbag = strip_data.channelbag_for_slot_ensure(slot);
468
469 /* We are storing the world space matrix in separate FCurves so the data can be stored in a
470 * blend file. */
471 Set<StringRefNull> added_names;
472 Array<Array<FCurve *>> world_space_data(transformables.size());
473 for (const int transformable_index : transformables.index_range()) {
474 const AnimTransformable &transformable = transformables[transformable_index];
475 if (!added_names.add(transformable.name())) {
476 /* When copying bones from different armatures, we can get identical names which would create
477 * an invalid copy buffer. */
478 continue;
479 }
480 Array<FCurve *> fcurves(12);
481 for (const int i : fcurves.index_range()) {
482 FCurve *fcurve = BKE_fcurve_create();
483 fcurve->rna_path_set(transformable.name());
484 fcurve->array_index = i;
485 const int vert_count = range.size();
486 BLI_assert(vert_count > 0);
487 /* Using FPoint because we only need 2 floats per key, not the huge struct that
488 * is BezTriple. */
489 fcurve->fpt = MEM_new_array_uninitialized<FPoint>(vert_count, "world_space_copy_points");
490 fcurve->totvert = vert_count;
491 /* Could allocate space on the channelbag in big chunks instead of appending which is a
492 * MEM_new every time. */
493 channelbag.fcurve_append(*fcurve);
494 fcurves[i] = fcurve;
495 }
496
497 world_space_data[transformable_index] = std::move(fcurves);
498 }
499
500 if (added_names.size() != transformables.size()) {
501 BKE_report(&reports,
503 "Found duplicate names in selection. Not all selected were saved into clipboard.");
504 }
505
506 Depsgraph *depsgraph = DEG_graph_new(&bmain, &scene, &view_layer, DAG_EVAL_VIEWPORT);
507 Vector<ID *> ids = get_unique_ids(transformables);
508 DEG_graph_build_from_ids(depsgraph, ids);
509
510 for (int frame = range.min; frame < range.max; frame++) {
511 const int key_index = frame - range.min;
512 DEG_evaluate_on_framechange(depsgraph, frame);
513 for (const int transformable_index : transformables.index_range()) {
514 if (world_space_data[transformable_index].size() == 0) {
515 /* May be empty if skipped due to name collisions. */
516 continue;
517 }
518 const AnimTransformable &transformable = transformables[transformable_index];
519 const float4x4 world_matrix = transformable.get_world_space(*depsgraph);
520 matrix_to_fcurves(world_matrix, world_space_data[transformable_index], frame, key_index);
521 }
522 }
523
524 DEG_graph_free(depsgraph);
525
526 char filepath[FILE_MAX];
527 BLI_path_join(filepath, sizeof(filepath), BKE_tempdir_base(), clipboard_name);
528 BLI_assert(copybuffer.is_valid());
529 copybuffer.write_as_copypaste_buffer(filepath, reports);
530 if (added_names.size() == transformables.size()) {
531 const char *transformable_type_name = transformables[0].type() ==
533 "objects" :
534 "bones";
535 BKE_reportf(&reports,
536 RPT_INFO,
537 "Copied %d %s across %d frames to the clipboard",
538 int(added_names.size()),
539 transformable_type_name,
540 range.max - range.min);
541 }
542}
543
544/* Build a map of the transformable name to the name in the clipboard to read from. */
546 const ClipboardData &clipboard_data)
547{
548 PasteMap paste_map;
549
550 const bool from_single = clipboard_data.size() == 1;
551 const bool to_single = transformables.size() == 1;
552 if (from_single && to_single) {
553 paste_map.add(&transformables[0], *clipboard_data.keys().begin());
554 return paste_map;
555 }
556
557 /* Pasting the same data to all transformables. */
558 if (from_single && !to_single) {
559 StringRefNull source_name = *clipboard_data.keys().begin();
560 for (AnimTransformable &transformable : transformables) {
561 paste_map.add(&transformable, source_name);
562 }
563 return paste_map;
564 }
565
566 /* Strict name matching. */
567 for (AnimTransformable &transformable : transformables) {
568 const Array<FCurve *> *fcurves = clipboard_data.lookup_ptr(transformable.name());
569 if (fcurves) {
570 paste_map.add(&transformable, transformable.name());
571 }
572 }
573 return paste_map;
574}
575
581 Main &bmain, const Span<AnimTransformable *> transformables, const Bounds<int> range)
582{
583 namespace ar = blender::animrig;
584 Array<TransformFCurves> fcurve_buffer(transformables.size());
585 for (const int i : transformables.index_range()) {
586 AnimTransformable *transformable = transformables[i];
587 ID *owner_id = transformable->owner_id();
588 bAction *paste_dna_action = ar::id_action_ensure(&bmain, owner_id);
589 /* When adding layers this becomes a lot more complicated. We'll have to answer where keys go
590 * in this case. Multiple things to consider:
591 * - The active layer may have no effect on the final pose
592 * - Not every layer may have a channelbag for this transformable.
593 * - When inserting keys into a layer that is additive, we need to adjust the inserted values.
594 * - When inserting keys into a layer with an influence < 1 we'll also have to adjust the
595 * values.
596 * - In all cases, the result has to be that the final world space of the transformable ends up
597 * where it was copied from.
598 */
599 ar::assert_baklava_phase_1_invariants(paste_dna_action->wrap());
600 ar::Channelbag &channelbag = ar::action_channelbag_ensure(*paste_dna_action, *owner_id);
601 TransformFCurves &transform_fcurves = fcurve_buffer[i];
602 transform_fcurves.channelbag = &channelbag;
603 transform_fcurves.rotation_mode = transformable->get_rotation_mode();
604 if (transform_fcurves.rotation_mode >= ROT_MODE_EUL) {
605 transform_fcurves.rotation.reinitialize(3);
606 }
607 else {
608 transform_fcurves.rotation.reinitialize(4);
609 }
610 const std::string loc_path = transformable->rna_path_to_property(
612 const std::string rot_path = transformable->rna_path_to_property(
614 const std::string scale_path = transformable->rna_path_to_property(
616 const std::string rotation_mode_path = transformable->rna_path_to_rotation_mode();
617
618 FCurve *rotation_mode_fcurve = nullptr;
619
620 for (FCurve *fcurve : channelbag.fcurves()) {
621 StringRefNull fcurve_path(fcurve->rna_path());
622 if (fcurve_path == loc_path) {
623 transform_fcurves.location[fcurve->array_index].fcurve = fcurve;
624 }
625 else if (fcurve_path == rot_path) {
626 transform_fcurves.rotation[fcurve->array_index].fcurve = fcurve;
627 }
628 else if (fcurve_path == scale_path) {
629 transform_fcurves.scale[fcurve->array_index].fcurve = fcurve;
630 }
631 else if (fcurve_path == rotation_mode_path) {
632 BLI_assert(rotation_mode_fcurve == nullptr);
633 rotation_mode_fcurve = fcurve;
634 }
635 }
636
637 /* Ensuring all FCurves exist. */
639 bmain, *transformable, transform_fcurves.location, channelbag, loc_path, range);
641 bmain, *transformable, transform_fcurves.rotation, channelbag, rot_path, range);
643 bmain, *transformable, transform_fcurves.scale, channelbag, scale_path, range);
644 if (rotation_mode_fcurve && rotation_mode_fcurve->bezt) {
645 /* We have to ensure the whole range uses the same rotation mode, otherwise it wouldn't be
646 * guaranteed that the rotation FCurves will be used over the full range. Changing euler to
647 * quaternion would change which FCurves are read from. */
648 const eRotationModes current_mode = transformable->get_rotation_mode();
649 ar::bake_fcurve(
650 rotation_mode_fcurve, {range.min, range.max - 1}, 1, ar::BakeCurveRemove::IN_RANGE);
651 bool has_key_on_frame;
652 const int range_start_index = BKE_fcurve_bezt_binarysearch_index(
653 rotation_mode_fcurve->bezt, range.min, rotation_mode_fcurve->totvert, &has_key_on_frame);
654 BLI_assert(has_key_on_frame);
655 for (int frame = range.min; frame < range.max; frame++) {
657 &rotation_mode_fcurve->bezt[range_start_index + frame - range.min], current_mode);
658 }
659 }
660 }
661
662 return fcurve_buffer;
663}
664
665static bAction *read_action_from_clipboard(Main &clipboard_bmain, ReportList &reports)
666{
667 namespace ar = blender::animrig;
668
669 if (clipboard_bmain.actions.is_empty()) {
670 BKE_report(&reports, RPT_ERROR, "Clipboard data has no animation");
671 return nullptr;
672 }
673
674 bAction *clipboard_dna_action = clipboard_bmain.actions.first();
675 ar::Action &clipboard_action = clipboard_dna_action->wrap();
676 if (clipboard_action.strip_keyframe_data().is_empty() ||
677 clipboard_action.strip_keyframe_data()[0]->channelbags().is_empty())
678 {
679 BKE_report(&reports, RPT_ERROR, "Clipboard data has no animation");
680 return nullptr;
681 }
682
683 return clipboard_dna_action;
684}
685
686static void paste_world_space(Main &bmain,
687 Scene &scene,
688 ViewLayer &view_layer,
689 ReportList &reports,
690 bAction &clipboard_dna_action,
691 const MutableSpan<AnimTransformable> transformables,
692 const AnimationPasteOffset offset)
693{
694 namespace ar = blender::animrig;
695
696 ar::Action &clipboard_action = clipboard_dna_action.wrap();
697 BLI_assert(clipboard_action.strip_keyframe_data_array_num == 1 &&
698 clipboard_action.strip_keyframe_data()[0]->channelbag_array_num == 1);
699 ar::Channelbag &channelbag = *clipboard_action.strip_keyframe_data()[0]->channelbags()[0];
700 ClipboardData clipboard_data;
701 for (FCurve *fcurve : channelbag.fcurves()) {
702 BLI_assert(fcurve != nullptr);
703 Array<FCurve *> &fcurves = clipboard_data.lookup_or_add(fcurve->rna_path(),
704 Array<FCurve *>(12));
705 fcurves[fcurve->array_index] = fcurve;
706 }
707
708 for (Array<FCurve *> &fcurves : clipboard_data.values()) {
709 for (FCurve *fcurve : fcurves) {
710 if (fcurve == nullptr) {
711 BKE_report(&reports, RPT_ERROR, "Clipboard contains incomplete animation data");
712 return;
713 }
714 }
715 }
716
717 PasteMap paste_map = generate_paste_mapping(transformables, clipboard_data);
718
719 if (paste_map.size() == 0) {
720 BKE_report(&reports, RPT_ERROR, "Cannot match selection to clipboard data");
721 return;
722 }
723
725 pasteables.reserve(paste_map.size());
726 for (AnimTransformable *anim_transformable : paste_map.keys()) {
727 pasteables.append(anim_transformable);
728 }
729 /* Build a minimal depsgraph because we need to evaluate the scene on every frame to correctly
730 * invert world to local space. */
731 Depsgraph *depsgraph = DEG_graph_new(&bmain, &scene, &view_layer, DAG_EVAL_VIEWPORT);
732 Vector<ID *> ids = get_unique_ids(pasteables);
733 DEG_graph_build_from_ids(depsgraph, ids);
734
735 /* We need to first apply the values to those transformables that are not affected by any
736 * other transformables. This is why we need to sort using the depsgraph. */
737 Vector<AnimTransformable *> sorted_transformables = depsgraph_sorted_transformables(depsgraph,
738 pasteables);
739
740 if (sorted_transformables.size() != pasteables.size()) {
742 &reports, RPT_ERROR, "Failed to figure out pasting order. Potential dependency cycle");
743 DEG_graph_free(depsgraph);
744 return;
745 }
746
747 Bounds<int> range = {int(clipboard_action.frame_start), int(clipboard_action.frame_end)};
749 const int paste_length = range.size();
750 const int start_frame = scene.r.cfra;
751 range = {start_frame, start_frame + paste_length};
752 }
753 /* Building the FCurves with all their required keys beforehand to avoid constantly inserting
754 * keys into the bezt array. */
756 bmain, sorted_transformables, range);
757 BLI_assert(fcurve_buffer.size() == sorted_transformables.size());
758
759 /* Since we potentially added FCurves, we have to rebuild the depsgraph relations. */
760 DEG_graph_build_from_ids(depsgraph, ids);
761
762 for (const int i : sorted_transformables.index_range()) {
763 AnimTransformable *transformable = sorted_transformables[i];
764 TransformFCurves &transform_fcurves = fcurve_buffer[i];
765
766 /* This could be optimized by batching together transformables that don't have a relation to
767 * avoid a few depsgraph evaluations. */
768 Rotation previous_rotation = transformable->get_rotation();
769 for (int frame = range.min; frame < range.max; frame++) {
770 DEG_evaluate_on_framechange(depsgraph, frame);
771 /* Assuming that all FCurves have the range baked on 1s. */
772 const int key_index = frame - range.min;
773 const StringRefNull clipboard_name = paste_map.lookup(transformable);
774 const Array<FCurve *> *fcurves = clipboard_data.lookup_ptr(clipboard_name);
775 BLI_assert_msg(fcurves != nullptr,
776 "Only transformables with matching matrix data should iterated here");
777 const float4x4 world_matrix = fcurves_to_matrix(*fcurves, key_index);
778 const float4x4 local_matrix = transformable->world_to_local(*depsgraph, world_matrix);
779 previous_rotation = set_keys_to_transform(
780 transform_fcurves, local_matrix, previous_rotation, key_index);
781 }
782 /* Action will have been created in `build_fcurves_for_paste`. */
783 bAction *paste_dna_action = BKE_animdata_from_id(transformable->owner_id())->action;
784 /* We have to update the action, otherwise the key values we just changed won't be visible to
785 * the next transformable. */
786 DEG_graph_id_tag_update(&bmain, depsgraph, &paste_dna_action->id, ID_RECALC_ANIMATION);
787 }
788
789 for (const int i : sorted_transformables.index_range()) {
790 AnimTransformable &transformable = *sorted_transformables[i];
791 TransformFCurves &transform_fcurves = fcurve_buffer[i];
792 clean_baked_fcurves(transformable,
794 transform_fcurves.location,
795 *transform_fcurves.channelbag);
796 clean_baked_fcurves(transformable,
798 transform_fcurves.rotation,
799 *transform_fcurves.channelbag);
800 clean_baked_fcurves(transformable,
802 transform_fcurves.scale,
803 *transform_fcurves.channelbag);
804 recalculate_handles(transform_fcurves.location);
805 recalculate_handles(transform_fcurves.rotation);
806 recalculate_handles(transform_fcurves.scale);
807 }
808
809 const char *transformable_type_name = transformables[0].type() ==
811 "objects" :
812 "bones";
813 if (sorted_transformables.size() == clipboard_data.size()) {
814 BKE_reportf(&reports,
815 RPT_INFO,
816 "Pasted all %d %s over %d frames",
817 int(sorted_transformables.size()),
818 transformable_type_name,
819 range.max - range.min);
820 }
821 else if (clipboard_data.size() == 1) {
822 BKE_reportf(&reports,
823 RPT_INFO,
824 "Pasted the same animation to %d %s over %d frames",
825 int(sorted_transformables.size()),
826 transformable_type_name,
827 range.max - range.min);
828 }
829 else {
830 BKE_reportf(&reports,
831 RPT_INFO,
832 "Pasted %d/%d %s over %d frames",
833 int(sorted_transformables.size()),
834 int(clipboard_data.size()),
835 transformable_type_name,
836 range.max - range.min);
837 }
838 DEG_graph_free(depsgraph);
839}
840
842
843/* -------------------------------------------------------------------- */
846
847enum class CopyRange : uint8_t {
848 /* Use the range provided by the operator. */
850 /* Use the playback range of the scene. This includes the preview range in case it is set. */
852};
853
855 {int(CopyRange::CUSTOM),
856 "CUSTOM",
857 0,
858 "Custom",
859 "Use the range provided in the operator properties"},
861 "PLAYBACK",
862 0,
863 "Playback Range",
864 "Use the playback range of the scene"},
865 {0, nullptr, 0, nullptr, nullptr},
866};
867
869{
871 if (transformables.is_empty()) {
872 BKE_report(op->reports, RPT_ERROR, "Nothing selected to copy");
873 return OPERATOR_CANCELLED;
874 }
875 const CopyRange range_mode = CopyRange(RNA_enum_get(op->ptr, "range_mode"));
877 switch (range_mode) {
879 bounds = {RNA_int_get(op->ptr, "start"), RNA_int_get(op->ptr, "end") + 1};
880 break;
882 Scene *scene = CTX_data_scene(C);
884 bounds = {range.start_frame, range.end_frame + 1};
885 break;
886 }
887
888 default:
889 return OPERATOR_CANCELLED;
890 break;
891 }
892 if (bounds.is_empty()) {
893 BKE_reportf(op->reports, RPT_ERROR, "Invalid frame range %d-%d", bounds.min, bounds.max);
894 return OPERATOR_CANCELLED;
895 }
899 *op->reports,
900 transformables,
901 bounds);
902 return OPERATOR_FINISHED;
903}
904
909
911{
912 ot->name = "Copy World Space Range";
913 ot->idname = "ANIM_OT_world_space_copy";
914 ot->description = "Copy animation from selected elements to the clipboard";
915
918
919 /* No undo possible since this creates data outside the current blend file. */
920 ot->flag = OPTYPE_REGISTER;
921 RNA_def_enum(ot->srna,
922 "range_mode",
925 "Range Mode",
926 "Determines which range should be copied");
928 ot->srna, "start", 0, -INT_MAX, INT_MAX, "Start", "Start frame to copy from", 0, INT_MAX);
930 ot->srna, "end", 250, -INT_MAX, INT_MAX, "End", "End frame to copy from", 0, INT_MAX);
931}
932
933static bool has_constraints(const Span<AnimTransformable> transformables)
934{
935 for (const AnimTransformable &transformable : transformables) {
936 switch (transformable.type()) {
938 bPoseChannel *pose_bone = transformable.data<bPoseChannel *>();
939 if (!pose_bone->constraints.is_empty()) {
940 return true;
941 }
942 break;
943 }
944
946 Object *object = transformable.data<Object *>();
947 if (!object->constraints.is_empty()) {
948 return true;
949 }
950 }
951 }
952 }
953 return false;
954}
955
957{
959 if (transformables.is_empty()) {
960 BKE_report(op->reports, RPT_ERROR, "Nothing selected to paste to");
961 return OPERATOR_CANCELLED;
962 }
963 if (has_constraints(transformables)) {
966 "Selection contains constraints. Perfect world space match cannot be guaranteed");
967 }
968
969 char filepath[FILE_MAX];
970 BLI_path_join(filepath, sizeof(filepath), BKE_tempdir_base(), clipboard_name);
971 Main *clipboard_bmain = BKE_copybuffer_read(
972 *CTX_data_main(C), filepath, op->reports, FILTER_ID_ALL);
973 if (!clipboard_bmain) {
974 BKE_report(op->reports, RPT_ERROR, "No clipboard to read from");
975 return OPERATOR_CANCELLED;
976 }
977 bAction *clipboard_dna_action = read_action_from_clipboard(*clipboard_bmain, *op->reports);
978
979 if (!clipboard_dna_action) {
980 BKE_main_free(clipboard_bmain);
981 return OPERATOR_CANCELLED;
982 }
983
984 const AnimationPasteOffset offset = AnimationPasteOffset(RNA_enum_get(op->ptr, "offset"));
988 *op->reports,
989 *clipboard_dna_action,
990 transformables,
991 offset);
992
993 for (AnimTransformable &transformable : transformables) {
994 DEG_id_tag_update(transformable.owner_id(), ID_RECALC_ANIMATION);
995 WM_event_add_notifier(C, NC_OBJECT | ND_POSE, transformable.owner_id());
996 }
997
998 BKE_main_free(clipboard_bmain);
999 return OPERATOR_FINISHED;
1000}
1001
1006
1009 "NONE",
1010 0,
1011 "No Offset",
1012 "Paste data to the same frames they were copied from"},
1014 "START",
1015 0,
1016 "Start at Current Frame",
1017 "Paste data starting at current frame"},
1018 {0, nullptr, 0, nullptr, nullptr},
1019};
1020
1022{
1023 ot->name = "Paste World Space";
1024 ot->idname = "ANIM_OT_world_space_paste";
1025 ot->description = "Paste the animation from the clipboard to selected elements";
1026
1029
1031
1032 RNA_def_enum(ot->srna,
1033 "offset",
1036 "Frame Offset",
1037 "Paste time offset of keys");
1038}
1039
1041
1042} // namespace blender::ed::animrig
Functions and classes to work with Actions.
Functions to work with AnimData.
Helper functions for animation to interact with the RNA system.
Blender kernel action and pose functionality.
#define FILE_MAX
#define BLI_path_join(...)
#define FILTER_ID_ALL
Definition DNA_ID.h:1241
Defines an abstraction around various structs to modify their transform properties via a unified API ...
#define C
Definition RandGen.cpp:29
#define ND_POSE
Definition WM_types.hh:482
#define NC_OBJECT
Definition WM_types.hh:392
#define BLI_assert_unreachable()
#define BLI_assert_msg(a, msg)
int64_t size() const
Definition BLI_array.hh:267
const T * data() const
Definition BLI_array.hh:323
IndexRange index_range() const
Definition BLI_array.hh:371
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
constexpr IndexRange()=default
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
ValueIterator values() const &
Definition BLI_map.hh:884
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
Value lookup_default(const Key &key, const Value &default_value) const
Definition BLI_map.hh:570
int64_t size() const
Definition BLI_map.hh:976
KeyIterator keys() const &
Definition BLI_map.hh:875
Value & lookup_or_add(const Key &key, const Value &value)
Definition BLI_map.hh:588
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
int64_t size() const
Definition BLI_set.hh:606
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
int64_t size() const
void append(const T &value)
bool is_empty() const
IndexRange index_range() const
void reserve(const int64_t min_capacity)
bool fcurve_remove(FCurve &fcurve_to_remove)
FCurve & fcurve_ensure(Main *bmain, const FCurveDescriptor &fcurve_descriptor)
float4x4 get_world_space(const Depsgraph &depsgraph) const
std::string rna_path_to_property(PropertyType prop_type) const
eRotationModes get_rotation_mode() const
TransformFloats get_property(PropertyType prop_type) const
std::string rna_path_to_rotation_mode() const
float4x4 world_to_local(const Depsgraph &depsgraph, const float4x4 &world_matrix) const
void set_property(PropertyType prop_type, Span< float > values, AxisMutable axis_flag)
#define INT_MAX
float3x3 scale(float3x3 mat, float2 scale)
static Rotation set_keys_to_transform(TransformFCurves &t_fcus, const float4x4 &matrix, const Rotation &reference_rotation, const int paste_index)
const EnumPropertyItem rna_enum_copy_range_items[]
static bool world_space_paste_poll(bContext *C)
static DegComponentIdentifier transformable_to_deg_identifier(const AnimTransformable &transformable)
static void clean_baked_fcurves(AnimTransformable &transformable, AnimTransformable::PropertyType property_type, MutableSpan< PasteFCurve > fcurves, blender::animrig::Channelbag &channelbag)
static Array< TransformFCurves > build_fcurves_for_paste(Main &bmain, const Span< AnimTransformable * > transformables, const Bounds< int > range)
static void matrix_to_fcurves(const float4x4 &matrix, Span< FCurve * > fcurves, const int frame, const int key_index)
constexpr const char * clipboard_name
Map< StringRefNull, Array< FCurve * > > ClipboardData
static float4x4 fcurves_to_matrix(const Span< const FCurve * > fcurves, const int key_index)
static Vector< ID * > get_unique_ids(const Span< AnimTransformable * > transformables)
static Vector< AnimTransformable * > depsgraph_sorted_transformables(const Depsgraph *depsgraph, const MutableSpan< AnimTransformable * > transformables)
static void copy_world_space(Main &bmain, Scene &scene, ViewLayer &view_layer, ReportList &reports, const Span< AnimTransformable > transformables, const Bounds< int > range)
static wmOperatorStatus world_space_paste_exec(bContext *C, wmOperator *op)
Map< AnimTransformable *, StringRefNull > PasteMap
static wmOperatorStatus world_space_copy_exec(bContext *C, wmOperator *op)
static PasteMap generate_paste_mapping(const MutableSpan< AnimTransformable > transformables, const ClipboardData &clipboard_data)
static bAction * read_action_from_clipboard(Main &clipboard_bmain, ReportList &reports)
static bool has_constraints(const Span< AnimTransformable > transformables)
static void ensure_baked_fcurves(Main &bmain, const AnimTransformable &transformable, MutableSpan< PasteFCurve > fcus, blender::animrig::Channelbag &channelbag, const StringRefNull rna_path, const Bounds< int > range)
void ANIM_OT_world_space_paste(wmOperatorType *ot)
static Array< TransformableRelations > build_transformable_relations(const Depsgraph *depsgraph, const MutableSpan< AnimTransformable * > transformables)
static bool world_space_copy_poll(bContext *C)
void ANIM_OT_world_space_copy(wmOperatorType *ot)
static void recalculate_handles(MutableSpan< PasteFCurve > fcurves)
static void paste_world_space(Main &bmain, Scene &scene, ViewLayer &view_layer, ReportList &reports, bAction &clipboard_dna_action, const MutableSpan< AnimTransformable > transformables, const AnimationPasteOffset offset)
static bool is_fcurve_flat(FCurve &fcurve)
const EnumPropertyItem rna_enum_animation_paste_offset_items[]
Array< float, 4 > TransformFloats
Vector< ed::AnimTransformable > selected_transformables_from_context(bContext &C)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
unsigned __int64 uint64_t
Definition BKE_text.h:91
int RNA_enum_get(PointerRNA *ptr, const char *name)
Main * BKE_copybuffer_read(Main &reference_bmain, const char *libname, ReportList *reports, uint64_t id_types_mask)
void BKE_fcurve_keyframe_move_value_with_handles(BezTriple *keyframe, float new_value)
@ RPT_WARNING
Definition BKE_report.hh:40
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void DEG_graph_free(Depsgraph *graph)
Definition depsgraph.cc:307
bool ED_operator_posemode(bContext *C)
void DEG_graph_id_tag_update(Main *bmain, Depsgraph *depsgraph, ID *id, unsigned int flags)
PropertyRNA * RNA_def_enum(StructOrFunctionRNA *cont_, const char *identifier, const EnumPropertyItem *items, const int default_value, const char *ui_name, const char *ui_description)
Depsgraph * DEG_graph_new(Main *bmain, Scene *scene, ViewLayer *view_layer, eEvaluationMode mode)
Definition depsgraph.cc:279
int RNA_int_get(PointerRNA *ptr, const char *name)
MatBase< float, 4, 4 > float4x4
ViewLayer * CTX_data_view_layer(const bContext *C)
ScenePlaybackRange BKE_scene_get_playback_range(const Scene *scene)
Definition scene.cc:2607
AnimData * BKE_animdata_from_id(const ID *id)
Definition anim_data.cc:93
void BKE_fcurve_handles_recalc(FCurve &fcu)
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
void DEG_graph_build_from_ids(Depsgraph *graph, Span< ID * > ids)
unsigned char uint8_t
Definition BKE_text.h:79
@ DAG_EVAL_VIEWPORT
const char * BKE_tempdir_base() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
Definition appdir.cc:1288
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
void BKE_main_free(Main *bmain)
Definition main.cc:202
PropertyRNA * RNA_def_int(StructOrFunctionRNA *cont_, const char *identifier, const int default_value, const int hardmin, const int hardmax, const char *ui_name, const char *ui_description, const int softmin, const int softmax)
bool ED_operator_objectmode(bContext *C)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
Main * CTX_data_main(const bContext *C)
void DEG_foreach_dependent_component(const Depsgraph *depsgraph, const ID *start_id, eDepsObjectComponentType start_component_type, StringRef start_component_name, DEGForeachNamedIDComponentCallback callback)
@ ID_RECALC_ANIMATION
Definition DNA_ID.h:1077
void DEG_evaluate_on_framechange(Depsgraph *graph, float frame, DepsgraphEvaluateSyncWriteback sync_writeback=DEG_EVALUATE_SYNC_WRITEBACK_NO)
Scene * CTX_data_scene(const bContext *C)
int BKE_fcurve_bezt_binarysearch_index(const BezTriple array[], float frame, int arraylen, bool *r_replace)
@ OPTYPE_REGISTER
Definition WM_types.hh:188
@ OPTYPE_UNDO
Definition WM_types.hh:190
VecBase< float, 3 > float3
@ FCURVE_EXTRAPOLATE_CONSTANT
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
void mat4_decompose(float loc[3], float quat[4], float size[3], const float wmat[4][4])
FCurve * BKE_fcurve_create()
#define fabsf
eBezTriple_Interpolation ipo
eFCurve_Extend extend
ListBaseT< FModifier > modifiers
unsigned int totvert
ListBaseT< bAction > actions
Definition BKE_main.hh:408
const c_style_mat & ptr() const
struct RenderData r
ListBaseT< struct bConstraint > constraints
Rotation converted_to_mode(eRotationModes mode, const Rotation *reference_euler=nullptr) const
bool operator==(const DegComponentIdentifier &other) const
blender::animrig::Channelbag * channelbag
Vector< TransformableRelations * > ancestors
wmOperatorStatus(*) exec(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1125
const char * description
Definition WM_types.hh:1115
bool(*) poll(bContext *C) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1165
struct ReportList * reports