BGE Py API
[blender.git] / source / gameengine / GameLogic / SCA_PythonController.cpp
1 /**
2  * Execute Python scripts
3  *
4  * $Id$
5  *
6  * ***** BEGIN GPL LICENSE BLOCK *****
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software Foundation,
20  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21  *
22  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
23  * All rights reserved.
24  *
25  * The Original Code is: all of this file.
26  *
27  * Contributor(s): none yet.
28  *
29  * ***** END GPL LICENSE BLOCK *****
30  */
31
32 #include "SCA_PythonController.h"
33 #include "SCA_LogicManager.h"
34 #include "SCA_ISensor.h"
35 #include "SCA_IActuator.h"
36 #include "PyObjectPlus.h"
37 #include "compile.h"
38 #include "eval.h"
39 #include <algorithm>
40
41
42 #ifdef HAVE_CONFIG_H
43 #include <config.h>
44 #endif
45
46 // initialize static member variables
47 SCA_PythonController* SCA_PythonController::m_sCurrentController = NULL;
48
49
50 SCA_PythonController::SCA_PythonController(SCA_IObject* gameobj,
51                                                                                    PyTypeObject* T)
52         : SCA_IController(gameobj, T),
53         m_bytecode(NULL),
54         m_bModified(true),
55         m_pythondictionary(NULL)
56 {
57 }
58
59 /*
60 //debugging
61 CValue*         SCA_PythonController::AddRef()
62 {
63         //printf("AddRef refcount = %i\n",GetRefCount());
64         return CValue::AddRef();
65 }
66 int                     SCA_PythonController::Release()
67 {
68         //printf("Release refcount = %i\n",GetRefCount());
69         return CValue::Release();
70 }
71 */
72
73
74
75 SCA_PythonController::~SCA_PythonController()
76 {
77         if (m_bytecode)
78         {
79                 //
80                 //printf("released python byte script\n");
81                 Py_DECREF(m_bytecode);
82         }
83         
84         if (m_pythondictionary)
85         {
86                 // break any circular references in the dictionary
87                 PyDict_Clear(m_pythondictionary);
88                 Py_DECREF(m_pythondictionary);
89         }
90 }
91
92
93
94 CValue* SCA_PythonController::GetReplica()
95 {
96         SCA_PythonController* replica = new SCA_PythonController(*this);
97         // Copy the compiled bytecode if possible.
98         Py_XINCREF(replica->m_bytecode);
99         replica->m_bModified = replica->m_bytecode == NULL;
100         
101         // The replica->m_pythondictionary is stolen - replace with a copy.
102         if (m_pythondictionary)
103                 replica->m_pythondictionary = PyDict_Copy(m_pythondictionary);
104                 
105         /*
106         // The other option is to incref the replica->m_pythondictionary -
107         // the replica objects can then share data.
108         if (m_pythondictionary)
109                 Py_INCREF(replica->m_pythondictionary);
110         */
111         
112         // this will copy properties and so on...
113         CValue::AddDataToReplica(replica);
114
115         return replica;
116 }
117
118
119
120 void SCA_PythonController::SetScriptText(const STR_String& text)
121
122         m_scriptText = text;
123         m_bModified = true;
124 }
125
126
127
128 void SCA_PythonController::SetScriptName(const STR_String& name)
129 {
130         m_scriptName = name;
131 }
132
133
134
135 void SCA_PythonController::SetDictionary(PyObject*      pythondictionary)
136 {
137         if (m_pythondictionary)
138         {
139                 PyDict_Clear(m_pythondictionary);
140                 Py_DECREF(m_pythondictionary);
141         }
142         m_pythondictionary = PyDict_Copy(pythondictionary); /* new reference */
143 }
144
145 int SCA_PythonController::IsTriggered(class SCA_ISensor* sensor)
146 {
147         if (std::find(m_triggeredSensors.begin(), m_triggeredSensors.end(), sensor) != 
148                 m_triggeredSensors.end())
149                 return 1;
150         return 0;
151 }
152
153 #if 0
154 static const char* sPyGetCurrentController__doc__;
155 #endif
156
157
158 PyObject* SCA_PythonController::sPyGetCurrentController(PyObject* self)
159 {
160         return m_sCurrentController->AddRef();
161 }
162
163 SCA_IActuator* SCA_PythonController::LinkedActuatorFromPy(PyObject *value)
164 {
165         // for safety, todo: only allow for registered actuators (pointertable)
166         // we don't want to crash gameengine/blender by python scripts
167         std::vector<SCA_IActuator*> lacts =  m_sCurrentController->GetLinkedActuators();
168         std::vector<SCA_IActuator*>::iterator it;
169         
170         if (PyString_Check(value)) {
171                 /* get the actuator from the name */
172                 char *name= PyString_AsString(value);
173                 for(it = lacts.begin(); it!= lacts.end(); it++) {
174                         if( name == (*it)->GetName() ) {
175                                 return *it;
176                         }
177                 }
178         }
179         else {
180                 /* Expecting an actuator type */
181                 for(it = lacts.begin(); it!= lacts.end(); it++) {
182                         if( static_cast<SCA_IActuator*>(value) == (*it) ) {
183                                 return *it;
184                         }
185                 }
186         }
187         
188         /* set the exception */
189         PyObject *value_str = PyObject_Repr(value); /* new ref */
190         PyErr_Format(PyExc_ValueError, "'%s' not in this controllers actuator list", PyString_AsString(value_str));
191         Py_DECREF(value_str);
192         
193         return false;
194 }
195
196 #if 0
197 static const char* sPyAddActiveActuator__doc__;
198 #endif
199
200 PyObject* SCA_PythonController::sPyAddActiveActuator(
201           
202                 PyObject* self, 
203                 PyObject* args)
204 {
205         
206         PyObject* ob1;
207         int activate;
208         if (!PyArg_ParseTuple(args, "Oi", &ob1,&activate))
209                 return NULL;
210         
211         SCA_IActuator* actu = LinkedActuatorFromPy(ob1);
212         if(actu==NULL)
213                 return NULL;
214         
215         CValue* boolval = new CBoolValue(activate!=0);
216         m_sCurrentLogicManager->AddActiveActuator((SCA_IActuator*)actu,boolval);
217         boolval->Release();
218         Py_RETURN_NONE;
219 }
220
221
222 const char* SCA_PythonController::sPyGetCurrentController__doc__ = "getCurrentController()";
223 const char* SCA_PythonController::sPyAddActiveActuator__doc__= "addActiveActuator(actuator,bool)";
224 const char SCA_PythonController::GetActuators_doc[] = "getActuator";
225
226 PyTypeObject SCA_PythonController::Type = {
227         PyObject_HEAD_INIT(&PyType_Type)
228                 0,
229                 "SCA_PythonController",
230                 sizeof(SCA_PythonController),
231                 0,
232                 PyDestructor,
233                 0,
234                 __getattr,
235                 __setattr,
236                 0, //&MyPyCompare,
237                 __repr,
238                 0, //&cvalue_as_number,
239                 0,
240                 0,
241                 0,
242                 0
243 };
244
245 PyParentObject SCA_PythonController::Parents[] = {
246         &SCA_PythonController::Type,
247         &SCA_IController::Type,
248         &CValue::Type,
249         NULL
250 };
251 PyMethodDef SCA_PythonController::Methods[] = {
252         {"activate", (PyCFunction) SCA_PythonController::sPyActivate, METH_O},
253         {"deactivate", (PyCFunction) SCA_PythonController::sPyDeActivate, METH_O},
254         
255         {"getActuators", (PyCFunction) SCA_PythonController::sPyGetActuators, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetActuators_doc},
256         {"getActuator", (PyCFunction) SCA_PythonController::sPyGetActuator, METH_O, (PY_METHODCHAR)SCA_PythonController::GetActuator_doc},
257         {"getSensors", (PyCFunction) SCA_PythonController::sPyGetSensors, METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::GetSensors_doc},
258         {"getSensor", (PyCFunction) SCA_PythonController::sPyGetSensor, METH_O, (PY_METHODCHAR)SCA_PythonController::GetSensor_doc},
259         //Deprecated functions ------>
260         {"setScript", (PyCFunction) SCA_PythonController::sPySetScript, METH_O},
261         {"getScript", (PyCFunction) SCA_PythonController::sPyGetScript, METH_NOARGS},
262         {"getState", (PyCFunction) SCA_PythonController::sPyGetState, METH_NOARGS},
263         //<----- Deprecated
264         {NULL,NULL} //Sentinel
265 };
266
267
268 bool SCA_PythonController::Compile()
269 {
270         //printf("py script modified '%s'\n", m_scriptName.Ptr());
271         
272         // if a script already exists, decref it before replace the pointer to a new script
273         if (m_bytecode)
274         {
275                 Py_DECREF(m_bytecode);
276                 m_bytecode=NULL;
277         }
278         // recompile the scripttext into bytecode
279         m_bytecode = Py_CompileString(m_scriptText.Ptr(), m_scriptName.Ptr(), Py_file_input);
280         m_bModified=false;
281         
282         if (m_bytecode)
283         {
284                 
285                 return true;
286         }
287         else {
288                 // didn't compile, so instead of compile, complain
289                 // something is wrong, tell the user what went wrong
290                 printf("Python compile error from controller \"%s\": \n", GetName().Ptr());
291                 //PyRun_SimpleString(m_scriptText.Ptr());
292                 PyErr_Print();
293                 
294                 /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
295                  * their user count. Not to mention holding references to wrapped data.
296                  * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
297                  * has alredy dealocated the pointer */
298                 PySys_SetObject( (char *)"last_traceback", Py_None);
299                 PyErr_Clear(); /* just to be sure */
300                 
301                 return false;
302         }
303 }
304
305 void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
306 {
307         m_sCurrentController = this;
308         m_sCurrentLogicManager = logicmgr;
309         
310         if (m_bModified)
311         {
312                 if (Compile()==false) // sets m_bModified to false
313                         return;
314         }
315         if (!m_bytecode) {
316                 return;
317         }
318                 
319         
320                 /*
321                  * This part here with excdict is a temporary patch
322                  * to avoid python/gameengine crashes when python
323                  * inadvertently holds references to game objects
324                  * in global variables.
325                  * 
326                  * The idea is always make a fresh dictionary, and
327                  * destroy it right after it is used to make sure
328                  * python won't hold any gameobject references.
329                  * 
330                  * Note that the PyDict_Clear _is_ necessary before
331                  * the Py_DECREF() because it is possible for the
332                  * variables inside the dictionary to hold references
333                  * to the dictionary (ie. generate a cycle), so we
334                  * break it by hand, then DECREF (which in this case
335                  * should always ensure excdict is cleared).
336                  */
337
338         PyObject *excdict= PyDict_Copy(m_pythondictionary);
339         PyObject* resultobj = PyEval_EvalCode((PyCodeObject*)m_bytecode,
340                 excdict, excdict);
341
342         if (resultobj)
343         {
344                 Py_DECREF(resultobj);
345         }
346         else
347         {
348                 // something is wrong, tell the user what went wrong
349                 printf("Python script error from controller \"%s\": \n", GetName().Ptr());
350                 PyErr_Print();
351                 
352                 /* Added in 2.48a, the last_traceback can reference Objects for example, increasing
353                  * their user count. Not to mention holding references to wrapped data.
354                  * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
355                  * has alredy dealocated the pointer */
356                 PySys_SetObject( (char *)"last_traceback", Py_None);
357                 PyErr_Clear(); /* just to be sure */
358                 
359                 //PyRun_SimpleString(m_scriptText.Ptr());
360         }
361
362         // clear after PyErrPrint - seems it can be using
363         // something in this dictionary and crash?
364         PyDict_Clear(excdict);
365         Py_DECREF(excdict);
366         m_triggeredSensors.erase(m_triggeredSensors.begin(), m_triggeredSensors.end());
367         m_sCurrentController = NULL;
368 }
369
370
371
372 PyObject* SCA_PythonController::_getattr(const char *attr)
373 {
374         if (!strcmp(attr,"state")) {
375                 return PyInt_FromLong(m_statemask);
376         }
377         if (!strcmp(attr,"script")) {
378                 return PyString_FromString(m_scriptText);
379         }
380         _getattr_up(SCA_IController);
381 }
382
383 int SCA_PythonController::_setattr(const char *attr, PyObject *value)
384 {
385         if (!strcmp(attr,"state")) {
386                 PyErr_SetString(PyExc_AttributeError, "state is read only");
387                 return 1;
388         }
389         if (!strcmp(attr,"script")) {
390                 char *scriptArg = PyString_AsString(value);
391                 
392                 if (scriptArg==NULL) {
393                         PyErr_SetString(PyExc_TypeError, "expected a string (script name)");
394                         return -1;
395                 }
396         
397                 /* set scripttext sets m_bModified to true, 
398                         so next time the script is needed, a reparse into byte code is done */
399                 this->SetScriptText(scriptArg);
400                 
401                 return 1;
402         }
403         return SCA_IController::_setattr(attr, value);
404 }
405
406 PyObject* SCA_PythonController::PyActivate(PyObject* self, PyObject *value)
407 {
408         SCA_IActuator* actu = LinkedActuatorFromPy(value);
409         if(actu==NULL)
410                 return NULL;
411         
412         CValue* boolval = new CBoolValue(true);
413         m_sCurrentLogicManager->AddActiveActuator((SCA_IActuator*)actu, boolval);
414         boolval->Release();
415         Py_RETURN_NONE;
416 }
417
418 PyObject* SCA_PythonController::PyDeActivate(PyObject* self, PyObject *value)
419 {
420         SCA_IActuator* actu = LinkedActuatorFromPy(value);
421         if(actu==NULL)
422                 return NULL;
423         
424         CValue* boolval = new CBoolValue(false);
425         m_sCurrentLogicManager->AddActiveActuator((SCA_IActuator*)actu, boolval);
426         boolval->Release();
427         Py_RETURN_NONE;
428 }
429
430 PyObject* SCA_PythonController::PyGetActuators(PyObject* self)
431 {
432         PyObject* resultlist = PyList_New(m_linkedactuators.size());
433         for (unsigned int index=0;index<m_linkedactuators.size();index++)
434         {
435                 PyList_SET_ITEM(resultlist,index,m_linkedactuators[index]->AddRef());
436         }
437
438         return resultlist;
439 }
440
441 const char SCA_PythonController::GetSensor_doc[] = 
442 "GetSensor (char sensorname) return linked sensor that is named [sensorname]\n";
443 PyObject*
444 SCA_PythonController::PyGetSensor(PyObject* self, PyObject* value)
445 {
446
447         char *scriptArg = PyString_AsString(value);
448         if (scriptArg==NULL) {
449                 PyErr_SetString(PyExc_TypeError, "expected a string (sensor name)");
450                 return NULL;
451         }
452         
453         for (unsigned int index=0;index<m_linkedsensors.size();index++)
454         {
455                 SCA_ISensor* sensor = m_linkedsensors[index];
456                 STR_String realname = sensor->GetName();
457                 if (realname == scriptArg)
458                 {
459                         return sensor->AddRef();
460                 }
461         }
462         
463         char emsg[96];
464         PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested sensor \"%s\"", scriptArg );
465         PyErr_SetString(PyExc_AttributeError, emsg);
466         return NULL;
467 }
468
469
470
471 const char SCA_PythonController::GetActuator_doc[] = 
472 "GetActuator (char sensorname) return linked actuator that is named [actuatorname]\n";
473 PyObject*
474 SCA_PythonController::PyGetActuator(PyObject* self, PyObject* value)
475 {
476
477         char *scriptArg = PyString_AsString(value);
478         if (scriptArg==NULL) {
479                 PyErr_SetString(PyExc_TypeError, "expected a string (actuator name)");
480                 return NULL;
481         }
482         
483         for (unsigned int index=0;index<m_linkedactuators.size();index++)
484         {
485                 SCA_IActuator* actua = m_linkedactuators[index];
486                 if (actua->GetName() == scriptArg)
487                 {
488                         return actua->AddRef();
489                 }
490         }
491         
492         char emsg[96];
493         PyOS_snprintf( emsg, sizeof( emsg ), "Unable to find requested actuator \"%s\"", scriptArg );
494         PyErr_SetString(PyExc_AttributeError, emsg);
495         return NULL;
496 }
497
498
499 const char SCA_PythonController::GetSensors_doc[]   = "getSensors returns a list of all attached sensors";
500 PyObject*
501 SCA_PythonController::PyGetSensors(PyObject* self)
502 {
503         PyObject* resultlist = PyList_New(m_linkedsensors.size());
504         for (unsigned int index=0;index<m_linkedsensors.size();index++)
505         {
506                 PyList_SET_ITEM(resultlist,index,m_linkedsensors[index]->AddRef());
507         }
508         
509         return resultlist;
510 }
511
512 /* 1. getScript */
513 PyObject* SCA_PythonController::PyGetScript(PyObject* self)
514 {
515         ShowDeprecationWarning("getScript()", "the script property");
516         return PyString_FromString(m_scriptText);
517 }
518
519 /* 2. setScript */
520 PyObject* SCA_PythonController::PySetScript(PyObject* self, PyObject* value)
521 {
522         char *scriptArg = PyString_AsString(value);
523         
524         ShowDeprecationWarning("setScript()", "the script property");
525         
526         if (scriptArg==NULL) {
527                 PyErr_SetString(PyExc_TypeError, "expected a string (script name)");
528                 return NULL;
529         }
530         
531         /* set scripttext sets m_bModified to true, 
532                 so next time the script is needed, a reparse into byte code is done */
533
534         this->SetScriptText(scriptArg);
535         
536         Py_RETURN_NONE;
537 }
538
539 /* 1. getScript */
540 PyObject* SCA_PythonController::PyGetState(PyObject* self)
541 {
542         ShowDeprecationWarning("getState()", "the state property");
543         return PyInt_FromLong(m_statemask);
544 }
545
546 /* eof */