Blender V5.3
keyframes_general.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2008 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10#include <cfloat>
11#include <cmath>
12#include <cstdlib>
13#include <cstring>
14#include <iostream>
15#include <variant>
16
17#include "MEM_guardedalloc.h"
18
19#include "BLI_listbase.hh"
20#include "BLI_math_vector_c.hh"
21#include "BLI_string.hh"
22#include "BLI_string_utils.hh"
23#include "BLI_utildefines.hh"
24
25#include "DNA_anim_types.h"
26#include "DNA_object_types.h"
27#include "DNA_scene_types.h"
28#include "DNA_space_types.h"
29
30#include "BKE_action.hh"
31#include "BKE_curve.hh"
32#include "BKE_fcurve.hh"
33#include "BKE_main.hh"
34#include "BKE_scene.hh"
35
36#include "RNA_access.hh"
37#include "RNA_enum_types.hh"
38#include "RNA_path.hh"
39
40#include "ED_keyframes_edit.hh"
41
42#include "ANIM_action.hh"
43#include "ANIM_animdata.hh"
44#include "ANIM_fcurve.hh"
45
47
48namespace blender {
49
50/* This file contains code for various keyframe-editing tools which are 'destructive'
51 * (i.e. they will modify the order of the keyframes, and change the size of the array).
52 * While some of these tools may eventually be moved out into blenkernel, for now, it is
53 * fine to have these calls here.
54 *
55 * There are also a few tools here which cannot be easily coded for in the other system (yet).
56 * These may also be moved around at some point, but for now, they are best added here.
57 *
58 * - Joshua Leung, Dec 2008
59 */
60
61/* -------------------------------------------------------------------- */
64
66{
67 bool changed = false;
68
69 /* this can only work when there is an F-Curve, and also when there are some BezTriples */
70 if (ELEM(nullptr, fcu, fcu->bezt)) {
71 return changed;
72 }
73
74 for (int i = 0; i < fcu->totvert; i++) {
75 /* If a key is selected */
76 if (fcu->bezt[i].f2 & SELECT) {
77 /* Expand the list */
78 BezTriple *newbezt = MEM_new_array_zeroed<BezTriple>((fcu->totvert + 1), "beztriple");
79
80 memcpy(newbezt, fcu->bezt, sizeof(BezTriple) * (i + 1));
81 memcpy(newbezt + i + 1, fcu->bezt + i, sizeof(BezTriple));
82 memcpy(newbezt + i + 2, fcu->bezt + i + 1, sizeof(BezTriple) * (fcu->totvert - (i + 1)));
83 fcu->totvert++;
84 changed = true;
85 /* reassign pointers... (free old, and add new) */
86 MEM_delete(fcu->bezt);
87 fcu->bezt = newbezt;
88
89 /* Unselect the current key */
90 BEZT_DESEL_ALL(&fcu->bezt[i]);
91 i++;
92
93 /* Select the copied key */
94 BEZT_SEL_ALL(&fcu->bezt[i]);
95 }
96 }
97 return changed;
98}
99
101
102/* -------------------------------------------------------------------- */
105
107 float thresh,
108 bool cleardefault,
109 const bool only_selected_keys)
110{
111 FCurve *fcu = static_cast<FCurve *>(ale->key_data);
112 BezTriple *old_bezts, *bezt, *beztn;
113 BezTriple *lastb;
114 int totCount, i;
115
116 /* Check if any points. */
117 if ((fcu == nullptr) || (fcu->bezt == nullptr) || (fcu->totvert == 0) ||
118 (!cleardefault && fcu->totvert == 1))
119 {
120 return;
121 }
122
123 /* make a copy of the old BezTriples, and clear F-Curve */
124 old_bezts = fcu->bezt;
125 totCount = fcu->totvert;
126 fcu->bezt = nullptr;
127 fcu->totvert = 0;
128
129 /* now insert first keyframe, as it should be ok */
130 bezt = old_bezts;
132 if (!(bezt->f2 & SELECT)) {
133 lastb = fcu->bezt;
134 lastb->f1 = lastb->f2 = lastb->f3 = eBezTriple_Flag{};
135 }
136
137 /* Loop through BezTriples, comparing them. Skip any that do
138 * not fit the criteria for "ok" points.
139 */
140 for (i = 1; i < totCount; i++) {
141 float prev[2], cur[2], next[2];
142
143 /* get BezTriples and their values */
144 if (i < (totCount - 1)) {
145 beztn = (old_bezts + (i + 1));
146 next[0] = beztn->vec[1][0];
147 next[1] = beztn->vec[1][1];
148 }
149 else {
150 beztn = nullptr;
151 next[0] = next[1] = 0.0f;
152 }
153 lastb = (fcu->bezt + (fcu->totvert - 1));
154 bezt = (old_bezts + i);
155
156 /* get references for quicker access */
157 prev[0] = lastb->vec[1][0];
158 prev[1] = lastb->vec[1][1];
159 cur[0] = bezt->vec[1][0];
160 cur[1] = bezt->vec[1][1];
161
162 if (only_selected_keys && !(bezt->f2 & SELECT)) {
164 lastb = (fcu->bezt + (fcu->totvert - 1));
165 lastb->f1 = lastb->f2 = lastb->f3 = eBezTriple_Flag{};
166 continue;
167 }
168
169 /* check if current bezt occurs at same time as last ok */
170 if (IS_EQT(cur[0], prev[0], thresh)) {
171 /* If there is a next beztriple, and if occurs at the same time, only insert
172 * if there is a considerable distance between the points, and also if the
173 * current is further away than the next one is to the previous.
174 */
175 if (beztn && IS_EQT(cur[0], next[0], thresh) && (IS_EQT(next[1], prev[1], thresh) == 0)) {
176 /* only add if current is further away from previous */
177 if (cur[1] > next[1]) {
178 if (IS_EQT(cur[1], prev[1], thresh) == 0) {
179 /* add new keyframe */
181 }
182 }
183 }
184 else {
185 /* only add if values are a considerable distance apart */
186 if (IS_EQT(cur[1], prev[1], thresh) == 0) {
187 /* add new keyframe */
189 }
190 }
191 }
192 else {
193 /* checks required are dependent on whether this is last keyframe or not */
194 if (beztn) {
195 /* does current have same value as previous and next? */
196 if (IS_EQT(cur[1], prev[1], thresh) == 0) {
197 /* add new keyframe */
199 }
200 else if (IS_EQT(cur[1], next[1], thresh) == 0) {
201 /* add new keyframe */
203 }
204 }
205 else {
206 /* add if value doesn't equal that of previous */
207 if (IS_EQT(cur[1], prev[1], thresh) == 0) {
208 /* add new keyframe */
210 }
211 }
212 }
213 }
214
215 /* now free the memory used by the old BezTriples */
216 if (old_bezts) {
217 MEM_delete(old_bezts);
218 }
219
220 /* final step, if there is just one key in fcurve, check if it's
221 * the default value and if is, remove fcurve completely. */
222 if (cleardefault && fcu->totvert == 1) {
223 float default_value = 0.0f;
224 PointerRNA ptr;
225 PropertyRNA *prop;
226 PointerRNA id_ptr = RNA_id_pointer_create(ale->id);
227
228 /* get property to read from, and get value as appropriate */
229 if (RNA_path_resolve_property(&id_ptr, fcu->rna_path_parsed(), &ptr, &prop)) {
230 if (RNA_property_type(prop) == PROP_FLOAT) {
231 default_value = RNA_property_float_get_default_index(&ptr, prop, fcu->array_index);
232 }
233 }
234
235 if (fcu->bezt->vec[1][1] == default_value) {
237
238 /* check if curve is really unused and if it is, return signal for deletion */
239 if (BKE_fcurve_is_empty(fcu)) {
240 AnimData *adt = ale->adt;
242 ale->key_data = nullptr;
243 }
244 }
245 }
246}
247
256 const int start_index,
257 int *r_segment_start_idx,
258 int *r_segment_len)
259{
260 *r_segment_start_idx = 0;
261 *r_segment_len = 0;
262
263 bool in_segment = false;
264
265 for (int i = start_index; i < fcu->totvert; i++) {
266 const bool point_is_selected = fcu->bezt[i].f2 & SELECT;
267 const bool point_is_ignored = fcu->bezt[i].f2 & BEZT_FLAG_IGNORE_TAG;
268
269 if (point_is_selected && !point_is_ignored) {
270 if (!in_segment) {
271 *r_segment_start_idx = i;
272 in_segment = true;
273 }
274 (*r_segment_len)++;
275 }
276 else if (in_segment) {
277 /* If the curve point is not selected then we have reached the end of the selected curve
278 * segment. */
279 return true; /* Segment found. */
280 }
281 }
282
283 /* If the last curve point was in the segment, `r_segment_len` and `r_segment_start_idx`
284 * are already updated and true is returned. */
285 return in_segment;
286}
287
288ListBaseT<FCurveSegment> find_fcurve_segments(FCurve *fcu)
289{
290 ListBaseT<FCurveSegment> segments = {nullptr, nullptr};
291
292 /* Ignore baked curves. */
293 if (!fcu->bezt) {
294 return segments;
295 }
296
297 int segment_start_idx = 0;
298 int segment_len = 0;
299 int current_index = 0;
300
301 while (find_fcurve_segment(fcu, current_index, &segment_start_idx, &segment_len)) {
302 FCurveSegment *segment;
303 segment = MEM_new_zeroed<FCurveSegment>("FCurveSegment");
304 segment->start_index = segment_start_idx;
305 segment->length = segment_len;
306 BLI_addtail(&segments, segment);
307 current_index = segment_start_idx + segment_len;
308 }
309 return segments;
310}
311
313{
314 const BezTriple *start_bezt = index - 1 >= 0 ? &fcu->bezt[index - 1] : &fcu->bezt[index];
315 return start_bezt;
316}
317
319{
320 const BezTriple *end_bezt = index < fcu->totvert ? &fcu->bezt[index] : &fcu->bezt[index - 1];
321 return end_bezt;
322}
323
324/* ---------------- */
325
326void blend_to_neighbor_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
327{
328 const BezTriple *target_bezt;
329 /* Find which key to blend towards. */
330 if (factor < 0) {
331 target_bezt = fcurve_segment_start_get(fcu, segment->start_index);
332 }
333 else {
334 target_bezt = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
335 }
336 const float lerp_factor = fabs(factor);
337 /* Blend each key individually. */
338 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
339 const float key_y_value = interpf(target_bezt->vec[1][1], fcu->bezt[i].vec[1][1], lerp_factor);
341 }
342}
343
344/* ---------------- */
345
347{
348 const int len = RNA_property_array_length(ptr, prop);
349
350 float default_value = 0;
351 /* Find the default value of that property. */
352 switch (RNA_property_type(prop)) {
353 case PROP_BOOLEAN:
354 if (len) {
355 default_value = float(RNA_property_boolean_get_default_index(ptr, prop, fcu->array_index));
356 }
357 else {
358 default_value = float(RNA_property_boolean_get_default(ptr, prop));
359 }
360 break;
361 case PROP_INT:
362 if (len) {
363 default_value = RNA_property_int_get_default_index(ptr, prop, fcu->array_index);
364 }
365 else {
366 default_value = RNA_property_int_get_default(ptr, prop);
367 }
368 break;
369 case PROP_FLOAT:
370 if (len) {
371 default_value = RNA_property_float_get_default_index(ptr, prop, fcu->array_index);
372 }
373 else {
374 default_value = RNA_property_float_get_default(ptr, prop);
375 }
376 break;
377
378 default:
379 break;
380 }
381 return default_value;
382}
383
384void blend_to_default_fcurve(PointerRNA *id_ptr, FCurve *fcu, const float factor)
385{
386 PointerRNA ptr;
387 PropertyRNA *prop;
388
389 /* Check if path is valid. */
390 if (!RNA_path_resolve_property(id_ptr, fcu->rna_path_parsed(), &ptr, &prop)) {
391 return;
392 }
393
394 const float default_value = get_default_rna_value(fcu, prop, &ptr);
395
396 /* Blend selected keys to default. */
397 for (int i = 0; i < fcu->totvert; i++) {
398 if (!(fcu->bezt[i].f2 & SELECT)) {
399 continue;
400 }
401 const float key_y_value = interpf(default_value, fcu->bezt[i].vec[1][1], factor);
403 }
404}
405
406/* ---------------- */
407
408void scale_average_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
409{
410 float y = 0;
411
412 /* Find first the average of the y values to then use it in the final calculation. */
413 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
414 y += fcu->bezt[i].vec[1][1];
415 }
416
417 const float y_average = y / segment->length;
418
419 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
420 const float key_y_value = interpf(y_average, fcu->bezt[i].vec[1][1], 1 - factor);
422 }
423}
424
425/* ---------------- */
426
428 double *A, *d1, *d2;
430};
431
433{
435 "Butterworth Coefficients");
436 bw_coeff->filter_order = filter_order;
437 bw_coeff->d1 = MEM_new_array_zeroed<double>(filter_order, "coeff filtered");
438 bw_coeff->d2 = MEM_new_array_zeroed<double>(filter_order, "coeff samples");
439 bw_coeff->A = MEM_new_array_zeroed<double>(filter_order, "Butterworth A");
440 return bw_coeff;
441}
442
444{
445 MEM_delete(bw_coeff->d1);
446 MEM_delete(bw_coeff->d2);
447 MEM_delete(bw_coeff->A);
448 MEM_delete(bw_coeff);
449}
450
451void ED_anim_calculate_butterworth_coefficients(const float cutoff_frequency,
452 const float sampling_frequency,
453 ButterworthCoefficients *bw_coeff)
454{
455 double s = double(sampling_frequency);
456 const double a = tan(M_PI * cutoff_frequency / s);
457 const double a2 = a * a;
458 double r;
459 for (int i = 0; i < bw_coeff->filter_order; ++i) {
460 r = sin(M_PI * (2.0 * i + 1.0) / (4.0 * bw_coeff->filter_order));
461 s = a2 + 2.0 * a * r + 1.0;
462 bw_coeff->A[i] = a2 / s;
463 bw_coeff->d1[i] = 2.0 * (1 - a2) / s;
464 bw_coeff->d2[i] = -(a2 - 2.0 * a * r + 1.0) / s;
465 }
466}
467
469 double x, double *w0, double *w1, double *w2, ButterworthCoefficients *bw_coeff)
470{
471 for (int i = 0; i < bw_coeff->filter_order; i++) {
472 w0[i] = bw_coeff->d1[i] * w1[i] + bw_coeff->d2[i] * w2[i] + x;
473 x = bw_coeff->A[i] * (w0[i] + 2.0 * w1[i] + w2[i]);
474 w2[i] = w1[i];
475 w1[i] = w0[i];
476 }
477 return x;
478}
479
480static float butterworth_calculate_blend_value(float *samples,
481 const float *filtered_values,
482 const int start_index,
483 const int end_index,
484 const int sample_index,
485 const int blend_in_out)
486{
487 if (start_index == end_index || blend_in_out == 0) {
488 return samples[start_index];
489 }
490
491 const float blend_in_y_samples = samples[start_index];
492 const float blend_out_y_samples = samples[end_index];
493
494 const float blend_in_y_filtered = filtered_values[start_index + blend_in_out];
495 const float blend_out_y_filtered = filtered_values[end_index - blend_in_out];
496
497 const float slope_in_samples = samples[start_index] - samples[start_index - 1];
498 const float slope_out_samples = samples[end_index] - samples[end_index + 1];
499 const float slope_in_filtered = filtered_values[start_index + blend_in_out - 1] -
500 filtered_values[start_index + blend_in_out];
501 const float slope_out_filtered = filtered_values[end_index - blend_in_out] -
502 filtered_values[end_index - blend_in_out - 1];
503
504 if (sample_index - start_index <= blend_in_out) {
505 const int blend_index = sample_index - start_index;
506 const float blend_in_out_factor = clamp_f(float(blend_index) / blend_in_out, 0.0f, 1.0f);
507 const float blend_value = interpf(blend_in_y_filtered +
508 slope_in_filtered * (blend_in_out - blend_index),
509 blend_in_y_samples + slope_in_samples * blend_index,
510 blend_in_out_factor);
511 return blend_value;
512 }
513 if (end_index - sample_index <= blend_in_out) {
514 const int blend_index = end_index - sample_index;
515 const float blend_in_out_factor = clamp_f(float(blend_index) / blend_in_out, 0.0f, 1.0f);
516 const float blend_value = interpf(blend_out_y_filtered +
517 slope_out_filtered * (blend_in_out - blend_index),
518 blend_out_y_samples + slope_out_samples * blend_index,
519 blend_in_out_factor);
520 return blend_value;
521 }
522 return 0;
523}
524
526 FCurveSegment *segment,
527 float *samples,
528 const int sample_count,
529 const float factor,
530 const int blend_in_out,
531 const int sample_rate,
532 ButterworthCoefficients *bw_coeff)
533{
534 const int filter_order = bw_coeff->filter_order;
535
536 float *filtered_values = MEM_new_array_zeroed<float>(sample_count,
537 "Butterworth Filtered FCurve Values");
538
539 double *w0 = MEM_new_array_zeroed<double>(filter_order, "w0");
540 double *w1 = MEM_new_array_zeroed<double>(filter_order, "w1");
541 double *w2 = MEM_new_array_zeroed<double>(filter_order, "w2");
542
543 /* The values need to be offset so the first sample starts at 0. This avoids oscillations at the
544 * start and end of the curve. */
545 const float fwd_offset = samples[0];
546
547 for (int i = 0; i < sample_count; i++) {
548 const double x = double(samples[i] - fwd_offset);
549 const double filtered_value = butterworth_filter_value(x, w0, w1, w2, bw_coeff);
550 filtered_values[i] = float(filtered_value) + fwd_offset;
551 }
552
553 for (int i = 0; i < filter_order; i++) {
554 w0[i] = 0.0;
555 w1[i] = 0.0;
556 w2[i] = 0.0;
557 }
558
559 const float bwd_offset = filtered_values[sample_count - 1];
560
561 /* Run the filter backwards as well to remove phase offset. */
562 for (int i = sample_count - 1; i >= 0; i--) {
563 const double x = double(filtered_values[i] - bwd_offset);
564 const double filtered_value = butterworth_filter_value(x, w0, w1, w2, bw_coeff);
565 filtered_values[i] = float(filtered_value) + bwd_offset;
566 }
567
568 const int segment_end_index = segment->start_index + segment->length;
569 BezTriple left_bezt = fcu->bezt[segment->start_index];
570 BezTriple right_bezt = fcu->bezt[segment_end_index - 1];
571
572 const int samples_start_index = filter_order * sample_rate;
573 const int samples_end_index = int(right_bezt.vec[1][0] - left_bezt.vec[1][0] + filter_order) *
574 sample_rate;
575
576 const int blend_in_out_clamped = min_ii(blend_in_out,
577 (samples_end_index - samples_start_index) / 2);
578
579 for (int i = segment->start_index; i < segment_end_index; i++) {
580 float blend_in_out_factor;
581 if (blend_in_out_clamped == 0) {
582 blend_in_out_factor = 1;
583 }
584 else if (i < segment->start_index + segment->length / 2) {
585 blend_in_out_factor = min_ff(float(i - segment->start_index) / blend_in_out_clamped, 1.0f);
586 }
587 else {
588 blend_in_out_factor = min_ff(float(segment_end_index - i - 1) / blend_in_out_clamped, 1.0f);
589 }
590
591 const float x_delta = fcu->bezt[i].vec[1][0] - left_bezt.vec[1][0] + filter_order;
592 /* Using round() instead of casting to int. Casting would introduce a stepping issue when the
593 * x-value is just below a full frame. */
594 const int filter_index = round(x_delta * sample_rate);
595 const float blend_value = butterworth_calculate_blend_value(samples,
596 filtered_values,
597 samples_start_index,
598 samples_end_index,
599 filter_index,
600 blend_in_out_clamped);
601
602 const float blended_value = interpf(
603 filtered_values[filter_index], blend_value, blend_in_out_factor);
604 const float key_y_value = interpf(blended_value, samples[filter_index], factor);
605
607 }
608
609 MEM_delete(filtered_values);
610 MEM_delete(w0);
611 MEM_delete(w1);
612 MEM_delete(w2);
613}
614
615/* ---------------- */
616
617void ED_ANIM_get_1d_gauss_kernel(const float sigma, const int kernel_size, double *r_kernel)
618{
619 BLI_assert(sigma > 0.0f);
620 BLI_assert(kernel_size > 0);
621 const double sigma_sq = 2.0 * sigma * sigma;
622 double sum = 0.0;
623
624 for (int i = 0; i < kernel_size; i++) {
625 const double normalized_index = double(i) / (kernel_size - 1);
626 r_kernel[i] = exp(-normalized_index * normalized_index / sigma_sq);
627 if (i == 0) {
628 sum += r_kernel[i];
629 }
630 else {
631 /* We only calculate half the kernel,
632 * the normalization needs to take that into account. */
633 sum += r_kernel[i] * 2;
634 }
635 }
636
637 /* Normalize kernel values. */
638 for (int i = 0; i < kernel_size; i++) {
639 r_kernel[i] /= sum;
640 }
641}
642
644 FCurveSegment *segment,
645 const float *original_values,
646 float *samples,
647 const int sample_count,
648 const float factor,
649 const int kernel_size,
650 const double *kernel)
651{
652 const int segment_end_index = segment->start_index + segment->length;
653 const float segment_start_x = fcu->bezt[segment->start_index].vec[1][0];
654 float *filtered_samples = MEM_dupalloc(samples);
655 for (int i = kernel_size; i < sample_count - kernel_size; i++) {
656 /* Apply the kernel. */
657 double filter_result = samples[i] * kernel[0];
658 for (int j = 1; j <= kernel_size; j++) {
659 const double kernel_value = kernel[j];
660 filter_result += samples[i + j] * kernel_value;
661 filter_result += samples[i - j] * kernel_value;
662 }
663 filtered_samples[i] = filter_result;
664 }
665
666 for (int i = segment->start_index; i < segment_end_index; i++) {
667 const float sample_index_f = (fcu->bezt[i].vec[1][0] - segment_start_x) + kernel_size;
668 /* Using round() instead of (int). The latter would create stepping on x-values that are just
669 * below a full frame. */
670 const int sample_index = round(sample_index_f);
671 /* Sampling the two closest indices to support subframe keys. This can end up being the same
672 * index as sample_index, in which case the interpolation will happen between two identical
673 * values. */
674 const int secondary_index = clamp_i(
675 sample_index + signum_i(sample_index_f - sample_index), 0, sample_count - 1);
676
677 const float filter_result = interpf(filtered_samples[secondary_index],
678 filtered_samples[sample_index],
679 std::abs(sample_index_f - sample_index));
680 const float key_y_value = interpf(
681 filter_result, original_values[i - segment->start_index], factor);
683 }
684 MEM_delete(filtered_samples);
685}
686/* ---------------- */
687
688static float ease_sigmoid_function(const float x, const float width, const float shift)
689{
690 const float x_shift = (x - shift) * width;
691 const float y = x_shift / sqrt(1 + pow2f(x_shift));
692 /* Normalize result to 0-1. */
693 return (y + 1) * 0.5f;
694}
695
697 FCurveSegment *segment,
698 const float factor,
699 const float width)
700{
701 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
702 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
703
704 const float key_x_range = right_key->vec[1][0] - left_key->vec[1][0];
705 const float key_y_range = right_key->vec[1][1] - left_key->vec[1][1];
706
707 /* Happens if there is only 1 key on the FCurve. Needs to be skipped because it
708 * would be a divide by 0. */
709 if (IS_EQF(key_x_range, 0.0f)) {
710 return;
711 }
712
713 /* Using the factor on the X-shift we are basically moving the curve horizontally. */
714 const float shift = -factor;
715 const float y_min = ease_sigmoid_function(-1, width, shift);
716 const float y_max = ease_sigmoid_function(1, width, shift);
717
718 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
719 /* Mapping the x-location of the key within the segment to a -1/1 range. */
720 const float x = ((fcu->bezt[i].vec[1][0] - left_key->vec[1][0]) / key_x_range) * 2 - 1;
721 const float y = ease_sigmoid_function(x, width, shift);
722 /* Normalizing the y value to the min and max to ensure that the keys at the end are not
723 * detached from the rest of the animation. */
724 const float blend = (y - y_min) * (1 / (y_max - y_min));
725
726 const float key_y_value = left_key->vec[1][1] + key_y_range * blend;
728 }
729}
730
731/* ---------------- */
732
733void blend_offset_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
734{
735 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
736 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
737
738 float y_delta;
739
740 if (factor > 0) {
741 const BezTriple segment_last_key = fcu->bezt[segment->start_index + segment->length - 1];
742 y_delta = right_key->vec[1][1] - segment_last_key.vec[1][1];
743 }
744 else {
745 const BezTriple segment_first_key = fcu->bezt[segment->start_index];
746 y_delta = left_key->vec[1][1] - segment_first_key.vec[1][1];
747 }
748
749 const float offset_value = y_delta * fabs(factor);
750 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
751 const float key_y_value = fcu->bezt[i].vec[1][1] + offset_value;
753 }
754}
755
756/* ---------------- */
757
758static float s_curve(float x, float slope, float width, float height, float xshift, float yshift)
759{
760 /* Formula for 'S' curve we use for the "ease" sliders.
761 * The shift values move the curve vertically or horizontally.
762 * The range of the curve used is from 0 to 1 on "x" and "y"
763 * so we can scale it (width and height) and move it (`xshift` and y `yshift`)
764 * to crop the part of the curve we need. Slope determines how curvy the shape is. */
765 float y = height * pow((x - xshift), slope) /
766 (pow((x - xshift), slope) + pow((width - (x - xshift)), slope)) +
767 yshift;
768
769 /* The curve doesn't do what we want beyond our margins so we clamp the values. */
770 if (x > xshift + width) {
771 y = height + yshift;
772 }
773 else if (x < xshift) {
774 y = yshift;
775 }
776 return y;
777}
778
779void blend_to_ease_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
780{
781 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
782 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
783
784 const float key_x_range = right_key->vec[1][0] - left_key->vec[1][0];
785 const float key_y_range = right_key->vec[1][1] - left_key->vec[1][1];
786
787 /* Happens if there is only 1 key on the FCurve. Needs to be skipped because it
788 * would be a divide by 0. */
789 if (IS_EQF(key_x_range, 0.0f)) {
790 return;
791 }
792
793 const float slope = 3.0;
794 /* By doubling the size of the "S" curve we just one side of it, a "C" shape. */
795 const float width = 2.0;
796 const float height = 2.0;
797 float xy_shift;
798
799 /* Shifting the x and y values we can decide what side of the "S" shape to use. */
800 if (factor > 0) {
801 xy_shift = -1.0;
802 }
803 else {
804 xy_shift = 0.0;
805 }
806
807 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
808
809 const float x = (fcu->bezt[i].vec[1][0] - left_key->vec[1][0]) / key_x_range;
810 const float ease = s_curve(x, slope, width, height, xy_shift, xy_shift);
811 const float base = left_key->vec[1][1] + key_y_range * ease;
812
813 float y_delta;
814 if (factor > 0) {
815 y_delta = base - fcu->bezt[i].vec[1][1];
816 }
817 else {
818 y_delta = fcu->bezt[i].vec[1][1] - base;
819 }
820
821 const float key_y_value = fcu->bezt[i].vec[1][1] + y_delta * factor;
823 }
824}
825
826/* ---------------- */
827
828bool match_slope_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
829{
830 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
831 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
832
833 BezTriple beyond_key;
834 const BezTriple *reference_key;
835
836 if (factor >= 0) {
837 /* Stop the function if there is no key beyond the right neighboring one. */
838 if (segment->start_index + segment->length >= fcu->totvert - 1) {
839 return false;
840 }
841 reference_key = right_key;
842 beyond_key = fcu->bezt[segment->start_index + segment->length + 1];
843 }
844 else {
845 /* Stop the function if there is no key beyond the left neighboring one. */
846 if (segment->start_index <= 1) {
847 return false;
848 }
849 reference_key = left_key;
850 beyond_key = fcu->bezt[segment->start_index - 2];
851 }
852
853 /* This delta values are used to get the relationship between the bookend keys and the
854 * reference keys beyond those. */
855 const float y_delta = beyond_key.vec[1][1] - reference_key->vec[1][1];
856 const float x_delta = beyond_key.vec[1][0] - reference_key->vec[1][0];
857
858 /* Avoids dividing by 0. */
859 if (x_delta == 0) {
860 return false;
861 }
862
863 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
864
865 /* These new deltas are used to determine the relationship between the current key and the
866 * bookend ones. */
867 const float new_x_delta = fcu->bezt[i].vec[1][0] - reference_key->vec[1][0];
868 const float new_y_delta = new_x_delta * y_delta / x_delta;
869
870 const float delta = reference_key->vec[1][1] + new_y_delta - fcu->bezt[i].vec[1][1];
871
872 const float key_y_value = fcu->bezt[i].vec[1][1] + delta * fabs(factor);
874 }
875 return true;
876}
877
878/* ---------------- */
879
881 FCurveSegment *segment,
882 const float factor,
883 tShearDirection direction)
884{
885 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
886 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
887
888 const float key_x_range = right_key->vec[1][0] - left_key->vec[1][0];
889 const float key_y_range = right_key->vec[1][1] - left_key->vec[1][1];
890
891 /* Happens if there is only 1 key on the FCurve. Needs to be skipped because it
892 * would be a divide by 0. */
893 if (IS_EQF(key_x_range, 0.0f)) {
894 return;
895 }
896
897 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
898 /* For easy calculation of the curve, the values are normalized. */
899 float normalized_x;
900 if (direction == SHEAR_FROM_LEFT) {
901 normalized_x = (fcu->bezt[i].vec[1][0] - left_key->vec[1][0]) / key_x_range;
902 }
903 else {
904 normalized_x = (right_key->vec[1][0] - fcu->bezt[i].vec[1][0]) / key_x_range;
905 }
906
907 const float y_delta = key_y_range * normalized_x;
908
909 const float key_y_value = fcu->bezt[i].vec[1][1] + y_delta * factor;
911 }
912}
913
914/* ---------------- */
915
916void push_pull_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
917{
918 const BezTriple *left_key = fcurve_segment_start_get(fcu, segment->start_index);
919 const BezTriple *right_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
920
921 const float key_x_range = right_key->vec[1][0] - left_key->vec[1][0];
922 const float key_y_range = right_key->vec[1][1] - left_key->vec[1][1];
923
924 /* Happens if there is only 1 key on the FCurve. Needs to be skipped because it
925 * would be a divide by 0. */
926 if (IS_EQF(key_x_range, 0.0f)) {
927 return;
928 }
929
930 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
931 /* For easy calculation of the curve, the values are normalized. */
932 const float normalized_x = (fcu->bezt[i].vec[1][0] - left_key->vec[1][0]) / key_x_range;
933
934 const float linear = left_key->vec[1][1] + key_y_range * normalized_x;
935
936 const float delta = fcu->bezt[i].vec[1][1] - linear;
937
938 const float key_y_value = linear + delta * factor;
940 }
941}
942
943/* ---------------- */
944
945void time_offset_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float frame_offset)
946{
947 /* Two bookend keys of the fcurve are needed to be able to cycle the values. */
948 const BezTriple *last_key = &fcu->bezt[fcu->totvert - 1];
949 const BezTriple *first_key = &fcu->bezt[0];
950
951 const float fcu_x_range = last_key->vec[1][0] - first_key->vec[1][0];
952 const float fcu_y_range = last_key->vec[1][1] - first_key->vec[1][1];
953
954 const float first_key_x = first_key->vec[1][0];
955
956 /* If we operate directly on the fcurve there will be a feedback loop
957 * so we need to capture the "y" values on an array to then apply them on a second loop. */
958 float *y_values = MEM_new_array_zeroed<float>(segment->length, "Time Offset Samples");
959
960 for (int i = 0; i < segment->length; i++) {
961 /* This simulates the fcu curve moving in time. */
962 const float time = fcu->bezt[segment->start_index + i].vec[1][0] + frame_offset;
963 /* Need to normalize time to first_key to specify that as the wrapping point. */
964 const float wrapped_time = floored_fmod(time - first_key_x, fcu_x_range) + first_key_x;
965 const float delta_y = fcu_y_range * floorf((time - first_key_x) / fcu_x_range);
966
967 const float key_y_value = evaluate_fcurve(fcu, wrapped_time) + delta_y;
968 y_values[i] = key_y_value;
969 }
970
971 for (int i = 0; i < segment->length; i++) {
972 BKE_fcurve_keyframe_move_value_with_handles(&fcu->bezt[segment->start_index + i], y_values[i]);
973 }
974 MEM_delete(y_values);
975}
976
977/* ---------------- */
978
980 FCurveSegment *segment,
981 const float factor,
982 const FCurveSegmentAnchor anchor)
983{
984 const BezTriple *reference_key;
985 switch (anchor) {
987 reference_key = fcurve_segment_start_get(fcu, segment->start_index);
988 break;
990 reference_key = fcurve_segment_end_get(fcu, segment->start_index + segment->length);
991 break;
992 }
993
994 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
995 const float key_y_value = interpf(fcu->bezt[i].vec[1][1], reference_key->vec[1][1], factor);
997 }
998}
999
1000/* ---------------- */
1001
1002void breakdown_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
1003{
1004 const BezTriple *left_bezt = fcurve_segment_start_get(fcu, segment->start_index);
1005 const BezTriple *right_bezt = fcurve_segment_end_get(fcu,
1006 segment->start_index + segment->length);
1007
1008 const float lerp_factor = (factor + 1) / 2;
1009 for (int i = segment->start_index; i < segment->start_index + segment->length; i++) {
1010 const float key_y_value = interpf(right_bezt->vec[1][1], left_bezt->vec[1][1], lerp_factor);
1012 }
1013}
1014
1016
1017/* -------------------------------------------------------------------- */
1020
1021/* Check if the keyframe interpolation type is supported */
1022static bool prepare_for_decimate(FCurve *fcu, int i)
1023{
1024 switch (fcu->bezt[i].ipo) {
1025 case BEZT_IPO_BEZ:
1026 /* We do not need to do anything here as the keyframe already has the required setting.
1027 */
1028 return true;
1029 case BEZT_IPO_LIN:
1030 /* Convert to a linear bezt curve to be able to use the decimation algorithm. */
1031 fcu->bezt[i].ipo = BEZT_IPO_BEZ;
1032 fcu->bezt[i].h1 = HD_FREE;
1033 fcu->bezt[i].h2 = HD_FREE;
1034
1035 if (i != 0) {
1036 float h1[3];
1037 sub_v3_v3v3(h1, fcu->bezt[i - 1].vec[1], fcu->bezt[i].vec[1]);
1038 mul_v3_fl(h1, 1.0f / 3.0f);
1039 add_v3_v3(h1, fcu->bezt[i].vec[1]);
1040 copy_v3_v3(fcu->bezt[i].vec[0], h1);
1041 }
1042
1043 if (i + 1 != fcu->totvert) {
1044 float h2[3];
1045 sub_v3_v3v3(h2, fcu->bezt[i + 1].vec[1], fcu->bezt[i].vec[1]);
1046 mul_v3_fl(h2, 1.0f / 3.0f);
1047 add_v3_v3(h2, fcu->bezt[i].vec[1]);
1048 copy_v3_v3(fcu->bezt[i].vec[2], h2);
1049 }
1050 return true;
1051 default:
1052 /* These are unsupported. */
1053 return false;
1054 }
1055}
1056
1057/* Decimate the given curve segment. */
1059 int bezt_segment_start_idx,
1060 int bezt_segment_len,
1061 float remove_ratio,
1062 float error_sq_max)
1063{
1064 int selected_len = bezt_segment_len;
1065
1066 /* Make sure that we can remove the start/end point of the segment if they
1067 * are not the start/end point of the curve. BKE_curve_decimate_bezt_array
1068 * has a check that prevents removal of the first and last index in the
1069 * passed array. */
1070 if (bezt_segment_len + bezt_segment_start_idx != fcu->totvert &&
1071 prepare_for_decimate(fcu, bezt_segment_len + bezt_segment_start_idx))
1072 {
1073 bezt_segment_len++;
1074 }
1075 if (bezt_segment_start_idx != 0 && prepare_for_decimate(fcu, bezt_segment_start_idx - 1)) {
1076 bezt_segment_start_idx--;
1077 bezt_segment_len++;
1078 }
1079
1080 const int target_fcurve_verts = ceil(bezt_segment_len - selected_len * remove_ratio);
1081
1082 BKE_curve_decimate_bezt_array(&fcu->bezt[bezt_segment_start_idx],
1083 bezt_segment_len,
1084 12, /* The actual resolution displayed in the viewport is dynamic
1085 * so we just pick a value that preserves the curve shape. */
1086 false,
1089 error_sq_max,
1090 target_fcurve_verts);
1091}
1092
1093bool decimate_fcurve(bAnimListElem *ale, float remove_ratio, float error_sq_max)
1094{
1095 FCurve *fcu = static_cast<FCurve *>(ale->key_data);
1096 /* Check if the curve actually has any points. */
1097 if (fcu == nullptr || fcu->bezt == nullptr || fcu->totvert == 0) {
1098 return true;
1099 }
1100
1101 BezTriple *old_bezts = fcu->bezt;
1102
1103 bool can_decimate_all_selected = true;
1104
1105 for (int i = 0; i < fcu->totvert; i++) {
1106 /* Ignore keyframes that are not supported. */
1107 if (!prepare_for_decimate(fcu, i)) {
1108 can_decimate_all_selected = false;
1109 fcu->bezt[i].f2 |= BEZT_FLAG_IGNORE_TAG;
1110 }
1111 /* Make sure that the temp flag is unset as we use it to determine what to remove. */
1112 fcu->bezt[i].f2 &= ~BEZT_FLAG_TEMP_TAG;
1113 }
1114
1115 ListBaseT<FCurveSegment> segments = find_fcurve_segments(fcu);
1116 for (FCurveSegment &segment : segments) {
1117 decimate_fcurve_segment(fcu, segment.start_index, segment.length, remove_ratio, error_sq_max);
1118 }
1119 segments.free_no_destruct();
1120
1121 uint old_totvert = fcu->totvert;
1122 fcu->bezt = nullptr;
1123 fcu->totvert = 0;
1124
1125 for (int i = 0; i < old_totvert; i++) {
1126 BezTriple *bezt = (old_bezts + i);
1127 bezt->f2 &= ~BEZT_FLAG_IGNORE_TAG;
1128 if ((bezt->f2 & BEZT_FLAG_TEMP_TAG) == 0) {
1130 }
1131 }
1132 /* now free the memory used by the old BezTriples */
1133 if (old_bezts) {
1134 MEM_delete(old_bezts);
1135 }
1136
1137 return can_decimate_all_selected;
1138}
1139
1141
1142/* -------------------------------------------------------------------- */
1145
1146/* temp struct used for smooth_fcurve */
1148 float *h1, *h2, *h3; /* bezt->vec[0,1,2][1] */
1149 float y1, y2, y3; /* averaged before/new/after y-values */
1150};
1151
1153{
1154 int totSel = 0;
1155
1156 if (fcu->bezt == nullptr) {
1157 return;
1158 }
1159
1160 /* first loop through - count how many verts are selected */
1161 BezTriple *bezt = fcu->bezt;
1162 for (int i = 0; i < fcu->totvert; i++, bezt++) {
1163 if (BEZT_ISSEL_ANY(bezt)) {
1164 totSel++;
1165 }
1166 }
1167
1168 /* if any points were selected, allocate tSmooth_Bezt points to work on */
1169 if (totSel >= 3) {
1170 tSmooth_Bezt *tarray, *tsb;
1171
1172 /* allocate memory in one go */
1173 tsb = tarray = MEM_new_array_zeroed<tSmooth_Bezt>(totSel, "tSmooth_Bezt Array");
1174
1175 /* populate tarray with data of selected points */
1176 bezt = fcu->bezt;
1177 for (int i = 0, x = 0; (i < fcu->totvert) && (x < totSel); i++, bezt++) {
1178 if (BEZT_ISSEL_ANY(bezt)) {
1179 /* tsb simply needs pointer to vec, and index */
1180 tsb->h1 = &bezt->vec[0][1];
1181 tsb->h2 = &bezt->vec[1][1];
1182 tsb->h3 = &bezt->vec[2][1];
1183
1184 /* advance to the next tsb to populate */
1185 if (x < totSel - 1) {
1186 tsb++;
1187 }
1188 else {
1189 break;
1190 }
1191 }
1192 }
1193
1194 /* calculate the new smoothed F-Curve's with weighted averages:
1195 * - this is done with two passes to avoid progressive corruption errors
1196 * - uses 5 points for each operation (which stores in the relevant handles)
1197 * - previous: w/a ratio = 3:5:2:1:1
1198 * - next: w/a ratio = 1:1:2:5:3
1199 */
1200
1201 /* round 1: calculate smoothing deltas and new values */
1202 tsb = tarray;
1203 for (int i = 0; i < totSel; i++, tsb++) {
1204 /* Don't touch end points (otherwise, curves slowly explode,
1205 * as we don't have enough data there). */
1206 if (ELEM(i, 0, (totSel - 1)) == 0) {
1207 const tSmooth_Bezt *tP1 = tsb - 1;
1208 const tSmooth_Bezt *tP2 = (i - 2 > 0) ? (tsb - 2) : (nullptr);
1209 const tSmooth_Bezt *tN1 = tsb + 1;
1210 const tSmooth_Bezt *tN2 = (i + 2 < totSel) ? (tsb + 2) : (nullptr);
1211
1212 const float p1 = *tP1->h2;
1213 const float p2 = (tP2) ? (*tP2->h2) : (*tP1->h2);
1214 const float c1 = *tsb->h2;
1215 const float n1 = *tN1->h2;
1216 const float n2 = (tN2) ? (*tN2->h2) : (*tN1->h2);
1217
1218 /* calculate previous and next, then new position by averaging these */
1219 tsb->y1 = (3 * p2 + 5 * p1 + 2 * c1 + n1 + n2) / 12;
1220 tsb->y3 = (p2 + p1 + 2 * c1 + 5 * n1 + 3 * n2) / 12;
1221
1222 tsb->y2 = (tsb->y1 + tsb->y3) / 2;
1223 }
1224 }
1225
1226 /* round 2: apply new values */
1227 tsb = tarray;
1228 for (int i = 0; i < totSel; i++, tsb++) {
1229 /* don't touch end points, as their values weren't touched above */
1230 if (ELEM(i, 0, (totSel - 1)) == 0) {
1231 /* y2 takes the average of the 2 points */
1232 *tsb->h2 = tsb->y2;
1233
1234 /* handles are weighted between their original values and the averaged values */
1235 *tsb->h1 = ((*tsb->h1) * 0.7f) + (tsb->y1 * 0.3f);
1236 *tsb->h3 = ((*tsb->h3) * 0.7f) + (tsb->y3 * 0.3f);
1237 }
1238 }
1239
1240 /* free memory required for tarray */
1241 MEM_delete(tarray);
1242 }
1243
1244 /* recalculate handles */
1246}
1247
1249
1250/* -------------------------------------------------------------------- */
1260
1261namespace ed::animation {
1262
1264
1266{
1267 /* No need to check the channelbags for having F-Curves, as they are only
1268 * added when an F-Curve needs to be stored. */
1269 return this->keyframe_data.channelbags().is_empty();
1270}
1271
1273{
1274 if (this->keyframe_data.channelbags().size() != 1) {
1275 return false;
1276 }
1277
1278 const animrig::Channelbag *channelbag = this->keyframe_data.channelbag(0);
1279 return channelbag->fcurves().size() == 1;
1280}
1281
1282bool KeyframeCopyBuffer::is_bone(const FCurve &fcurve) const
1283{
1284 return this->bone_fcurves.contains(&fcurve);
1285}
1286
1288{
1289 /* The number of slots can be taken from any of these properties, so just assert that they are
1290 * consistent with each other. */
1291 BLI_assert(this->keyframe_data.channelbags().size() == this->slot_identifiers.size());
1292
1293 /* Return the number of channelbags, as this is actually storing data; the `slot_identifiers`
1294 * field is more cache-like. Even though they should produce the same value, I (Sybren) feel more
1295 * comfortable using the channelbag count, as channelbags are defined as per-slot F-Curve
1296 * storage. */
1297 return this->keyframe_data.channelbags().size();
1298}
1299
1301{
1302 /* TODO: use a nicer data structure so this loop isn't necessary any more. Or use a vector, in
1303 * which case we always need to loop, but it'll be small and maybe the lower overhead of Vector
1304 * (vs Map) will be worth it anyway. */
1305 for (const auto [handle, identifier] : this->slot_identifiers.items()) {
1306 if (identifier == slot_identifier) {
1307 return this->keyframe_data.channelbag_for_slot(handle);
1308 }
1309 }
1310 return nullptr;
1311}
1312
1314{
1315 using namespace blender::animrig;
1316
1317 std::cout << "KeyframeCopyBuffer contents:" << std::endl;
1318 std::cout << " frame range: " << this->first_frame << "-" << this->last_frame << std::endl;
1319 std::cout << " scene frame: " << this->current_frame << std::endl;
1320
1321 if (is_empty()) {
1322 std::cout << " buffer is empty" << std::endl;
1323 }
1324
1325 if (is_single_fcurve()) {
1326 std::cout << " buffer has single F-Curve" << std::endl;
1327 }
1328
1329 const StripKeyframeData &keyframe_data = this->keyframe_data;
1330 std::cout << " channelbags: " << keyframe_data.channelbags().size() << std::endl;
1331 for (const Channelbag *channelbag : keyframe_data.channelbags()) {
1332
1333 const std::string &slot_identifier = this->slot_identifiers.lookup(channelbag->slot_handle);
1334 if (slot_identifier == KeyframeCopyBuffer::SLOTLESS_SLOT_IDENTIFIER) {
1335 std::cout << " - Channelbag for slotless F-Curves:" << std::endl;
1336 }
1337 else {
1338 std::cout << " - Channelbag for slot \"" << slot_identifier << "\":" << std::endl;
1339 }
1340 for (const FCurve *fcurve : channelbag->fcurves()) {
1341 std::cout << " " << fcurve->rna_path() << "[" << fcurve->array_index << "]";
1342 if (this->is_bone(*fcurve)) {
1343 std::cout << " (bone)";
1344 }
1345 std::cout << std::endl;
1346 }
1347 }
1348}
1349
1350} // namespace ed::animation
1351
1353{
1354 using namespace blender::ed::animation;
1356 keyframe_copy_buffer = MEM_new<KeyframeCopyBuffer>(__func__);
1357}
1358
1360{
1361 using namespace blender::ed::animation;
1363 MEM_delete(keyframe_copy_buffer);
1364 }
1365}
1366
1367/* ------------------- */
1368
1369static bool is_animating_bone(const bAnimListElem *ale)
1370{
1372
1373 if (!ale->id || ale->id->id_type() != ID_OB) {
1374 return false;
1375 }
1376
1377 Object *ob = reinterpret_cast<Object *>(ale->id);
1378 if (ob->type != OB_ARMATURE) {
1379 return false;
1380 }
1381
1382 FCurve *fcurve = static_cast<FCurve *>(ale->key_data);
1383 const StringRefNull rna_path = fcurve->rna_path();
1384 if (rna_path.is_empty()) {
1385 return false;
1386 }
1387
1388 char bone_name[sizeof(bPoseChannel::name)];
1389 if (!BLI_str_quoted_substr(rna_path.c_str(), "pose.bones[", bone_name, sizeof(bone_name))) {
1390 return false;
1391 }
1392
1393 bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, bone_name);
1394 return pchan != nullptr;
1395};
1396
1397namespace {
1398
1399using namespace blender::animrig;
1400using namespace blender::ed::animation;
1401
1415class SlotMapper {
1416 public:
1417 KeyframeCopyBuffer &buffer;
1418
1421
1432 static constexpr animrig::slot_handle_t SLOTLESS_SLOT_HANDLE = 0;
1433
1437 Channelbag &channelbag_for_ale(const bAnimListElem *ale)
1438 {
1439 /* Slots really only exist with F-Curves from Actions. */
1440 const Action *map_key_action;
1441 slot_handle_t map_key_handle;
1442 if (ale->fcurve_owner_id->id_type() == ID_AC) {
1443 map_key_action = &reinterpret_cast<bAction *>(ale->fcurve_owner_id)->wrap();
1444 map_key_handle = ale->slot_handle;
1445 }
1446 else {
1447 map_key_action = nullptr;
1448 map_key_handle = SLOTLESS_SLOT_HANDLE;
1449 }
1450
1451 const auto map_key = std::make_pair(map_key_action, map_key_handle);
1452
1453 if (const std::optional<slot_handle_t> opt_internal_slot_handle =
1454 this->orig_to_buffer_slots.lookup_try(map_key))
1455 {
1456 /* There already is a slot for this, and that means there is a channelbag too. */
1457 const slot_handle_t internal_slot_handle = *opt_internal_slot_handle;
1458 BLI_assert(this->buffer.slot_identifiers.contains(internal_slot_handle));
1459
1460 Channelbag *channelbag = this->buffer.keyframe_data.channelbag_for_slot(
1461 internal_slot_handle);
1462 BLI_assert_msg(channelbag, "If the slot exists, so should the channelbag");
1463
1464 return *channelbag;
1465 }
1466
1467 /* Create a new Channelbag for this F-Curve. */
1468 const slot_handle_t internal_slot_handle = ++this->buffer.last_used_slot_handle;
1469 Channelbag &channelbag = this->buffer.keyframe_data.channelbag_for_slot_add(
1470 internal_slot_handle);
1471 this->orig_to_buffer_slots.add_new(map_key, internal_slot_handle);
1472
1473 /* Determine the slot identifier. */
1474 StringRef slot_identifier;
1475 if (map_key_action) {
1476 const Slot *ale_slot = map_key_action->slot_for_handle(ale->slot_handle);
1477 BLI_assert_msg(ale_slot, "Slot for copied keyframes is expected to exist.");
1478 slot_identifier = ale_slot->identifier;
1479 }
1480 else {
1481 slot_identifier = KeyframeCopyBuffer::SLOTLESS_SLOT_IDENTIFIER;
1482 }
1483 this->buffer.slot_identifiers.add(internal_slot_handle, slot_identifier);
1484
1485 /* ale->id might be nullptr on unassigned slots. */
1486 this->buffer.slot_animated_ids.add_new(internal_slot_handle, ale->id);
1487
1488 return channelbag;
1489 }
1490};
1491
1492} // namespace
1493
1494bool copy_animedit_keys(bAnimContext *ac, ListBaseT<bAnimListElem> *anim_data)
1495{
1496 using namespace blender::ed::animation;
1497 using namespace blender::animrig;
1498
1500
1501 SlotMapper slot_mapper{*keyframe_copy_buffer};
1502
1503 for (const bAnimListElem &ale : *anim_data) {
1505 const FCurve *fcu = static_cast<const FCurve *>(ale.key_data);
1506
1507 /* Firstly, check if F-Curve has any selected keyframes. Skip if no selected
1508 * keyframes found (so no need to create unnecessary copy-buffer data). This
1509 * check should also eliminate any problems associated with using
1510 * sample-data. */
1512 nullptr,
1513 /* The const-cast is because I (Sybren) want to have `fcu` as `const` in as much of
1514 * this ListBaseT iterator as possible. The code is alternating between the
1515 * to-be-copied F-Curve and the copy, and I want the compiler to help distinguish
1516 * those. */
1517 const_cast<FCurve *>(fcu),
1518 nullptr,
1520 nullptr) == 0)
1521 {
1522 continue;
1523 }
1524
1525 Channelbag &channelbag = slot_mapper.channelbag_for_ale(&ale);
1526
1527 /* Create an F-Curve on this ChannelBag. */
1528 FCurve &fcurve_copy = *BKE_fcurve_create();
1529 fcurve_copy.rna_path_set(fcu->rna_path());
1530 fcurve_copy.array_index = fcu->array_index;
1531 channelbag.fcurve_append(fcurve_copy);
1532
1533 if (fcu->grp) {
1534 bActionGroup &group = channelbag.channel_group_ensure(fcu->grp->name);
1535 channelbag.fcurve_assign_to_channel_group(fcurve_copy, group);
1536 }
1537
1538 /* Detect if this is a bone. We do that here rather than during pasting
1539 * because ID pointers will get invalidated on undo / loading another file. */
1540 if (is_animating_bone(&ale)) {
1541 keyframe_copy_buffer->bone_fcurves.add(&fcurve_copy);
1542 }
1543
1544 /* Add selected keyframes to the buffer F-Curve. */
1545 int bezt_index = 0;
1546 BezTriple *bezt = fcu->bezt;
1547 for (; bezt_index < fcu->totvert; bezt_index++, bezt++) {
1548 /* Don't copy if only a handle is selected. */
1549 if (!BEZT_ISSEL_IDX(bezt, 1)) {
1550 continue;
1551 }
1552
1553 /* Use INSERTKEY_FAST as that avoids recalculating handles. They should
1554 * remain as-is in the buffer. */
1556
1557 /* Keep track of the extremities. */
1558 const float bezt_frame = bezt->vec[1][0];
1561 }
1562 }
1563
1565
1566#ifndef NDEBUG
1567 /* TODO: remove this call completely when slot-aware copy-pasting has been implemented. */
1569#endif
1570
1571 return !keyframe_copy_buffer->is_empty();
1572}
1573
1574namespace ed::animation {
1575
1576std::optional<std::string> flip_names(const StringRefNull rna_path)
1577{
1578 int ofs_start, ofs_end;
1579 if (!BLI_str_quoted_substr_range(rna_path.c_str(), "pose.bones[", &ofs_start, &ofs_end)) {
1580 return {};
1581 }
1582
1583 /* NOTE: there is no need to un-escape the string to flip it.
1584 * However the buffer does need to be twice the size. */
1585 char bname_new[MAX_VGROUP_NAME * 2];
1586
1587 /* Take a copy so it's 0-terminated. */
1588 const std::string bone_name = rna_path.substr(ofs_start, ofs_end - ofs_start);
1589
1590 BLI_string_flip_side_name(bname_new, bone_name.c_str(), false, sizeof(bname_new));
1591
1592 return rna_path.substr(0, ofs_start) + bname_new + rna_path.substr(ofs_end);
1593}
1594
1595using pastebuf_match_func = bool (*)(Main *bmain,
1596 const FCurve &fcurve_to_match,
1597 const FCurve &fcurve_in_copy_buffer,
1598 animrig::slot_handle_t slot_handle_in_copy_buffer,
1599 bool from_single,
1600 bool to_single,
1601 bool flip);
1602
1603namespace {
1604
1605using namespace blender::animrig;
1606
1607enum class SlotMatchMethod {
1609 NONE = 0,
1611 IDENTIFIER = 1,
1613 SELECTION = 2,
1615 SELECTION_AND_IDENTIFIER = 3,
1616};
1617
1618} // namespace
1619
1624static SlotMatchMethod get_slot_match_method(const bool from_single,
1625 const bool to_single,
1626 const KeyframePasteContext &paste_context)
1627{
1628 BLI_assert_msg(!(from_single && to_single),
1629 "The from-single-to-single case is expected to be implemented as a special case "
1630 "in `paste_animedit_keys()`");
1631 UNUSED_VARS_NDEBUG(from_single);
1632
1633 if (paste_context.num_fcurves_selected == 0) {
1634 /* No F-Curves selected to explicitly paste into. The names of the selected slots determine the
1635 * source Channelbag. */
1636
1637 if (paste_context.num_slots_selected == 0) {
1638 /* Since none of the slots were selected to paste into, just do a match by name and ignore
1639 * their selection state. */
1640 return SlotMatchMethod::IDENTIFIER;
1641 }
1642
1643 if (keyframe_copy_buffer->num_slots() == 1) {
1644 /* Copied from one slot, pasting into one or more selected slots. This should only look at
1645 * selection of the target slot, and ignore slot names. */
1646 return SlotMatchMethod::SELECTION;
1647 }
1648
1649 /* Copied from multiple slots, in which case slot names do matter, and the targets should be
1650 * limited by their slot selection (i.e. F-Curves from unselected slots should not be pasted
1651 * into). */
1652 return SlotMatchMethod::SELECTION_AND_IDENTIFIER;
1653 }
1654
1655 if (to_single) {
1656 /* Copying into a single F-Curve. Because the single-to-single case is handled somewhere else,
1657 * we know multiple F-Curves were copied. Slot names do not matter, matching is done purely on
1658 * RNA path + array index.
1659 *
1660 * TODO: slot names may matter here after all, when the copy buffer has multiple slots. In that
1661 * case the single F-Curve to paste into can still match multiple copied F-Curves. That's a
1662 * corner case to implement at some other time, though. */
1663 return SlotMatchMethod::NONE;
1664 }
1665
1666 /* Pasting into multiple F-Curves. Whether slot names matter depends on how many slots the
1667 * key were copied from:
1668 * - 0 slots: impossible, then there would not be any keys at all.
1669 * - 1 slot: slot names do not matter. This makes it possible to copy-paste between slots.
1670 * - 2+ slots: slot names matter, only paste within the same slot as the copied data.
1671 */
1672
1673 const int num_slots_copied = keyframe_copy_buffer->num_slots();
1674 BLI_assert_msg(num_slots_copied > 0,
1675 "If any keyframes were copied, they MUST have come from some slot.");
1676 if (num_slots_copied > 1) {
1677 /* Copied from multiple slots, so do name matching. */
1678 return SlotMatchMethod::IDENTIFIER;
1679 }
1680
1681 return SlotMatchMethod::NONE;
1682}
1683
1691 Main *bmain,
1692 const bAnimListElem &ale_to_paste_into,
1693 const bool from_single,
1694 const bool to_single,
1695 const KeyframePasteContext &paste_context)
1696{
1697 using namespace blender::animrig;
1698
1699 BLI_assert(ale_to_paste_into.datatype == ALE_FCURVE);
1700 const FCurve &fcurve_to_match = *static_cast<FCurve *>(ale_to_paste_into.data);
1701
1702 BLI_assert_msg(!(from_single && to_single),
1703 "The from-single-to-single case is expected to be implemented as a special case "
1704 "in `paste_animedit_keys()`");
1705
1706 /* Because `channelbags_to_paste_from` can reference `single_copy_buffer_channelbag`, the latter
1707 * has to live longer, hence it is declared first. */
1708 const Channelbag *single_copy_buffer_channelbag;
1709 Span<const Channelbag *> channelbags_to_paste_from;
1710
1711 /* Get the slot of this ALE, as some of the cases below need to query it. It might be slotless,
1712 * for example for NLA control curves. */
1713 const Slot *ale_slot = nullptr;
1714 const Action *ale_action = nullptr;
1715 if (ale_to_paste_into.fcurve_owner_id->id_type() == ID_AC) {
1716 ale_action = &reinterpret_cast<bAction *>(ale_to_paste_into.fcurve_owner_id)->wrap();
1717 ale_slot = ale_action->slot_for_handle(ale_to_paste_into.slot_handle);
1718 BLI_assert(ale_slot);
1719 }
1720
1721 /* NASTINESS: this code shouldn't have to care about which slots are currently visible in
1722 * the channel list. But since selection state is only relevant when they CAN actually be
1723 * selected, it does matter. This code assumes:
1724 * 1. because SELECTION or SELECTION_AND_IDENTIFIER was returned, slot selection is a
1725 * thing in this mode,
1726 * 2. because slot selection is a thing, and this F-Curve is potentially getting pasted
1727 * into, its slot is visible too,
1728 * 3. and because of that, the selection state of this slot is enough to check here. */
1729
1730 const SlotMatchMethod slot_match = get_slot_match_method(from_single, to_single, paste_context);
1731 switch (slot_match) {
1732 case SlotMatchMethod::SELECTION:
1733 if (!ale_slot->is_selected()) {
1734 return nullptr;
1735 }
1737
1738 case SlotMatchMethod::NONE:
1739 /* Just search through all channelbags in the copy buffer. */
1740 channelbags_to_paste_from = keyframe_copy_buffer->keyframe_data.channelbags();
1741 break;
1742
1743 case SlotMatchMethod::SELECTION_AND_IDENTIFIER:
1744 if (!ale_slot->is_selected()) {
1745 return nullptr;
1746 }
1748
1749 case SlotMatchMethod::IDENTIFIER: {
1750 /* See if we copied from a slot whose identifier matches this ALE. */
1751 const std::string target_slot_identifier = ale_slot ?
1752 ale_slot->identifier :
1754
1755 single_copy_buffer_channelbag = keyframe_copy_buffer->channelbag_for_slot(
1756 target_slot_identifier);
1757 if (!single_copy_buffer_channelbag) {
1758 /* No data copied from a slot with this name. */
1759 return nullptr;
1760 }
1761
1762 /* Only consider the F-Curves from this channelbag. Because of channelbags_to_paste_from
1763 * referencing single_copy_buffer_channelbag, the latter has to live longer, hence it was
1764 * declared first. */
1765 channelbags_to_paste_from = Span<const Channelbag *>(&single_copy_buffer_channelbag, 1);
1766 break;
1767 }
1768 }
1769
1770 for (const Channelbag *channelbag : channelbags_to_paste_from) {
1771 for (const FCurve *fcurve : channelbag->fcurves()) {
1772 if (strategy(bmain,
1773 fcurve_to_match,
1774 *fcurve,
1775 channelbag->slot_handle,
1776 from_single,
1777 to_single,
1778 paste_context.flip))
1779 {
1780 return fcurve;
1781 }
1782 }
1783 }
1784
1785 return nullptr;
1786}
1787
1789 const FCurve &fcurve_to_match,
1790 const FCurve &fcurve_in_copy_buffer,
1791 animrig::slot_handle_t /*slot_handle_in_copy_buffer*/,
1792 const bool from_single,
1793 const bool to_single,
1794 const bool flip)
1795{
1796 if (fcurve_to_match.rna_path().is_empty() || fcurve_in_copy_buffer.rna_path().is_empty()) {
1797 /* No paths to compare to, so only ok if pasting to a single F-Curve. */
1798 return to_single;
1799 }
1800
1801 /* The 'source' of the copy data is considered 'ok' if either we're copying a single F-Curve,
1802 * or the array index matches (so [location X,Y,Z] can be copied to a single 'scale' property,
1803 * and it'll pick up the right X/Y/Z component). */
1804 const bool is_source_ok = from_single ||
1805 fcurve_in_copy_buffer.array_index == fcurve_to_match.array_index;
1806 if (!is_source_ok) {
1807 return false;
1808 }
1809
1810 if (!to_single && flip && keyframe_copy_buffer->is_bone(fcurve_in_copy_buffer)) {
1811 const std::optional<std::string> with_flipped_name = ed::animation::flip_names(
1812 fcurve_in_copy_buffer.rna_path());
1813 return with_flipped_name && with_flipped_name == fcurve_to_match.rna_path();
1814 }
1815
1816 return to_single || fcurve_in_copy_buffer.rna_path() == fcurve_to_match.rna_path();
1817}
1818
1820 Main *bmain,
1821 const FCurve &fcurve_to_match,
1822 const FCurve &fcurve_in_copy_buffer,
1823 const animrig::slot_handle_t slot_handle_in_copy_buffer,
1824 const bool from_single,
1825 const bool to_single,
1826 const bool flip)
1827{
1828 if (fcurve_to_match.rna_path_parsed().size() != fcurve_in_copy_buffer.rna_path_parsed().size()) {
1829 return false;
1830 }
1831
1832 return pastebuf_match_path_property(bmain,
1833 fcurve_to_match,
1834 fcurve_in_copy_buffer,
1835 slot_handle_in_copy_buffer,
1836 from_single,
1837 to_single,
1838 flip);
1839}
1840
1842 const FCurve &fcurve_to_match,
1843 const FCurve &fcurve_in_copy_buffer,
1844 animrig::slot_handle_t /*slot_handle_in_copy_buffer*/,
1845 const bool from_single,
1846 const bool /*to_single*/,
1847 const bool /*flip*/)
1848{
1849 if (fcurve_in_copy_buffer.rna_path().is_empty() || fcurve_to_match.rna_path().is_empty()) {
1850 return false;
1851 }
1852
1853 /* The 'source' of the copy data is considered 'ok' if either we're copying a single F-Curve,
1854 * or the array index matches (so [location X,Y,Z] can be copied to a single 'scale' property,
1855 * and it'll pick up the right X/Y/Z component). */
1856 const bool is_source_ok = from_single ||
1857 fcurve_in_copy_buffer.array_index == fcurve_to_match.array_index;
1858 if (!is_source_ok) {
1859 return false;
1860 }
1861
1862 /* See if the property name matches. */
1863 const ParsedRNAPathRef rnapath_to_match = fcurve_to_match.rna_path_parsed();
1864 const ParsedRNAPathRef rnapath_in_copy_buffer = fcurve_in_copy_buffer.rna_path_parsed();
1865 if (rnapath_to_match.is_empty() || rnapath_in_copy_buffer.is_empty()) {
1866 /* Can happen if the path is malformed. */
1867 return false;
1868 }
1869
1870 const rna_path::Item last_item_to_match = rnapath_to_match.last();
1871 const rna_path::Item last_item_in_copy_buffer = rnapath_in_copy_buffer.last();
1872
1873 /* Both last items have to be of the same type, or there is no match. */
1874 if (last_item_to_match.index() != last_item_in_copy_buffer.index()) {
1875 return false;
1876 }
1877
1878 /* If this is a member (like '.rotation_euler') or lookup key (like `["customprop"]`) they have
1879 * to match. If they are LookupIndex, they also have to be preceded by the same member to match.
1880 */
1881 if (last_item_to_match != last_item_in_copy_buffer) {
1882 return false;
1883 }
1884 if (!std::holds_alternative<rna_path::LookupIndex>(last_item_to_match)) {
1885 /* For non-indexes this is enough. */
1886 return true;
1887 }
1888
1889 if (rnapath_to_match.size() < 2 || rnapath_in_copy_buffer.size() < 2) {
1890 /* RNA paths of just an array index are not valid, so don't see this as a match. */
1891 return false;
1892 }
1893
1894 const rna_path::Item preceding_item_to_match = rnapath_to_match.last(1);
1895 const rna_path::Item preceding_item_in_copy_buffer = rnapath_in_copy_buffer.last(1);
1896 return preceding_item_to_match == preceding_item_in_copy_buffer;
1897}
1898
1900 const FCurve &fcurve_to_match,
1901 const FCurve &fcurve_in_copy_buffer,
1902 animrig::slot_handle_t /* slot_handle_in_copy_buffer */,
1903 const bool from_single,
1904 const bool /*to_single*/,
1905 const bool /*flip*/)
1906{
1907 return from_single || fcurve_in_copy_buffer.array_index == fcurve_to_match.array_index;
1908}
1909
1910/* ................ */
1911
1912static void do_curve_mirror_flippping(const FCurve &fcurve, BezTriple &bezt)
1913{
1914 if (!keyframe_copy_buffer->is_bone(fcurve)) {
1915 return;
1916 }
1917
1918 /* TODO: pull the investigation of the RNA path out of this function, and out of the loop over
1919 * all keys of the F-Curve. It only has to be done once per F-Curve, and not for every single
1920 * key. */
1921 const StringRefNull rna_path = fcurve.rna_path();
1922 const size_t slength = rna_path.size();
1923 bool flip = false;
1924 if (BLI_strn_endswith(rna_path.c_str(), "location", slength) && fcurve.array_index == 0) {
1925 flip = true;
1926 }
1927 else if (BLI_strn_endswith(rna_path.c_str(), "rotation_quaternion", slength) &&
1928 ELEM(fcurve.array_index, 2, 3))
1929 {
1930 flip = true;
1931 }
1932 else if (BLI_strn_endswith(rna_path.c_str(), "rotation_euler", slength) &&
1933 ELEM(fcurve.array_index, 1, 2))
1934 {
1935 flip = true;
1936 }
1937 else if (BLI_strn_endswith(rna_path.c_str(), "rotation_axis_angle", slength) &&
1938 ELEM(fcurve.array_index, 2, 3))
1939 {
1940 flip = true;
1941 }
1942
1943 if (flip) {
1944 bezt.vec[0][1] = -bezt.vec[0][1];
1945 bezt.vec[1][1] = -bezt.vec[1][1];
1946 bezt.vec[2][1] = -bezt.vec[2][1];
1947 }
1948}
1949
1950/* helper for paste_animedit_keys() - performs the actual pasting */
1952 const FCurve &fcurve_in_copy_buffer,
1953 float offset[2],
1954 const eKeyMergeMode merge_mode,
1955 bool flip)
1956{
1957 BezTriple *bezt;
1958 int i;
1959
1960 /* First de-select existing FCurve's keyframes */
1961 for (i = 0, bezt = fcu->bezt; i < fcu->totvert; i++, bezt++) {
1962 BEZT_DESEL_ALL(bezt);
1963 }
1964
1965 /* mix mode with existing data */
1966 switch (merge_mode) {
1968 /* do-nothing */
1969 break;
1970
1972 /* remove all keys */
1974 break;
1975
1978 float f_min;
1979 float f_max;
1980
1981 if (merge_mode == KEYFRAME_PASTE_MERGE_OVER_RANGE) {
1982 f_min = fcurve_in_copy_buffer.bezt[0].vec[1][0] + offset[0];
1983 f_max = fcurve_in_copy_buffer.bezt[fcurve_in_copy_buffer.totvert - 1].vec[1][0] +
1984 offset[0];
1985 }
1986 else { /* Entire Range */
1987 f_min = keyframe_copy_buffer->first_frame + offset[0];
1988 f_max = keyframe_copy_buffer->last_frame + offset[0];
1989 }
1990
1991 /* remove keys in range */
1992 if (f_min < f_max) {
1993 /* select verts in range for removal */
1994 for (i = 0, bezt = fcu->bezt; i < fcu->totvert; i++, bezt++) {
1995 if ((f_min < bezt[0].vec[1][0]) && (bezt[0].vec[1][0] < f_max)) {
1996 bezt->f2 |= BEZT_FLAG_SELECT;
1997 }
1998 }
1999
2000 /* remove frames in the range */
2002 }
2003 break;
2004 }
2005 }
2006
2007 /* just start pasting, with the first keyframe on the current frame, and so on */
2008 for (i = 0, bezt = fcurve_in_copy_buffer.bezt; i < fcurve_in_copy_buffer.totvert; i++, bezt++) {
2009 /* Create a copy to modify, before inserting it into the F-Curve. The
2010 * applied offset also determines the frame number of the pasted BezTriple.
2011 * If the insertion is done before the offset is applied, it will replace
2012 * the original key and _then_ move it to the new position. */
2013 BezTriple bezt_copy = *bezt;
2014
2015 if (flip) {
2016 do_curve_mirror_flippping(fcurve_in_copy_buffer, bezt_copy);
2017 }
2018
2019 add_v2_v2(bezt_copy.vec[0], offset);
2020 add_v2_v2(bezt_copy.vec[1], offset);
2021 add_v2_v2(bezt_copy.vec[2], offset);
2022
2023 /* Ensure that all pasted data is selected. */
2024 BEZT_SEL_ALL(&bezt_copy);
2025
2026 /* Only now that it has the right values, do the pasting into the F-Curve. */
2028 }
2029
2030 /* recalculate F-Curve's handles? */
2032}
2033} // namespace ed::animation
2034
2037 "START",
2038 0,
2039 "Frame Start",
2040 "Paste keys starting at current frame"},
2041 {KEYFRAME_PASTE_OFFSET_CFRA_END, "END", 0, "Frame End", "Paste keys ending at current frame"},
2043 "RELATIVE",
2044 0,
2045 "Frame Relative",
2046 "Paste keys relative to the current frame when copying"},
2047 {KEYFRAME_PASTE_OFFSET_NONE, "NONE", 0, "No Offset", "Paste keys from original time"},
2048 {0, nullptr, 0, nullptr, nullptr},
2049};
2050
2053 "LEFT_KEY",
2054 0,
2055 "Left Key",
2056 "Paste keys with the first key matching the key left of the cursor"},
2058 "RIGHT_KEY",
2059 0,
2060 "Right Key",
2061 "Paste keys with the last key matching the key right of the cursor"},
2063 "CURRENT_FRAME",
2064 0,
2065 "Current Frame Value",
2066 "Paste keys relative to the value of the curve under the cursor"},
2068 "CURSOR_VALUE",
2069 0,
2070 "Cursor Value",
2071 "Paste keys relative to the Y-Position of the cursor"},
2073 "NONE",
2074 0,
2075 "No Offset",
2076 "Paste keys with the same value as they were copied"},
2077 {0, nullptr, 0, nullptr, nullptr},
2078};
2079
2081 {KEYFRAME_PASTE_MERGE_MIX, "MIX", 0, "Mix", "Overlay existing with new keys"},
2082 {KEYFRAME_PASTE_MERGE_OVER, "OVER_ALL", 0, "Overwrite All", "Replace all keys"},
2084 "OVER_RANGE",
2085 0,
2086 "Overwrite Range",
2087 "Overwrite keys in pasted range"},
2089 "OVER_RANGE_ALL",
2090 0,
2091 "Overwrite Entire Range",
2092 "Overwrite keys in pasted range, using the range of all copied keys"},
2093 {0, nullptr, 0, nullptr, nullptr},
2094};
2095
2096static float paste_get_y_offset(const bAnimContext *ac,
2097 const FCurve &fcurve_in_copy_buffer,
2098 const bAnimListElem *ale,
2099 const eKeyPasteValueOffset value_offset_mode)
2100{
2102 const FCurve *fcu = static_cast<const FCurve *>(ale->data);
2103 const float cfra = BKE_scene_frame_get(ac->scene);
2104
2105 switch (value_offset_mode) {
2107 const SpaceGraph *sipo = reinterpret_cast<SpaceGraph *>(ac->sl);
2108 const float offset = sipo->cursorVal - fcurve_in_copy_buffer.bezt[0].vec[1][1];
2109 return offset;
2110 }
2111
2113 const float cfra_y = evaluate_fcurve(fcu, cfra);
2114 const float offset = cfra_y - fcurve_in_copy_buffer.bezt[0].vec[1][1];
2115 return offset;
2116 }
2117
2119 bool replace;
2120 const int fcu_index = BKE_fcurve_bezt_binarysearch_index(
2121 fcu->bezt, cfra, fcu->totvert, &replace);
2122 const BezTriple left_key = fcu->bezt[max_ii(fcu_index - 1, 0)];
2123 const float offset = left_key.vec[1][1] - fcurve_in_copy_buffer.bezt[0].vec[1][1];
2124 return offset;
2125 }
2126
2128 bool replace;
2129 const int fcu_index = BKE_fcurve_bezt_binarysearch_index(
2130 fcu->bezt, cfra, fcu->totvert, &replace);
2131 const BezTriple right_key = fcu->bezt[min_ii(fcu_index, fcu->totvert - 1)];
2132 const float offset = right_key.vec[1][1] -
2133 fcurve_in_copy_buffer.bezt[fcurve_in_copy_buffer.totvert - 1].vec[1][1];
2134 return offset;
2135 }
2136
2138 break;
2139 }
2140
2141 return 0.0f;
2142}
2143
2145 ListBaseT<bAnimListElem> *anim_data,
2146 const KeyframePasteContext &paste_context)
2147{
2148 using namespace blender::ed::animation;
2149
2152 }
2153 if (anim_data->is_empty()) {
2155 }
2156
2157 const Scene *scene = (ac->scene);
2158 const bool from_single = keyframe_copy_buffer->is_single_fcurve();
2159 const bool to_single = anim_data->is_single();
2160 float offset[2] = {0, 0};
2161
2162 /* methods of offset */
2163 switch (paste_context.offset_mode) {
2165 offset[0] = float(scene->r.cfra - keyframe_copy_buffer->first_frame);
2166 break;
2168 offset[0] = float(scene->r.cfra - keyframe_copy_buffer->last_frame);
2169 break;
2171 offset[0] = float(scene->r.cfra - keyframe_copy_buffer->current_frame);
2172 break;
2174 offset[0] = 0.0f;
2175 break;
2176 }
2177
2178 if (from_single && to_single) {
2179 /* 1:1 match, no tricky checking, just paste. */
2180 bAnimListElem *ale = anim_data->first();
2181 FCurve *fcu = static_cast<FCurve *>(ale->data); /* destination F-Curve */
2182 const FCurve &fcurve_in_copy_buffer =
2184
2185 offset[1] = paste_get_y_offset(
2186 ac, fcurve_in_copy_buffer, ale, paste_context.value_offset_mode);
2187
2188 ANIM_nla_mapping_apply_if_needed_fcurve(ale, fcu, false, false);
2190 fcu, fcurve_in_copy_buffer, offset, paste_context.merge_mode, false);
2191 ANIM_nla_mapping_apply_if_needed_fcurve(ale, fcu, true, false);
2192
2194
2195 ANIM_animdata_update(ac, anim_data);
2196
2197 return KEYFRAME_PASTE_OK;
2198 }
2199
2200 /* Try to find "matching" channels to paste keyframes into with increasingly
2201 * loose matching heuristics. The process finishes when at least one F-Curve
2202 * has been pasted into. */
2207
2208 for (const pastebuf_match_func matcher : matchers) {
2209 bool found_match = false;
2210
2211 for (bAnimListElem &ale : *anim_data) {
2212 /* See if there is an F-Curve in the copy buffer that matches this ALE. */
2213 const FCurve *fcurve_in_copy_buffer = pastebuf_find_matching_copybuf_item(
2214 matcher, ac->bmain, ale, from_single, to_single, paste_context);
2215 if (!fcurve_in_copy_buffer) {
2216 continue;
2217 }
2218
2219 /* Copy the relevant data from the matching buffer curve. */
2220 offset[1] = paste_get_y_offset(
2221 ac, *fcurve_in_copy_buffer, &ale, paste_context.value_offset_mode);
2222
2223 /* Do the actual pasting. */
2224 FCurve *fcurve_to_paste_into = static_cast<FCurve *>(ale.data);
2225 ANIM_nla_mapping_apply_if_needed_fcurve(&ale, fcurve_to_paste_into, false, false);
2226 paste_animedit_keys_fcurve(fcurve_to_paste_into,
2227 *fcurve_in_copy_buffer,
2228 offset,
2229 paste_context.merge_mode,
2230 paste_context.flip);
2231 ANIM_nla_mapping_apply_if_needed_fcurve(&ale, fcurve_to_paste_into, true, false);
2232
2233 found_match = true;
2235 }
2236
2237 /* Don't continue if some fcurves were pasted. */
2238 if (found_match) {
2239 break;
2240 }
2241 }
2242
2243 ANIM_animdata_update(ac, anim_data);
2244
2245 return KEYFRAME_PASTE_OK;
2246}
2247
2249
2250} // namespace blender
Functions and classes to work with Actions.
Functions to work with AnimData.
Functions to modify FCurves.
Blender kernel action and pose functionality.
#define SELECT
Definition BKE_mask.hh:19
#define ATTR_FALLTHROUGH
#define M_PI
#define BEZT_ISSEL_IDX(bezt, i)
#define BEZT_SEL_ALL(bezt)
#define BEZT_ISSEL_ANY(bezt)
#define BEZT_DESEL_ALL(bezt)
Object is a sort of wrapper for general info.
#define MAX_VGROUP_NAME
#define ANIM_UPDATE_DEFAULT
Read Blender memory allocation and freeing.
#define UNUSED_VARS_NDEBUG(...)
#define BLI_assert(a)
#define ELEM(...)
#define IS_EQF(a, b)
#define BLI_assert_msg(a, msg)
#define IS_EQT(a, b, c)
constexpr Span()=default
std::optional< Value > lookup_try(const Key &key) const
Definition BLI_map.hh:531
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
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
bool contains(const Key &key) const
Definition BLI_map.hh:353
ItemIterator items() const &
Definition BLI_map.hh:902
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
constexpr bool is_empty() const
Definition BLI_span.hh:264
Slot * slot_for_handle(slot_handle_t handle)
const FCurve * fcurve(int64_t index) const
bool fcurve_assign_to_channel_group(FCurve &fcurve, bActionGroup &to_group)
Span< const FCurve * > fcurves() const
bActionGroup & channel_group_ensure(StringRefNull name)
const Channelbag * channelbag_for_slot(const Slot &slot) const
Channelbag & channelbag_for_slot_add(const Slot &slot)
Span< const Channelbag * > channelbags() const
const Channelbag * channelbag(int64_t index) const
#define tan
#define sin
#define round
#define pow
#define exp
#define ceil
float wrap(float a, float b, float c)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
ccl_device_inline dual3 fabs(const ccl_private dual3 &a)
Definition math_dual.h:241
decltype(blender::ActionSlot::handle) slot_handle_t
void animdata_fcurve_delete(AnimData *adt, FCurve *fcu)
Definition animdata.cc:251
int insert_bezt_fcurve(FCurve *fcu, const BezTriple *bezt, eInsertKeyFlags flag)
Lesser Key-framing API call.
std::optional< std::string > flip_names(const StringRefNull rna_path)
KeyframeCopyBuffer * keyframe_copy_buffer
static void paste_animedit_keys_fcurve(FCurve *fcu, const FCurve &fcurve_in_copy_buffer, float offset[2], const eKeyMergeMode merge_mode, bool flip)
static SlotMatchMethod get_slot_match_method(const bool from_single, const bool to_single, const KeyframePasteContext &paste_context)
bool pastebuf_match_index_only(Main *, const FCurve &fcurve_to_match, const FCurve &fcurve_in_copy_buffer, animrig::slot_handle_t, const bool from_single, const bool, const bool)
static const FCurve * pastebuf_find_matching_copybuf_item(const pastebuf_match_func strategy, Main *bmain, const bAnimListElem &ale_to_paste_into, const bool from_single, const bool to_single, const KeyframePasteContext &paste_context)
bool pastebuf_match_path_property_and_component_length(Main *bmain, const FCurve &fcurve_to_match, const FCurve &fcurve_in_copy_buffer, const animrig::slot_handle_t slot_handle_in_copy_buffer, const bool from_single, const bool to_single, const bool flip)
bool pastebuf_match_path_property(Main *, const FCurve &fcurve_to_match, const FCurve &fcurve_in_copy_buffer, animrig::slot_handle_t, const bool from_single, const bool, const bool)
static void do_curve_mirror_flippping(const FCurve &fcurve, BezTriple &bezt)
bool(*)(Main *bmain, const FCurve &fcurve_to_match, const FCurve &fcurve_in_copy_buffer, animrig::slot_handle_t slot_handle_in_copy_buffer, bool from_single, bool to_single, bool flip) pastebuf_match_func
bool pastebuf_match_path_full(Main *, const FCurve &fcurve_to_match, const FCurve &fcurve_in_copy_buffer, animrig::slot_handle_t, const bool from_single, const bool to_single, const bool flip)
BLI_INLINE Texture * wrap(MTLTexture *texture)
std::variant< Member, LookupIndex, LookupKey > Item
Definition RNA_path.hh:106
BMesh Iterators.
ButterworthCoefficients * ED_anim_allocate_butterworth_coefficients(const int filter_order)
MINLINE float min_ff(float a, float b)
void ease_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor, const float width)
int RNA_property_array_length(PointerRNA *ptr, PropertyRNA *prop)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
@ KEYFRAME_PASTE_NOTHING_TO_PASTE
@ KEYFRAME_PASTE_NOWHERE_TO_PASTE
void ANIM_fcurves_copybuf_reset()
KeyframeEditFunc ANIM_editkeyframes_ok(short mode)
void ANIM_fcurves_copybuf_free()
void scale_from_fcurve_segment_neighbor(FCurve *fcu, FCurveSegment *segment, const float factor, const FCurveSegmentAnchor anchor)
void BKE_fcurve_keyframe_move_value_with_handles(BezTriple *keyframe, float new_value)
bool BKE_fcurve_delete_keys_selected(FCurve &fcu)
static float s_curve(float x, float slope, float width, float height, float xshift, float yshift)
static float paste_get_y_offset(const bAnimContext *ac, const FCurve &fcurve_in_copy_buffer, const bAnimListElem *ale, const eKeyPasteValueOffset value_offset_mode)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
bool bool BLI_str_quoted_substr(const char *__restrict str, const char *__restrict prefix, char *result, size_t result_maxncpy)
void ED_anim_calculate_butterworth_coefficients(const float cutoff_frequency, const float sampling_frequency, ButterworthCoefficients *bw_coeff)
PointerRNA RNA_id_pointer_create(ID *id)
void smooth_fcurve(FCurve *fcu)
static bool is_animating_bone(const bAnimListElem *ale)
void clean_fcurve(bAnimListElem *ale, float thresh, bool cleardefault, const bool only_selected_keys)
void butterworth_smooth_fcurve_segment(FCurve *fcu, FCurveSegment *segment, float *samples, const int sample_count, const float factor, const int blend_in_out, const int sample_rate, ButterworthCoefficients *bw_coeff)
void blend_offset_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
int bool bool bool BLI_strn_endswith(const char *__restrict str, const char *__restrict end, size_t str_len) ATTR_NONNULL(1
float RNA_property_float_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index)
const EnumPropertyItem rna_enum_keyframe_paste_merge_items[]
MINLINE int max_ii(int a, int b)
Span< rna_path::Item > ParsedRNAPathRef
Definition RNA_path.hh:113
bool duplicate_fcurve_keys(FCurve *fcu)
@ KEYFRAME_PASTE_MERGE_OVER_RANGE_ALL
@ KEYFRAME_PASTE_MERGE_OVER_RANGE
@ KEYFRAME_PASTE_OFFSET_CFRA_START
@ KEYFRAME_PASTE_OFFSET_CFRA_RELATIVE
@ KEYFRAME_PASTE_OFFSET_CFRA_END
short ANIM_fcurve_keyframes_loop(KeyframeEditData *ked, FCurve *fcu, KeyframeEditFunc key_ok, KeyframeEditFunc key_cb, FcuEditFunc fcu_cb)
static float ease_sigmoid_function(const float x, const float width, const float shift)
void ANIM_nla_mapping_apply_if_needed_fcurve(bAnimListElem *ale, FCurve *fcu, const bool restore, const bool only_keys)
Definition anim_draw.cc:406
void ANIM_animdata_update(bAnimContext *ac, ListBaseT< bAnimListElem > *anim_data)
Definition anim_deps.cc:365
void time_offset_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float frame_offset)
void push_pull_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
static double butterworth_filter_value(double x, double *w0, double *w1, double *w2, ButterworthCoefficients *bw_coeff)
MINLINE void mul_v3_fl(float r[3], float f)
ListBaseT< FCurveSegment > find_fcurve_segments(FCurve *fcu)
MINLINE float pow2f(float x)
PropertyType RNA_property_type(PropertyRNA *prop)
@ INSERTKEY_OVERWRITE_FULL
bool copy_animedit_keys(bAnimContext *ac, ListBaseT< bAnimListElem > *anim_data)
void blend_to_neighbor_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
void * MEM_new_zeroed(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
static bool prepare_for_decimate(FCurve *fcu, int i)
MINLINE void add_v2_v2(float r[2], const float a[2])
@ PROP_BOOLEAN
Definition RNA_types.hh:210
void BKE_fcurve_handles_recalc(FCurve &fcu)
float BKE_scene_frame_get(const Scene *scene)
Definition scene.cc:2595
MINLINE int signum_i(float a)
void breakdown_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
static void decimate_fcurve_segment(FCurve *fcu, int bezt_segment_start_idx, int bezt_segment_len, float remove_ratio, float error_sq_max)
void scale_average_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
sqrt(x)+1/max(0
unsigned int BKE_curve_decimate_bezt_array(BezTriple *bezt_array, unsigned int bezt_array_len, unsigned int resolu, bool is_cyclic, eBezTriple_Flag flag_test, eBezTriple_Flag flag_set, float error_sq_max, unsigned int error_target_len)
static const BezTriple * fcurve_segment_end_get(FCurve *fcu, int index)
bool match_slope_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
@ KEYFRAME_PASTE_VALUE_OFFSET_NONE
@ KEYFRAME_PASTE_VALUE_OFFSET_LEFT_KEY
@ KEYFRAME_PASTE_VALUE_OFFSET_CURSOR
@ KEYFRAME_PASTE_VALUE_OFFSET_RIGHT_KEY
@ KEYFRAME_PASTE_VALUE_OFFSET_CFRA
static float butterworth_calculate_blend_value(float *samples, const float *filtered_values, const int start_index, const int end_index, const int sample_index, const int blend_in_out)
MINLINE void add_v3_v3(float r[3], const float a[3])
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
static bool find_fcurve_segment(FCurve *fcu, const int start_index, int *r_segment_start_idx, int *r_segment_len)
void blend_to_default_fcurve(PointerRNA *id_ptr, FCurve *fcu, const float factor)
void smooth_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float *original_values, float *samples, const int sample_count, const float factor, const int kernel_size, const double *kernel)
void shear_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor, tShearDirection direction)
float RNA_property_float_get_default(PointerRNA *ptr, PropertyRNA *prop)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
void ED_anim_free_butterworth_coefficients(ButterworthCoefficients *bw_coeff)
bool BLI_str_quoted_substr_range(const char *__restrict str, const char *__restrict prefix, int *__restrict r_start, int *__restrict r_end) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
float get_default_rna_value(const FCurve *fcu, PropertyRNA *prop, PointerRNA *ptr)
void ED_ANIM_get_1d_gauss_kernel(const float sigma, const int kernel_size, double *r_kernel)
const EnumPropertyItem rna_enum_keyframe_paste_offset_items[]
int RNA_property_int_get_default(PointerRNA *ptr, PropertyRNA *prop)
eKeyPasteError paste_animedit_keys(bAnimContext *ac, ListBaseT< bAnimListElem > *anim_data, const KeyframePasteContext &paste_context)
void BKE_fcurve_delete_keys_all(FCurve &fcu)
MINLINE float interpf(float target, float origin, float t)
int BKE_fcurve_bezt_binarysearch_index(const BezTriple array[], float frame, int arraylen, bool *r_replace)
bool BKE_fcurve_is_empty(const FCurve *fcu)
bool RNA_property_boolean_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index)
int RNA_property_int_get_default_index(PointerRNA *ptr, PropertyRNA *prop, int index)
MINLINE int min_ii(int a, int b)
MINLINE int clamp_i(int value, int min, int max)
bool RNA_path_resolve_property(const PointerRNA *ptr, const char *path, PointerRNA *r_ptr, PropertyRNA **r_prop)
Definition rna_path.cc:578
static const BezTriple * fcurve_segment_start_get(FCurve *fcu, int index)
const EnumPropertyItem rna_enum_keyframe_paste_offset_value_items[]
bool RNA_property_boolean_get_default(PointerRNA *ptr, PropertyRNA *prop)
bPoseChannel * BKE_pose_channel_find_name(const bPose *pose, const char *name)
bool decimate_fcurve(bAnimListElem *ale, float remove_ratio, float error_sq_max)
FCurve * BKE_fcurve_create()
MINLINE float floored_fmod(float f, float n)
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void blend_to_ease_fcurve_segment(FCurve *fcu, FCurveSegment *segment, const float factor)
float evaluate_fcurve(const FCurve *fcu, float evaltime)
MINLINE float clamp_f(float value, float min, float max)
size_t BLI_string_flip_side_name(char *name_dst, const char *name_src, bool strip_number, size_t name_dst_maxncpy) ATTR_NONNULL(1
#define floorf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
eBezTriple_Flag f2
eBezTriple_Handle h2
eBezTriple_Flag f3
eBezTriple_Flag f1
eBezTriple_Interpolation ipo
eBezTriple_Handle h1
bActionGroup * grp
unsigned int totvert
eKeyPasteValueOffset value_offset_mode
struct bPose * pose
struct RenderData r
eAnim_Update_Flags update
bool is_bone(const FCurve &fcurve) const
Map< blender::animrig::slot_handle_t, ID * > slot_animated_ids
blender::animrig::StripKeyframeData keyframe_data
Map< blender::animrig::slot_handle_t, std::string > slot_identifiers
blender::animrig::slot_handle_t last_used_slot_handle
blender::animrig::Channelbag * channelbag_for_slot(StringRef slot_identifier)