Merge branch 'master' into blender2.8
[blender.git] / source / blender / python / intern / bpy_rna_anim.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/intern/bpy_rna_anim.c
24  *  \ingroup pythonintern
25  *
26  * This file defines the animation related methods used in bpy_rna.c
27  */
28
29 #include <Python.h>
30 #include <float.h> /* FLT_MAX */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_utildefines.h"
35 #include "BLI_string.h"
36
37 #include "DNA_scene_types.h"
38 #include "DNA_anim_types.h"
39
40 #include "ED_keyframing.h"
41 #include "ED_keyframes_edit.h"
42
43 #include "BKE_report.h"
44 #include "BKE_context.h"
45 #include "BKE_animsys.h"
46 #include "BKE_fcurve.h"
47 #include "BKE_idcode.h"
48
49 #include "RNA_access.h"
50 #include "RNA_enum_types.h"
51
52 #include "WM_api.h"
53 #include "WM_types.h"
54
55 #include "bpy_rna.h"
56 #include "bpy_capi_utils.h"
57 #include "bpy_rna_anim.h"
58
59 #include "../generic/python_utildefines.h"
60
61 /* for keyframes and drivers */
62 static int pyrna_struct_anim_args_parse(
63         PointerRNA *ptr, const char *error_prefix, const char *path,
64         const char **path_full, int *index)
65 {
66         const bool is_idbase = RNA_struct_is_ID(ptr->type);
67         PropertyRNA *prop;
68         PointerRNA r_ptr;
69
70         if (ptr->data == NULL) {
71                 PyErr_Format(PyExc_TypeError,
72                              "%.200s this struct has no data, can't be animated",
73                              error_prefix);
74                 return -1;
75         }
76
77         /* full paths can only be given from ID base */
78         if (is_idbase) {
79                 int r_index = -1;
80                 if (RNA_path_resolve_property_full(ptr, path, &r_ptr, &prop, &r_index) == false) {
81                         prop = NULL;
82                 }
83                 else if (r_index != -1) {
84                         PyErr_Format(PyExc_ValueError,
85                                      "%.200s path includes index, must be a separate argument",
86                                      error_prefix, path);
87                         return -1;
88                 }
89                 else if (ptr->id.data != r_ptr.id.data) {
90                         PyErr_Format(PyExc_ValueError,
91                                      "%.200s path spans ID blocks",
92                                      error_prefix, path);
93                         return -1;
94                 }
95         }
96         else {
97                 prop = RNA_struct_find_property(ptr, path);
98                 r_ptr = *ptr;
99         }
100
101         if (prop == NULL) {
102                 PyErr_Format(PyExc_TypeError,
103                              "%.200s property \"%s\" not found",
104                              error_prefix, path);
105                 return -1;
106         }
107
108         if (!RNA_property_animateable(&r_ptr, prop)) {
109                 PyErr_Format(PyExc_TypeError,
110                              "%.200s property \"%s\" not animatable",
111                              error_prefix, path);
112                 return -1;
113         }
114
115         if (RNA_property_array_check(prop) == 0) {
116                 if ((*index) == -1) {
117                         *index = 0;
118                 }
119                 else {
120                         PyErr_Format(PyExc_TypeError,
121                                      "%.200s index %d was given while property \"%s\" is not an array",
122                                      error_prefix, *index, path);
123                         return -1;
124                 }
125         }
126         else {
127                 int array_len = RNA_property_array_length(&r_ptr, prop);
128                 if ((*index) < -1 || (*index) >= array_len) {
129                         PyErr_Format(PyExc_TypeError,
130                                      "%.200s index out of range \"%s\", given %d, array length is %d",
131                                      error_prefix, path, *index, array_len);
132                         return -1;
133                 }
134         }
135
136         if (is_idbase) {
137                 *path_full = BLI_strdup(path);
138         }
139         else {
140                 *path_full = RNA_path_from_ID_to_property(&r_ptr, prop);
141
142                 if (*path_full == NULL) {
143                         PyErr_Format(PyExc_TypeError,
144                                      "%.200s could not make path to \"%s\"",
145                                      error_prefix, path);
146                         return -1;
147                 }
148         }
149
150         return 0;
151 }
152
153 /* internal use for insert and delete */
154 static int pyrna_struct_keyframe_parse(
155         PointerRNA *ptr, PyObject *args, PyObject *kw, const char *parse_str, const char *error_prefix,
156         const char **path_full, int *index, float *cfra, const char **group_name, int *options)     /* return values */
157 {
158         static const char *kwlist[] = {"data_path", "index", "frame", "group", "options", NULL};
159         PyObject *pyoptions = NULL;
160         const char *path;
161
162         /* note, parse_str MUST start with 's|ifsO!' */
163         if (!PyArg_ParseTupleAndKeywords(args, kw, parse_str, (char **)kwlist, &path, index, cfra, group_name,
164                                          &PySet_Type, &pyoptions))
165         {
166                 return -1;
167         }
168
169         if (pyrna_struct_anim_args_parse(ptr, error_prefix, path, path_full, index) == -1)
170                 return -1;
171
172         if (*cfra == FLT_MAX)
173                 *cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
174
175         /* flag may be null (no option currently for remove keyframes e.g.). */
176         if (options) {
177                 if (pyoptions && (pyrna_set_to_enum_bitfield(rna_enum_keying_flag_items, pyoptions, options, error_prefix) == -1)) {
178                         return -1;
179                 }
180
181                 *options |= INSERTKEY_NO_USERPREF;
182         }
183
184         return 0; /* success */
185 }
186
187 char pyrna_struct_keyframe_insert_doc[] =
188 ".. method:: keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
189 "\n"
190 "   Insert a keyframe on the property given, adding fcurves and animation data when necessary.\n"
191 "\n"
192 "   :arg data_path: path to the property to key, analogous to the fcurve's data path.\n"
193 "   :type data_path: string\n"
194 "   :arg index: array index of the property to key.\n"
195 "      Defaults to -1 which will key all indices or a single channel if the property is not an array.\n"
196 "   :type index: int\n"
197 "   :arg frame: The frame on which the keyframe is inserted, defaulting to the current frame.\n"
198 "   :type frame: float\n"
199 "   :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
200 "   :type group: str\n"
201 "   :arg options: Optional flags:\n"
202 "\n"
203 "      - ``INSERTKEY_NEEDED`` Only insert keyframes where they're needed in the relevant F-Curves.\n"
204 "      - ``INSERTKEY_VISUAL`` Insert keyframes based on 'visual transforms'.\n"
205 "      - ``INSERTKEY_XYZ_TO_RGB`` Color for newly added transformation F-Curves (Location, Rotation, Scale)\n"
206 "         and also Color is based on the transform axis.\n"
207 "   :type flag: set\n"
208 "   :return: Success of keyframe insertion.\n"
209 "   :rtype: boolean\n"
210 ;
211 PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyObject *kw)
212 {
213         /* args, pyrna_struct_keyframe_parse handles these */
214         const char *path_full = NULL;
215         int index = -1;
216         float cfra = FLT_MAX;
217         const char *group_name = NULL;
218         char keytype = BEZT_KEYTYPE_KEYFRAME; /* XXX: Expose this as a one-off option... */
219         int options = 0;
220
221         PYRNA_STRUCT_CHECK_OBJ(self);
222
223         if (pyrna_struct_keyframe_parse(&self->ptr, args, kw,
224                                         "s|ifsO!:bpy_struct.keyframe_insert()", "bpy_struct.keyframe_insert()",
225                                         &path_full, &index, &cfra, &group_name, &options) == -1)
226         {
227                 return NULL;
228         }
229         else if (self->ptr.type == &RNA_NlaStrip) {
230                 /* Handle special properties for NLA Strips, whose F-Curves are stored on the
231                  * strips themselves. These are stored separately or else the properties will
232                  * not have any effect.
233                  */
234                 struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
235                 ReportList reports;
236                 short result = 0;
237
238                 PointerRNA ptr = self->ptr;
239                 PropertyRNA *prop = NULL;
240                 const char *prop_name;
241
242                 BKE_reports_init(&reports, RPT_STORE);
243
244                 /* Retrieve the property identifier from the full path, since we can't get it any other way */
245                 prop_name = strrchr(path_full, '.');
246                 if ((prop_name >= path_full) &&
247                     (prop_name + 1 < path_full + strlen(path_full)))
248                 {
249                         prop = RNA_struct_find_property(&ptr, prop_name + 1);
250                 }
251
252                 if (prop) {
253                         NlaStrip *strip = (NlaStrip *)ptr.data;
254                         FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
255
256                         result = insert_keyframe_direct(depsgraph, &reports, ptr, prop, fcu, cfra, keytype, options);
257                 }
258                 else {
259                         BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
260                 }
261                 MEM_freeN((void *)path_full);
262
263                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
264                         return NULL;
265
266                 return PyBool_FromLong(result);
267         }
268         else {
269                 struct Depsgraph *depsgraph = CTX_data_depsgraph(BPy_GetContext());
270                 ReportList reports;
271                 short result;
272
273                 BKE_reports_init(&reports, RPT_STORE);
274
275                 result = insert_keyframe(depsgraph, &reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, keytype, options);
276                 MEM_freeN((void *)path_full);
277
278                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
279                         return NULL;
280
281                 return PyBool_FromLong(result);
282         }
283 }
284
285 char pyrna_struct_keyframe_delete_doc[] =
286 ".. method:: keyframe_delete(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
287 "\n"
288 "   Remove a keyframe from this properties fcurve.\n"
289 "\n"
290 "   :arg data_path: path to the property to remove a key, analogous to the fcurve's data path.\n"
291 "   :type data_path: string\n"
292 "   :arg index: array index of the property to remove a key. Defaults to -1 removing all indices or a single channel if the property is not an array.\n"
293 "   :type index: int\n"
294 "   :arg frame: The frame on which the keyframe is deleted, defaulting to the current frame.\n"
295 "   :type frame: float\n"
296 "   :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
297 "   :type group: str\n"
298 "   :return: Success of keyframe deleation.\n"
299 "   :rtype: boolean\n"
300 ;
301 PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyObject *kw)
302 {
303         /* args, pyrna_struct_keyframe_parse handles these */
304         const char *path_full = NULL;
305         int index = -1;
306         float cfra = FLT_MAX;
307         const char *group_name = NULL;
308
309         PYRNA_STRUCT_CHECK_OBJ(self);
310
311         if (pyrna_struct_keyframe_parse(&self->ptr, args, kw,
312                                         "s|ifsO!:bpy_struct.keyframe_delete()",
313                                         "bpy_struct.keyframe_insert()",
314                                         &path_full, &index, &cfra, &group_name, NULL) == -1)
315         {
316                 return NULL;
317         }
318         else if (self->ptr.type == &RNA_NlaStrip) {
319                 /* Handle special properties for NLA Strips, whose F-Curves are stored on the
320                  * strips themselves. These are stored separately or else the properties will
321                  * not have any effect.
322                  */
323                 ReportList reports;
324                 short result = 0;
325
326                 PointerRNA ptr = self->ptr;
327                 PropertyRNA *prop = NULL;
328                 const char *prop_name;
329
330                 BKE_reports_init(&reports, RPT_STORE);
331
332                 /* Retrieve the property identifier from the full path, since we can't get it any other way */
333                 prop_name = strrchr(path_full, '.');
334                 if ((prop_name >= path_full) &&
335                     (prop_name + 1 < path_full + strlen(path_full)))
336                 {
337                         prop = RNA_struct_find_property(&ptr, prop_name + 1);
338                 }
339
340                 if (prop) {
341                         ID *id = ptr.id.data;
342                         NlaStrip *strip = (NlaStrip *)ptr.data;
343                         FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
344
345                         BLI_assert(fcu != NULL); /* NOTE: This should be true, or else we wouldn't be able to get here */
346
347                         if (BKE_fcurve_is_protected(fcu)) {
348                                 BKE_reportf(&reports, RPT_WARNING,
349                                             "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'",
350                                             strip->name, BKE_idcode_to_name(GS(id->name)), id->name + 2);
351                         }
352                         else {
353                                 /* remove the keyframe directly
354                                  * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve,
355                                  *       and delete_keyframe() expects the FCurve to be part of an action
356                                  */
357                                 bool found = false;
358                                 int i;
359
360                                 /* try to find index of beztriple to get rid of */
361                                 i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
362                                 if (found) {
363                                         /* delete the key at the index (will sanity check + do recalc afterwards) */
364                                         delete_fcurve_key(fcu, i, 1);
365                                         result = true;
366                                 }
367                         }
368                 }
369                 else {
370                         BKE_reportf(&reports, RPT_ERROR, "Could not resolve path (%s)", path_full);
371                 }
372                 MEM_freeN((void *)path_full);
373
374                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
375                         return NULL;
376
377                 return PyBool_FromLong(result);
378         }
379         else {
380                 short result;
381                 ReportList reports;
382
383                 BKE_reports_init(&reports, RPT_STORE);
384
385                 result = delete_keyframe(&reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0);
386                 MEM_freeN((void *)path_full);
387
388                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
389                         return NULL;
390
391                 return PyBool_FromLong(result);
392         }
393
394 }
395
396 char pyrna_struct_driver_add_doc[] =
397 ".. method:: driver_add(path, index=-1)\n"
398 "\n"
399 "   Adds driver(s) to the given property\n"
400 "\n"
401 "   :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
402 "   :type path: string\n"
403 "   :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
404 "   :type index: int\n"
405 "   :return: The driver(s) added.\n"
406 "   :rtype: :class:`bpy.types.FCurve` or list if index is -1 with an array property.\n"
407 ;
408 PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
409 {
410         const char *path, *path_full;
411         int index = -1;
412
413         PYRNA_STRUCT_CHECK_OBJ(self);
414
415         if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
416                 return NULL;
417
418         if (pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_add():", path, &path_full, &index) == -1) {
419                 return NULL;
420         }
421         else {
422                 PyObject *ret = NULL;
423                 ReportList reports;
424                 int result;
425
426                 BKE_reports_init(&reports, RPT_STORE);
427
428                 result = ANIM_add_driver(&reports, (ID *)self->ptr.id.data, path_full, index,
429                                          CREATEDRIVER_WITH_FMODIFIER, DRIVER_TYPE_PYTHON);
430
431                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
432                         return NULL;
433
434                 if (result) {
435                         ID *id = self->ptr.id.data;
436                         AnimData *adt = BKE_animdata_from_id(id);
437                         FCurve *fcu;
438
439                         PointerRNA tptr;
440
441                         if (index == -1) { /* all, use a list */
442                                 int i = 0;
443                                 ret = PyList_New(0);
444                                 while ((fcu = list_find_fcurve(&adt->drivers, path_full, i++))) {
445                                         RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
446                                         PyList_APPEND(ret, pyrna_struct_CreatePyObject(&tptr));
447                                 }
448                         }
449                         else {
450                                 fcu = list_find_fcurve(&adt->drivers, path_full, index);
451                                 RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
452                                 ret = pyrna_struct_CreatePyObject(&tptr);
453                         }
454
455                         WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
456                 }
457                 else {
458                         /* XXX, should be handled by reports, */
459                         PyErr_SetString(PyExc_TypeError, "bpy_struct.driver_add(): failed because of an internal error");
460                         return NULL;
461                 }
462
463                 MEM_freeN((void *)path_full);
464
465                 return ret;
466         }
467 }
468
469
470 char pyrna_struct_driver_remove_doc[] =
471 ".. method:: driver_remove(path, index=-1)\n"
472 "\n"
473 "   Remove driver(s) from the given property\n"
474 "\n"
475 "   :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
476 "   :type path: string\n"
477 "   :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
478 "   :type index: int\n"
479 "   :return: Success of driver removal.\n"
480 "   :rtype: boolean\n"
481 ;
482 PyObject *pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args)
483 {
484         const char *path, *path_full;
485         int index = -1;
486
487         PYRNA_STRUCT_CHECK_OBJ(self);
488
489         if (!PyArg_ParseTuple(args, "s|i:driver_remove", &path, &index))
490                 return NULL;
491
492         if (pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_remove():", path, &path_full, &index) == -1) {
493                 return NULL;
494         }
495         else {
496                 short result;
497                 ReportList reports;
498
499                 BKE_reports_init(&reports, RPT_STORE);
500
501                 result = ANIM_remove_driver(&reports, (ID *)self->ptr.id.data, path_full, index, 0);
502
503                 MEM_freeN((void *)path_full);
504
505                 if (BPy_reports_to_error(&reports, PyExc_RuntimeError, true) == -1)
506                         return NULL;
507
508                 WM_event_add_notifier(BPy_GetContext(), NC_ANIMATION | ND_FCURVES_ORDER, NULL);
509
510                 return PyBool_FromLong(result);
511         }
512 }