0fe1d2d26ba35559b4b1624a13ebf5e267b80fd2
[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
27 /* ****************************************** */
28 /* Drivers - PyExpression Evaluation */
29
30 #include <Python.h>
31
32 #include "DNA_anim_types.h"
33
34 #include "BLI_listbase.h"
35 #include "BLI_math_base.h"
36
37 #include "BKE_fcurve.h"
38 #include "BKE_global.h"
39
40 #include "bpy_driver.h"
41
42 extern void BPY_update_rna_module(void);
43
44
45 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
46 PyObject *bpy_pydriver_Dict= NULL;
47
48 /* For faster execution we keep a special dictionary for pydrivers, with
49  * the needed modules and aliases.
50  */
51 int bpy_pydriver_create_dict(void)
52 {
53         PyObject *d, *mod;
54
55         /* validate namespace for driver evaluation */
56         if (bpy_pydriver_Dict) return -1;
57
58         d= PyDict_New();
59         if (d == NULL)
60                 return -1;
61         else
62                 bpy_pydriver_Dict= d;
63
64         /* import some modules: builtins, bpy, math, (Blender.noise)*/
65         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
66
67         mod= PyImport_ImportModule("math");
68         if (mod) {
69                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
70                 Py_DECREF(mod);
71         }
72
73         /* add bpy to global namespace */
74         mod= PyImport_ImportModuleLevel((char *)"bpy", NULL, NULL, NULL, 0);
75         if (mod) {
76                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
77                 Py_DECREF(mod);
78         }
79
80         /* add noise to global namespace */
81         mod= PyImport_ImportModuleLevel((char *)"noise", NULL, NULL, NULL, 0);
82         if (mod) {
83                 PyDict_SetItemString(bpy_pydriver_Dict, "noise", mod);
84                 Py_DECREF(mod);
85         }
86
87         return 0;
88 }
89
90 /* Update function, it gets rid of pydrivers global dictionary, forcing
91  * BPY_driver_exec to recreate it. This function is used to force
92  * reloading the Blender text module "pydrivers.py", if available, so
93  * updates in it reach pydriver evaluation.
94  */
95 void BPY_driver_reset(void)
96 {
97         PyGILState_STATE gilstate;
98         int use_gil= 1; /* !PYC_INTERPRETER_ACTIVE; */
99
100         if (use_gil)
101                 gilstate= PyGILState_Ensure();
102
103         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
104                 PyDict_Clear(bpy_pydriver_Dict);
105                 Py_DECREF(bpy_pydriver_Dict);
106                 bpy_pydriver_Dict= NULL;
107         }
108
109         if (use_gil)
110                 PyGILState_Release(gilstate);
111
112         return;
113 }
114
115 /* error return function for BPY_eval_pydriver */
116 static void pydriver_error(ChannelDriver *driver)
117 {
118         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
119         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
120
121         // BPy_errors_to_report(NULL); // TODO - reports
122         PyErr_Print();
123         PyErr_Clear();
124 }
125
126 /* This evals py driver expressions, 'expr' is a Python expression that
127  * should evaluate to a float number, which is returned.
128  *
129  * (old)note: PyGILState_Ensure() isnt always called because python can call
130  * the bake operator which intern starts a thread which calls scene update
131  * which does a driver update. to avoid a deadlock check PYC_INTERPRETER_ACTIVE
132  * if PyGILState_Ensure() is needed - see [#27683]
133  *
134  * (new)note: checking if python is running is not threadsafe [#28114]
135  * now release the GIL on python operator execution instead, using
136  * PyEval_SaveThread() / PyEval_RestoreThread() so we dont lock up blender.
137  */
138 float BPY_driver_exec(ChannelDriver *driver)
139 {
140         PyObject *driver_vars=NULL;
141         PyObject *retval= NULL;
142         PyObject *expr_vars; /* speed up by pre-hashing string & avoids re-converting unicode strings for every execution */
143         PyObject *expr_code;
144         PyGILState_STATE gilstate;
145         int use_gil;
146
147         DriverVar *dvar;
148         double result= 0.0; /* default return */
149         char *expr= NULL;
150         short targets_ok= 1;
151         int i;
152
153         /* get the py expression to be evaluated */
154         expr= driver->expression;
155         if ((expr == NULL) || (expr[0]=='\0'))
156                 return 0.0f;
157
158         if (!(G.f & G_SCRIPT_AUTOEXEC)) {
159                 printf("skipping driver '%s', automatic scripts are disabled\n", driver->expression);
160                 return 0.0f;
161         }
162
163         use_gil= 1; /* !PYC_INTERPRETER_ACTIVE; */
164
165         if (use_gil)
166                 gilstate= PyGILState_Ensure();
167
168         /* needed since drivers are updated directly after undo where 'main' is
169          * re-allocated [#28807] */
170         BPY_update_rna_module();
171
172         /* init global dictionary for py-driver evaluation settings */
173         if (!bpy_pydriver_Dict) {
174                 if (bpy_pydriver_create_dict() != 0) {
175                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
176                         if (use_gil)
177                                 PyGILState_Release(gilstate);
178                         return 0.0f;
179                 }
180         }
181
182         if (driver->expr_comp==NULL)
183                 driver->flag |= DRIVER_FLAG_RECOMPILE;
184
185         /* compile the expression first if it hasn't been compiled or needs to be rebuilt */
186         if (driver->flag & DRIVER_FLAG_RECOMPILE) {
187                 Py_XDECREF(driver->expr_comp);
188                 driver->expr_comp= PyTuple_New(2);
189
190                 expr_code= Py_CompileString(expr, "<bpy driver>", Py_eval_input);
191                 PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 0, expr_code);
192
193                 driver->flag &= ~DRIVER_FLAG_RECOMPILE;
194                 driver->flag |= DRIVER_FLAG_RENAMEVAR; /* maybe this can be removed but for now best keep until were sure */
195         }
196         else {
197                 expr_code= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 0);
198         }
199
200         if (driver->flag & DRIVER_FLAG_RENAMEVAR) {
201                 /* may not be set */
202                 expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
203                 Py_XDECREF(expr_vars);
204
205                 expr_vars= PyTuple_New(BLI_countlist(&driver->variables));
206                 PyTuple_SET_ITEM(((PyObject *)driver->expr_comp), 1, expr_vars);
207
208                 for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
209                         PyTuple_SET_ITEM(expr_vars, i++, PyUnicode_FromString(dvar->name));
210                 }
211                 
212                 driver->flag &= ~DRIVER_FLAG_RENAMEVAR;
213         }
214         else {
215                 expr_vars= PyTuple_GET_ITEM(((PyObject *)driver->expr_comp), 1);
216         }
217
218         /* add target values to a dict that will be used as '__locals__' dict */
219         driver_vars= PyDict_New(); // XXX do we need to decref this?
220         for (dvar= driver->variables.first, i=0; dvar; dvar= dvar->next) {
221                 PyObject *driver_arg= NULL;
222                 float tval= 0.0f;
223                 
224                 /* try to get variable value */
225                 tval= driver_get_variable_value(driver, dvar);
226                 driver_arg= PyFloat_FromDouble((double)tval);
227                 
228                 /* try to add to dictionary */
229                 /* if (PyDict_SetItemString(driver_vars, dvar->name, driver_arg)) { */
230                 if (PyDict_SetItem(driver_vars, PyTuple_GET_ITEM(expr_vars, i++), driver_arg) < 0) {
231                         /* this target failed - bad name */
232                         if (targets_ok) {
233                                 /* first one - print some extra info for easier identification */
234                                 fprintf(stderr, "\nBPY_driver_eval() - Error while evaluating PyDriver:\n");
235                                 targets_ok= 0;
236                         }
237                         
238                         fprintf(stderr, "\tBPY_driver_eval() - couldn't add variable '%s' to namespace\n", dvar->name);
239                         // BPy_errors_to_report(NULL); // TODO - reports
240                         PyErr_Print();
241                         PyErr_Clear();
242                 }
243         }
244
245 #if 0 // slow, with this can avoid all Py_CompileString above.
246         /* execute expression to get a value */
247         retval= PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
248 #else
249         /* evaluate the compiled expression */
250         if (expr_code)
251                 retval= PyEval_EvalCode((void *)expr_code, bpy_pydriver_Dict, driver_vars);
252 #endif
253
254         /* decref the driver vars first...  */
255         Py_DECREF(driver_vars);
256
257         /* process the result */
258         if (retval == NULL) {
259                 pydriver_error(driver);
260         }
261         else if ((result= PyFloat_AsDouble(retval)) == -1.0 && PyErr_Occurred()) {
262                 pydriver_error(driver);
263                 Py_DECREF(retval);
264                 result= 0.0;
265         }
266         else {
267                 /* all fine, make sure the "invalid expression" flag is cleared */
268                 driver->flag &= ~DRIVER_FLAG_INVALID;
269                 Py_DECREF(retval);
270         }
271
272         if (use_gil)
273                 PyGILState_Release(gilstate);
274
275         if (finite(result)) {
276                 return (float)result;
277         }
278         else {
279                 fprintf(stderr, "\tBPY_driver_eval() - driver '%s' evaluates to '%f'\n", dvar->name, result);
280                 return 0.0f;
281         }
282 }