9cd6fe3da91edd05e14e1a96fd24fb2b629d57c9
[blender.git] / source / blender / python / intern / bpy_driver.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): Willian P. Germano, Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/intern/bpy_driver.c
24  *  \ingroup pythonintern
25  *
26  * This file defines the 'BPY_driver_exec' to execute python driver expressions,
27  * called by the animation system, there are also some utility functions
28  * to deal with the namespace used for driver execution.
29  */
30
31 /* ****************************************** */
32 /* Drivers - PyExpression Evaluation */
33
34 #include <Python.h>
35
36 #include "DNA_anim_types.h"
37
38 #include "BLI_listbase.h"
39 #include "BLI_math_base.h"
40 #include "BLI_string.h"
41
42 #include "BKE_fcurve.h"
43 #include "BKE_global.h"
44
45 #include "bpy_rna_driver.h"  /* for pyrna_driver_get_variable_value */
46
47 #include "bpy_driver.h"
48
49 extern void BPY_update_rna_module(void);
50
51 #define USE_RNA_AS_PYOBJECT
52
53 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
54 PyObject *bpy_pydriver_Dict = NULL;
55
56 /* For faster execution we keep a special dictionary for pydrivers, with
57  * the needed modules and aliases.
58  */
59 int bpy_pydriver_create_dict(void)
60 {
61         PyObject *d, *mod;
62
63         /* validate namespace for driver evaluation */
64         if (bpy_pydriver_Dict) return -1;
65
66         d = PyDict_New();
67         if (d == NULL)
68                 return -1;
69         else
70                 bpy_pydriver_Dict = d;
71
72         /* import some modules: builtins, bpy, math, (Blender.noise)*/
73         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
74
75         mod = PyImport_ImportModule("math");
76         if (mod) {
77                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - don't overwrite existing values */
78                 Py_DECREF(mod);
79         }
80
81         /* add bpy to global namespace */
82         mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
83         if (mod) {
84                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
85                 Py_DECREF(mod);
86         }
87
88         /* add noise to global namespace */
89         mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
90         if (mod) {
91                 PyObject *modsub = PyDict_GetItemString(PyModule_GetDict(mod), "noise");
92                 PyDict_SetItemString(bpy_pydriver_Dict, "noise", modsub);
93                 Py_DECREF(mod);
94         }
95
96         return 0;
97 }
98
99 /* note, this function should do nothing most runs, only when changing frame */
100 static PyObject *bpy_pydriver_InternStr__frame = NULL;
101 /* not thread safe but neither is python */
102 static float bpy_pydriver_evaltime_prev = FLT_MAX;
103
104 static void bpy_pydriver_update_dict(const float evaltime)
105 {
106         if (bpy_pydriver_evaltime_prev != evaltime) {
107
108                 /* currently only update the frame */
109                 if (bpy_pydriver_InternStr__frame == NULL) {
110                         bpy_pydriver_InternStr__frame = PyUnicode_FromString("frame");
111                 }
112
113                 PyDict_SetItem(bpy_pydriver_Dict,
114                                bpy_pydriver_InternStr__frame,
115                                PyFloat_FromDouble(evaltime));
116
117                 bpy_pydriver_evaltime_prev = evaltime;
118         }
119 }
120
121 /* Update function, it gets rid of pydrivers global dictionary, forcing
122  * BPY_driver_exec to recreate it. This function is used to force
123  * reloading the Blender text module "pydrivers.py", if available, so
124  * updates in it reach pydriver evaluation.
125  */
126 void BPY_driver_reset(void)
127 {
128         PyGILState_STATE gilstate;
129         bool use_gil = true; /* !PyC_IsInterpreterActive(); */
130
131         if (use_gil)
132                 gilstate = PyGILState_Ensure();
133
134         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
135                 PyDict_Clear(bpy_pydriver_Dict);
136                 Py_DECREF(bpy_pydriver_Dict);
137                 bpy_pydriver_Dict = NULL;
138         }
139
140         if (bpy_pydriver_InternStr__frame) {
141                 Py_DECREF(bpy_pydriver_InternStr__frame);
142                 bpy_pydriver_InternStr__frame = NULL;
143                 bpy_pydriver_evaltime_prev = FLT_MAX;
144         }
145
146         if (use_gil)
147                 PyGILState_Release(gilstate);
148
149         return;
150 }
151
152 /* error return function for BPY_eval_pydriver */
153 static void pydriver_error(ChannelDriver *driver)
154 {
155         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
156         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
157
158         // BPy_errors_to_report(NULL); // TODO - reports
159         PyErr_Print();
160         PyErr_Clear();
161 }
162
163 /* This evals py driver expressions, 'expr' is a Python expression that
164  * should evaluate to a float number, which is returned.
165  *
166  * (old)note: PyGILState_Ensure() isn't always called because python can call
167  * the bake operator which intern starts a thread which calls scene update
168  * which does a driver update. to avoid a deadlock check PyC_IsInterpreterActive()
169  * if PyGILState_Ensure() is needed - see [#27683]
170  *
171  * (new)note: checking if python is running is not threadsafe [#28114]
172  * now release the GIL on python operator execution instead, using
173  * PyEval_SaveThread() / PyEval_RestoreThread() so we don't lock up blender.
174  */
175 float BPY_driver_exec(ChannelDriver *driver, const float evaltime)
176 {
177         PyObject *driver_vars = NULL;
178         PyObject *retval = NULL;
179         PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
180         PyObject *expr_code;
181         PyGILState_STATE gilstate;
182         bool use_gil;
183
184         DriverVar *dvar;
185         double result = 0.0; /* default return */
186         const char *expr;
187         short targets_ok = 1;
188         int i;
189
190         /* get the py expression to be evaluated */
191         expr = driver->expression;
192         if (expr[0] == '\0')
193                 return 0.0f;
194
195         if (!(G.f & G_SCRIPT_AUTOEXEC)) {
196                 if (!(G.f & G_SCRIPT_AUTOEXEC_FAIL_QUIET)) {
197                         G.f |= G_SCRIPT_AUTOEXEC_FAIL;
198                         BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Driver '%s'", expr);
199
200                         printf("skipping driver '%s', automatic scripts are disabled\n", expr);
201                 }
202                 return 0.0f;
203         }
204
205         use_gil = true;  /* !PyC_IsInterpreterActive(); */
206
207         if (use_gil)
208                 gilstate = PyGILState_Ensure();
209
210         /* needed since drivers are updated directly after undo where 'main' is
211          * re-allocated [#28807] */
212         BPY_update_rna_module();
213
214         /* init global dictionary for py-driver evaluation settings */
215         if (!bpy_pydriver_Dict) {
216                 if (bpy_pydriver_create_dict() != 0) {
217                         fprintf(stderr, "PyDriver error: couldn't create Python dictionary\n");
218                         if (use_gil)
219                                 PyGILState_Release(gilstate);
220                         return 0.0f;
221                 }
222         }
223
224         /* update global namespace */
225         bpy_pydriver_update_dict(evaltime);
226
227
228         if (driver->expr_comp == NULL)
229                 driver->flag |= DRIVER_FLAG_RECOMPILE;
230
231         /* compile the expression first if it hasn't been compiled or needs to be rebuilt */
232         if (driver->flag & DRIVER_FLAG_RECOMPILE) {
233                 Py_XDECREF(driver->expr_comp);
234                 driver->expr_comp = PyTuple_New(2);
235
236                 expr_code = Py_CompileString(expr, "<bpy driver>", Py_eval_input);
237                 PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, expr_code);
238
239                 driver->flag &= ~DRIVER_FLAG_RECOMPILE;
240                 driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
241         }
242         else {
243                 expr_code = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 0);
244         }
245
246         if (driver->flag & DRIVER_FLAG_RENAMEVAR) {
247                 /* may not be set */
248                 expr_vars = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
249                 Py_XDECREF(expr_vars);
250
251                 expr_vars = PyTuple_New(BLI_listbase_count(&driver->variables));
252                 PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 1, expr_vars);
253
254                 for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) {
255                         PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name));
256                 }
257                 
258                 driver->flag &= ~DRIVER_FLAG_RENAMEVAR;
259         }
260         else {
261                 expr_vars = PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
262         }
263
264         /* add target values to a dict that will be used as '__locals__' dict */
265         driver_vars = PyDict_New();
266         for (dvar = driver->variables.first, i = 0; dvar; dvar = dvar->next) {
267                 PyObject *driver_arg = NULL;
268
269         /* support for any RNA data */
270 #ifdef USE_RNA_AS_PYOBJECT
271                 if (dvar->type == DVAR_TYPE_SINGLE_PROP) {
272                         driver_arg = pyrna_driver_get_variable_value(driver, &dvar->targets[0]);
273
274                         if (driver_arg == NULL) {
275                                 driver_arg = PyFloat_FromDouble(0.0);
276                                 dvar->curval = 0.0f;
277                         }
278                         else {
279                                 /* no need to worry about overflow here, values from RNA are within limits. */
280                                 if (PyFloat_CheckExact(driver_arg)) {
281                                         dvar->curval = (float)PyFloat_AsDouble(driver_arg);
282                                 }
283                                 else if (PyLong_CheckExact(driver_arg)) {
284                                         dvar->curval = (float)PyLong_AsLong(driver_arg);
285                                 }
286                                 else if (PyBool_Check(driver_arg)) {
287                                         dvar->curval = (driver_arg == Py_True);
288                                 }
289                                 else {
290                                         dvar->curval = 0.0f;
291                                 }
292                         }
293                 }
294                 else
295 #endif
296                 {
297                         /* try to get variable value */
298                         float tval = driver_get_variable_value(driver, dvar);
299                         driver_arg = PyFloat_FromDouble((double)tval);
300                 }
301
302                 /* try to add to dictionary */
303                 /* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
304                 if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) < 0) {
305                         /* this target failed - bad name */
306                         if (targets_ok) {
307                                 /* first one - print some extra info for easier identification */
308                                 fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
309                                 targets_ok = 0;
310                         }
311                         
312                         fprintf(stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
313                         // BPy_errors_to_report(NULL); // TODO - reports
314                         PyErr_Print();
315                         PyErr_Clear();
316                 }
317         }
318
319
320 #if 0  /* slow, with this can avoid all Py_CompileString above. */
321         /* execute expression to get a value */
322         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
323 #else
324         /* evaluate the compiled expression */
325         if (expr_code)
326                 retval = PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
327 #endif
328
329         /* decref the driver vars first...  */
330         Py_DECREF(driver_vars);
331
332         /* process the result */
333         if (retval == NULL) {
334                 pydriver_error(driver);
335         }
336         else if ((result = PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
337                 pydriver_error(driver);
338                 Py_DECREF(retval);
339                 result = 0.0;
340         }
341         else {
342                 /* all fine, make sure the "invalid expression" flag is cleared */
343                 driver->flag &= ~DRIVER_FLAG_INVALID;
344                 Py_DECREF(retval);
345         }
346
347         if (use_gil)
348                 PyGILState_Release(gilstate);
349
350         if (finite(result)) {
351                 return (float)result;
352         }
353         else {
354                 fprintf(stderr, "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n", dvar->name, result);
355                 return 0.0f;
356         }
357 }