BGE API - small changes
[blender.git] / source / gameengine / Ketsji / KX_PythonInit.cpp
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Initialize Python thingies.
29  */
30
31 #include "GL/glew.h"
32
33 // directory header for py function getBlendFileList
34 #include <stdlib.h>
35 #ifndef WIN32
36   #include <dirent.h>
37 #else
38   #include "BLI_winstuff.h"
39 #endif
40
41 #ifdef WIN32
42 #pragma warning (disable : 4786)
43 #endif //WIN32
44
45 #include "KX_PythonInit.h"
46 //python physics binding
47 #include "KX_PyConstraintBinding.h"
48
49 #include "KX_KetsjiEngine.h"
50 #include "KX_RadarSensor.h"
51 #include "KX_RaySensor.h"
52 #include "KX_SCA_DynamicActuator.h"
53
54 #include "SCA_IInputDevice.h"
55 #include "SCA_PropertySensor.h"
56 #include "SCA_RandomActuator.h"
57 #include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */
58 #include "KX_ConstraintActuator.h"
59 #include "KX_IpoActuator.h"
60 #include "KX_SoundActuator.h"
61 #include "KX_StateActuator.h"
62 #include "BL_ActionActuator.h"
63 #include "RAS_IRasterizer.h"
64 #include "RAS_ICanvas.h"
65 #include "RAS_BucketManager.h"
66 #include "RAS_2DFilterManager.h"
67 #include "MT_Vector3.h"
68 #include "MT_Point3.h"
69 #include "ListValue.h"
70 #include "KX_Scene.h"
71 #include "SND_DeviceManager.h"
72
73 #include "NG_NetworkScene.h" //Needed for sendMessage()
74
75 #include "BL_Shader.h"
76
77 #include "KX_PyMath.h"
78
79 #include "PyObjectPlus.h"
80
81 #include "KX_PythonInitTypes.h" 
82
83 extern "C" {
84         #include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
85         #include "bpy_internal_import.h"  /* from the blender python api, but we want to import text too! */
86         #include "BGL.h"
87 }
88
89 #include "marshal.h" /* python header for loading/saving dicts */
90
91 #include "PHY_IPhysicsEnvironment.h"
92 // FIXME: Enable for access to blender python modules.  This is disabled because
93 // python has dependencies on a lot of other modules and is a pain to link.
94 //#define USE_BLENDER_PYTHON
95 #ifdef USE_BLENDER_PYTHON
96 //#include "BPY_extern.h"
97 #endif 
98
99 #include "BKE_utildefines.h"
100 #include "BKE_global.h"
101 #include "BLI_blenlib.h"
102 #include "GPU_material.h"
103
104 static void setSandbox(TPythonSecurityLevel level);
105 static void clearGameModules();
106
107 // 'local' copy of canvas ptr, for window height/width python scripts
108 static RAS_ICanvas* gp_Canvas = NULL;
109 static KX_Scene*        gp_KetsjiScene = NULL;
110 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
111 static RAS_IRasterizer* gp_Rasterizer = NULL;
112 static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
113
114 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
115 {
116         if (gp_Rasterizer)
117                 gp_Rasterizer->DrawDebugLine(from,to,color);
118 }
119
120 /* Macro for building the keyboard translation */
121 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(SCA_IInputDevice::KX_##name))
122 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyInt_FromLong(name)); Py_DECREF(item)
123 /* For the defines for types from logic bricks, we do stuff explicitly... */
124 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, item=PyInt_FromLong(name2)); Py_DECREF(item)
125
126
127 // temporarily python stuff, will be put in another place later !
128 #include "KX_Python.h"
129 #include "SCA_PythonController.h"
130 // List of methods defined in the module
131
132 static PyObject* ErrorObject;
133 STR_String gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1)";
134
135 static PyObject* gPyGetRandomFloat(PyObject*)
136 {
137         return PyFloat_FromDouble(MT_random());
138 }
139
140 static PyObject* gPySetGravity(PyObject*, PyObject* value)
141 {
142         MT_Vector3 vec;
143         if (!PyVecTo(value, vec))
144                 return NULL;
145
146         if (gp_KetsjiScene)
147                 gp_KetsjiScene->SetGravity(vec);
148         
149         Py_RETURN_NONE;
150 }
151
152 static char gPyExpandPath_doc[] =
153 "(path) - Converts a blender internal path into a proper file system path.\n\
154 path - the string path to convert.\n\n\
155 Use / as directory separator in path\n\
156 You can use '//' at the start of the string to define a relative path;\n\
157 Blender replaces that string by the directory of the startup .blend or runtime\n\
158 file to make a full path name (doesn't change during the game, even if you load\n\
159 other .blend).\n\
160 The function also converts the directory separator to the local file system format.";
161
162 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
163 {
164         char expanded[FILE_MAXDIR + FILE_MAXFILE];
165         char* filename;
166         
167         if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename))
168                 return NULL;
169
170         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
171         BLI_convertstringcode(expanded, gp_GamePythonPath);
172         return PyString_FromString(expanded);
173 }
174
175 static char gPySendMessage_doc[] = 
176 "sendMessage(subject, [body, to, from])\n\
177 sends a message in same manner as a message actuator\
178 subject = Subject of the message\
179 body = Message body\
180 to = Name of object to send the message to\
181 from = Name of object to sned the string from";
182
183 static PyObject* gPySendMessage(PyObject*, PyObject* args)
184 {
185         char* subject;
186         char* body = (char *)"";
187         char* to = (char *)"";
188         char* from = (char *)"";
189
190         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from))
191                 return NULL;
192
193         gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body);
194
195         Py_RETURN_NONE;
196 }
197
198 static bool usedsp = false;
199
200 // this gets a pointer to an array filled with floats
201 static PyObject* gPyGetSpectrum(PyObject*)
202 {
203         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
204
205         PyObject* resultlist = PyList_New(512);
206
207         if (audiodevice)
208         {
209                 if (!usedsp)
210                 {
211                         audiodevice->StartUsingDSP();
212                         usedsp = true;
213                 }
214                         
215                 float* spectrum = audiodevice->GetSpectrum();
216
217                 for (int index = 0; index < 512; index++)
218                 {
219                         PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(spectrum[index]));
220                 }
221         }
222         else {
223                 for (int index = 0; index < 512; index++)
224                 {
225                         PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0));
226                 }
227         }
228
229         return resultlist;
230 }
231
232
233 #if 0 // unused
234 static PyObject* gPyStartDSP(PyObject*, PyObject* args)
235 {
236         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
237
238         if (!audiodevice) {
239                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
240                 return NULL;
241         }
242         
243         if (!usedsp) {
244                 audiodevice->StartUsingDSP();
245                 usedsp = true;
246         }
247         
248         Py_RETURN_NONE;
249 }
250 #endif
251
252
253 static PyObject* gPyStopDSP(PyObject*, PyObject* args)
254 {
255         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
256
257         if (!audiodevice) {
258                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
259                 return NULL;
260         }
261         
262         if (usedsp) {
263                 audiodevice->StopUsingDSP();
264                 usedsp = true;
265         }
266         
267         Py_RETURN_NONE;
268 }
269
270 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
271 {
272         float ticrate;
273         if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
274                 return NULL;
275         
276         KX_KetsjiEngine::SetTicRate(ticrate);
277         Py_RETURN_NONE;
278 }
279
280 static PyObject* gPyGetLogicTicRate(PyObject*)
281 {
282         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
283 }
284
285 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
286 {
287         float ticrate;
288         if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
289                 return NULL;
290         
291         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
292         Py_RETURN_NONE;
293 }
294 #if 0 // unused
295 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
296 {
297         int debugMode;
298         if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
299                 return NULL;
300         
301         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
302         Py_RETURN_NONE;
303 }
304 #endif
305
306
307 static PyObject* gPyGetPhysicsTicRate(PyObject*)
308 {
309         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
310 }
311
312 static PyObject* gPyGetAverageFrameRate(PyObject*)
313 {
314         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
315 }
316
317 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
318 {
319         char cpath[sizeof(gp_GamePythonPath)];
320         char *searchpath = NULL;
321         PyObject* list, *value;
322         
323     DIR *dp;
324     struct dirent *dirp;
325         
326         if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath))
327                 return NULL;
328         
329         list = PyList_New(0);
330         
331         if (searchpath) {
332                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
333                 BLI_convertstringcode(cpath, gp_GamePythonPath);
334         } else {
335                 /* Get the dir only */
336                 BLI_split_dirfile_basic(gp_GamePythonPath, cpath, NULL);
337         }
338         
339     if((dp  = opendir(cpath)) == NULL) {
340                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
341                 fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
342                 return list;
343     }
344         
345     while ((dirp = readdir(dp)) != NULL) {
346                 if (BLI_testextensie(dirp->d_name, ".blend")) {
347                         value = PyString_FromString(dirp->d_name);
348                         PyList_Append(list, value);
349                         Py_DECREF(value);
350                 }
351     }
352         
353     closedir(dp);
354     return list;
355 }
356
357 static STR_String gPyGetCurrentScene_doc =  
358 "getCurrentScene()\n"
359 "Gets a reference to the current scene.\n";
360 static PyObject* gPyGetCurrentScene(PyObject* self)
361 {
362         return gp_KetsjiScene->GetProxy();
363 }
364
365 static STR_String gPyGetSceneList_doc =  
366 "getSceneList()\n"
367 "Return a list of converted scenes.\n";
368 static PyObject* gPyGetSceneList(PyObject* self)
369 {
370         KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
371         PyObject* list;
372         KX_SceneList* scenes = m_engine->CurrentScenes();
373         int numScenes = scenes->size();
374         int i;
375         
376         list = PyList_New(numScenes);
377         
378         for (i=0;i<numScenes;i++)
379         {
380                 KX_Scene* scene = scenes->at(i);
381                 PyList_SET_ITEM(list, i, scene->GetProxy());
382         }
383         
384         return list;
385 }
386
387 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
388 {
389 #define pprint(x) std::cout << x << std::endl;
390         bool count=0;
391         bool support=0;
392         pprint("Supported Extensions...");
393         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
394         count = 1;
395
396         support= GLEW_ARB_vertex_shader;
397         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
398         count = 1;
399         if(support){
400                 pprint(" ----------Details----------");
401                 int max=0;
402                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
403                 pprint("  Max uniform components." << max);
404
405                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
406                 pprint("  Max varying floats." << max);
407
408                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
409                 pprint("  Max vertex texture units." << max);
410         
411                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
412                 pprint("  Max combined texture units." << max);
413                 pprint("");
414         }
415
416         support=GLEW_ARB_fragment_shader;
417         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
418         count = 1;
419         if(support){
420                 pprint(" ----------Details----------");
421                 int max=0;
422                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
423                 pprint("  Max uniform components." << max);
424                 pprint("");
425         }
426
427         support = GLEW_ARB_texture_cube_map;
428         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
429         count = 1;
430         if(support){
431                 pprint(" ----------Details----------");
432                 int size=0;
433                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
434                 pprint("  Max cubemap size." << size);
435                 pprint("");
436         }
437
438         support = GLEW_ARB_multitexture;
439         count = 1;
440         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
441         if(support){
442                 pprint(" ----------Details----------");
443                 int units=0;
444                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
445                 pprint("  Max texture units available.  " << units);
446                 pprint("");
447         }
448
449         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
450         count = 1;
451
452         if(!count)
453                 pprint("No extenstions are used in this build");
454
455         Py_RETURN_NONE;
456 }
457
458
459 static struct PyMethodDef game_methods[] = {
460         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (PY_METHODCHAR)gPyExpandPath_doc},
461         {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (PY_METHODCHAR)gPySendMessage_doc},
462         {"getCurrentController",
463         (PyCFunction) SCA_PythonController::sPyGetCurrentController,
464         METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::sPyGetCurrentController__doc__},
465         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
466         METH_NOARGS, (PY_METHODCHAR)gPyGetCurrentScene_doc.Ptr()},
467         {"getSceneList", (PyCFunction) gPyGetSceneList,
468         METH_NOARGS, (PY_METHODCHAR)gPyGetSceneList_doc.Ptr()},
469         {"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
470         METH_VARARGS, (PY_METHODCHAR)SCA_PythonController::sPyAddActiveActuator__doc__},
471         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
472         METH_NOARGS, (PY_METHODCHAR)gPyGetRandomFloat_doc.Ptr()},
473         {"setGravity",(PyCFunction) gPySetGravity, METH_O, (PY_METHODCHAR)"set Gravitation"},
474         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (PY_METHODCHAR)"get audio spectrum"},
475         {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS, (PY_METHODCHAR)"stop using the audio dsp (for performance reasons)"},
476         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the logic tic rate"},
477         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the logic tic rate"},
478         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the physics tic rate"},
479         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the physics tic rate"},
480         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (PY_METHODCHAR)"Gets the estimated average frame rate"},
481         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (PY_METHODCHAR)"Gets a list of blend files in the same directory as the current blend file"},
482         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (PY_METHODCHAR)"Prints GL Extension Info"},
483         {NULL, (PyCFunction) NULL, 0, NULL }
484 };
485
486
487 static PyObject* gPyGetScreenPosition(PyObject*, PyObject* value)
488 {
489         MT_Vector3 vect;
490         KX_GameObject *obj = NULL;
491
492         if (!PyVecTo(value, vect))
493         {
494                 if(ConvertPythonToGameObject(value, &obj, true, ""))
495                 {
496                         PyErr_Clear();
497                         vect = MT_Vector3(obj->NodeGetWorldPosition());
498                 }
499                 else
500                 {
501                         PyErr_SetString(PyExc_TypeError, "Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a string for a name of a KX_GameObject");
502                         return NULL;
503                 }
504         }
505
506         GLdouble modelMatrix[16];
507         GLdouble projMatrix[16];
508         GLint   viewport[4];
509         GLdouble win[3];
510
511         glGetIntegerv(GL_VIEWPORT, viewport);
512         glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
513         glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);
514
515         gluProject(vect[0], vect[1], vect[2], modelMatrix, projMatrix, viewport, &win[0], &win[1], &win[2]);
516
517         vect[0] =  win[0] / (viewport[0] + viewport[2]);
518         vect[1] =  win[1] / (viewport[1] + viewport[3]);
519
520         PyObject* ret = PyTuple_New(2);
521         if(ret){
522                 PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));
523                 PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));
524                 return ret;
525         }
526
527         return NULL;
528 }
529
530 static PyObject* gPyGetScreenVect(PyObject*, PyObject* args)
531 {
532         double x,y;
533         if (!PyArg_ParseTuple(args,"dd:getScreenVect",&x,&y))
534                 return NULL;
535
536         MT_Vector3 vect;
537         MT_Point3 campos, screenpos;
538
539         GLdouble modelMatrix[16];
540         GLdouble projMatrix[16];
541         GLint   viewport[4];
542         GLdouble win[3];
543
544         glGetIntegerv(GL_VIEWPORT, viewport);
545         glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
546         glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);
547
548         vect[0] = x * viewport[2];
549         vect[1] = y * viewport[3];
550
551         vect[0] += viewport[0];
552         vect[1] += viewport[1];
553
554         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &vect[2]);
555         gluUnProject(vect[0], vect[1], vect[2], modelMatrix, projMatrix, viewport, &win[0], &win[1], &win[2]);
556
557         campos    = gp_Rasterizer->GetCameraPosition();
558         screenpos = MT_Point3(win[0], win[1], win[2]);
559         vect = campos-screenpos;
560
561         vect.normalize();
562         return PyObjectFrom(vect);
563 }
564
565 static PyObject* gPyGetScreenRay(PyObject* self, PyObject* args)
566 {
567         KX_Camera* cam;
568         MT_Vector3 vect;
569         double x,y,dist;
570         char *propName = NULL;
571
572         if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName))
573                 return NULL;
574
575         PyObject* argValue = PyTuple_New(2);
576         if (argValue) {
577                 PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));
578                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));
579         }
580
581         if(!PyVecTo(gPyGetScreenVect(self,argValue), vect))
582         {
583                 Py_DECREF(argValue);
584                 PyErr_SetString(PyExc_TypeError,
585                         "Error in getScreenRay. Invalid 2D coordinate. Expected a normalized 2D screen coordinate and an optional property argument");
586                 return NULL;
587         }
588         Py_DECREF(argValue);
589
590         cam = gp_KetsjiScene->GetActiveCamera();
591         dist *= -1.0;
592
593         argValue = (propName?PyTuple_New(3):PyTuple_New(2));
594         if (argValue) {
595                 PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect));
596                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist));
597                 if (propName)
598                         PyTuple_SET_ITEM(argValue, 2, PyString_FromString(propName));
599
600                 PyObject* ret= cam->PyrayCastTo(argValue,NULL);
601                 Py_DECREF(argValue);
602                 return ret;
603         }
604
605         return NULL;
606 }
607
608 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
609 {
610         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
611 }
612
613
614
615 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
616 {
617         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
618 }
619
620
621
622 // temporarility visibility thing, will be moved to rasterizer/renderer later
623 bool gUseVisibilityTemp = false;
624
625 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
626 {
627         int visible;
628         if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
629                 return NULL;
630         
631         gUseVisibilityTemp = (visible != 0);
632         Py_RETURN_NONE;
633 }
634
635
636
637 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
638 {
639         int visible;
640         if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
641                 return NULL;
642         
643         if (visible)
644         {
645                 if (gp_Canvas)
646                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
647         } else
648         {
649                 if (gp_Canvas)
650                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
651         }
652         
653         Py_RETURN_NONE;
654 }
655
656
657
658 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
659 {
660         int x,y;
661         if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
662                 return NULL;
663         
664         if (gp_Canvas)
665                 gp_Canvas->SetMousePosition(x,y);
666         
667         Py_RETURN_NONE;
668 }
669
670 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
671 {
672         float sep;
673         if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
674                 return NULL;
675
676         if (!gp_Rasterizer) {
677                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available");
678                 return NULL;
679         }
680         
681         gp_Rasterizer->SetEyeSeparation(sep);
682         
683         Py_RETURN_NONE;
684 }
685
686 static PyObject* gPyGetEyeSeparation(PyObject*)
687 {
688         if (!gp_Rasterizer) {
689                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
690                 return NULL;
691         }
692         
693         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
694 }
695
696 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
697 {
698         float focus;
699         if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
700                 return NULL;
701         
702         if (!gp_Rasterizer) {
703                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available");
704                 return NULL;
705         }
706
707         gp_Rasterizer->SetFocalLength(focus);
708         
709         Py_RETURN_NONE;
710 }
711
712 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
713 {
714         if (!gp_Rasterizer) {
715                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
716                 return NULL;
717         }
718         
719         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
720         
721         Py_RETURN_NONE;
722 }
723
724 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
725 {
726         
727         MT_Vector4 vec;
728         if (!PyVecTo(value, vec))
729                 return NULL;
730         
731         if (gp_Canvas)
732         {
733                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
734         }
735         Py_RETURN_NONE;
736 }
737
738
739
740 static PyObject* gPySetMistColor(PyObject*, PyObject* value)
741 {
742         
743         MT_Vector3 vec;
744         if (!PyVecTo(value, vec))
745                 return NULL;
746         
747         if (!gp_Rasterizer) {
748                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
749                 return NULL;
750         }       
751         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
752         
753         Py_RETURN_NONE;
754 }
755
756 static PyObject* gPyDisableMist(PyObject*)
757 {
758         
759         if (!gp_Rasterizer) {
760                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
761                 return NULL;
762         }       
763         gp_Rasterizer->DisableFog();
764         
765         Py_RETURN_NONE;
766 }
767
768
769 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
770 {
771
772         float miststart;
773         if (!PyArg_ParseTuple(args,"f:setMistStart",&miststart))
774                 return NULL;
775         
776         if (!gp_Rasterizer) {
777                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistStart(float), Rasterizer not available");
778                 return NULL;
779         }
780         
781         gp_Rasterizer->SetFogStart(miststart);
782         
783         Py_RETURN_NONE;
784 }
785
786
787
788 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
789 {
790
791         float mistend;
792         if (!PyArg_ParseTuple(args,"f:setMistEnd",&mistend))
793                 return NULL;
794         
795         if (!gp_Rasterizer) {
796                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistEnd(float), Rasterizer not available");
797                 return NULL;
798         }
799         
800         gp_Rasterizer->SetFogEnd(mistend);
801         
802         Py_RETURN_NONE;
803 }
804
805
806 static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
807 {
808         
809         MT_Vector3 vec;
810         if (!PyVecTo(value, vec))
811                 return NULL;
812         
813         if (!gp_Rasterizer) {
814                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setAmbientColor(color), Rasterizer not available");
815                 return NULL;
816         }       
817         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
818         
819         Py_RETURN_NONE;
820 }
821
822
823
824
825 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
826 {
827         char* filename;
828         if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
829                 return NULL;
830         
831         if (gp_Canvas)
832         {
833                 gp_Canvas->MakeScreenShot(filename);
834         }
835         
836         Py_RETURN_NONE;
837 }
838
839 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
840 {
841         float motionblurvalue;
842         if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
843                 return NULL;
844         
845         if (!gp_Rasterizer) {
846                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available");
847                 return NULL;
848         }
849         
850         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
851         
852         Py_RETURN_NONE;
853 }
854
855 static PyObject* gPyDisableMotionBlur(PyObject*)
856 {
857         if (!gp_Rasterizer) {
858                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
859                 return NULL;
860         }
861         
862         gp_Rasterizer->DisableMotionBlur();
863         
864         Py_RETURN_NONE;
865 }
866
867 int getGLSLSettingFlag(char *setting)
868 {
869         if(strcmp(setting, "lights") == 0)
870                 return G_FILE_GLSL_NO_LIGHTS;
871         else if(strcmp(setting, "shaders") == 0)
872                 return G_FILE_GLSL_NO_SHADERS;
873         else if(strcmp(setting, "shadows") == 0)
874                 return G_FILE_GLSL_NO_SHADOWS;
875         else if(strcmp(setting, "ramps") == 0)
876                 return G_FILE_GLSL_NO_RAMPS;
877         else if(strcmp(setting, "nodes") == 0)
878                 return G_FILE_GLSL_NO_NODES;
879         else if(strcmp(setting, "extra_textures") == 0)
880                 return G_FILE_GLSL_NO_EXTRA_TEX;
881         else
882                 return -1;
883 }
884
885 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
886                                                                                         PyObject* args,
887                                                                                         PyObject*)
888 {
889         char *setting;
890         int enable, flag, fileflags;
891
892         if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable))
893                 return NULL;
894         
895         flag = getGLSLSettingFlag(setting);
896         
897         if  (flag==-1) {
898                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known");
899                 return NULL;
900         }
901
902         fileflags = G.fileflags;
903         
904         if (enable)
905                 G.fileflags &= ~flag;
906         else
907                 G.fileflags |= flag;
908
909         /* display lists and GLSL materials need to be remade */
910         if(G.fileflags != fileflags) {
911                 if(gp_KetsjiEngine) {
912                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
913                         KX_SceneList::iterator it;
914
915                         for(it=scenes->begin(); it!=scenes->end(); it++)
916                                 if((*it)->GetBucketManager())
917                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
918                 }
919
920                 GPU_materials_free();
921         }
922
923         Py_RETURN_NONE;
924 }
925
926 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
927                                                                          PyObject* args, 
928                                                                          PyObject*)
929 {
930         char *setting;
931         int enabled = 0, flag;
932
933         if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting))
934                 return NULL;
935         
936         flag = getGLSLSettingFlag(setting);
937         
938         if  (flag==-1) {
939                 PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known");
940                 return NULL;
941         }
942
943         enabled = ((G.fileflags & flag) != 0);
944         return PyInt_FromLong(enabled);
945 }
946
947 #define KX_TEXFACE_MATERIAL                             0
948 #define KX_BLENDER_MULTITEX_MATERIAL    1
949 #define KX_BLENDER_GLSL_MATERIAL                2
950
951 static PyObject* gPySetMaterialType(PyObject*,
952                                                                         PyObject* args,
953                                                                         PyObject*)
954 {
955         int flag, type;
956
957         if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
958                 return NULL;
959
960         if(type == KX_BLENDER_GLSL_MATERIAL)
961                 flag = G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL;
962         else if(type == KX_BLENDER_MULTITEX_MATERIAL)
963                 flag = G_FILE_GAME_MAT;
964         else if(type == KX_TEXFACE_MATERIAL)
965                 flag = 0;
966         else {
967                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
968                 return NULL;
969         }
970
971         G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL);
972         G.fileflags |= flag;
973
974         Py_RETURN_NONE;
975 }
976
977 static PyObject* gPyGetMaterialType(PyObject*)
978 {
979         int flag;
980
981         if(G.fileflags & (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL))
982                 flag = KX_BLENDER_GLSL_MATERIAL;
983         else if(G.fileflags & G_FILE_GAME_MAT)
984                 flag = KX_BLENDER_MULTITEX_MATERIAL;
985         else
986                 flag = KX_TEXFACE_MATERIAL;
987         
988         return PyInt_FromLong(flag);
989 }
990
991 static PyObject* gPyDrawLine(PyObject*, PyObject* args)
992 {
993         PyObject* ob_from;
994         PyObject* ob_to;
995         PyObject* ob_color;
996
997         if (!gp_Rasterizer) {
998                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
999                 return NULL;
1000         }
1001
1002         if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
1003                 return NULL;
1004
1005         MT_Vector3 from;
1006         MT_Vector3 to;
1007         MT_Vector3 color;
1008         if (!PyVecTo(ob_from, from))
1009                 return NULL;
1010         if (!PyVecTo(ob_to, to))
1011                 return NULL;
1012         if (!PyVecTo(ob_color, color))
1013                 return NULL;
1014
1015         gp_Rasterizer->DrawDebugLine(from,to,color);
1016         
1017         Py_RETURN_NONE;
1018 }
1019
1020 static struct PyMethodDef rasterizer_methods[] = {
1021   {"getScreenPosition",(PyCFunction) gPyGetScreenPosition,
1022    METH_O, "getScreenPosition doc"},
1023   {"getScreenVect",(PyCFunction) gPyGetScreenVect,
1024    METH_VARARGS, "getScreenVect doc"},
1025   {"getScreenRay",(PyCFunction) gPyGetScreenRay,
1026    METH_VARARGS, "getScreenRay doc"},
1027   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
1028    METH_VARARGS, "getWindowWidth doc"},
1029    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
1030    METH_VARARGS, "getWindowHeight doc"},
1031   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
1032         METH_VARARGS, "make Screenshot doc"},
1033    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
1034    METH_VARARGS, "enableVisibility doc"},
1035         {"showMouse",(PyCFunction) gPyShowMouse,
1036    METH_VARARGS, "showMouse(bool visible)"},
1037    {"setMousePosition",(PyCFunction) gPySetMousePosition,
1038    METH_VARARGS, "setMousePosition(int x,int y)"},
1039   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
1040         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
1041  {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
1042  {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
1043   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
1044   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
1045   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
1046   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
1047
1048   
1049   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
1050   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
1051   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
1052   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
1053   {"setMaterialMode",(PyCFunction) gPySetMaterialType,
1054    METH_VARARGS, "set the material mode to use for OpenGL rendering"},
1055   {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
1056    METH_NOARGS, "get the material mode being used for OpenGL rendering"},
1057   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
1058    METH_VARARGS, "set the state of a GLSL material setting"},
1059   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
1060    METH_VARARGS, "get the state of a GLSL material setting"},
1061   {"drawLine", (PyCFunction) gPyDrawLine,
1062    METH_VARARGS, "draw a line on the screen"},
1063   { NULL, (PyCFunction) NULL, 0, NULL }
1064 };
1065
1066 // Initialization function for the module (*must* be called initGameLogic)
1067
1068 static char GameLogic_module_documentation[] =
1069 "This is the Python API for the game engine of GameLogic"
1070 ;
1071
1072 static char Rasterizer_module_documentation[] =
1073 "This is the Python API for the game engine of Rasterizer"
1074 ;
1075
1076
1077
1078 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
1079 {
1080         PyObject* m;
1081         PyObject* d;
1082         PyObject* item; /* temp PyObject* storage */
1083         
1084         gp_KetsjiEngine = engine;
1085         gp_KetsjiScene = scene;
1086
1087         gUseVisibilityTemp=false;
1088
1089         // Create the module and add the functions
1090         m = Py_InitModule4("GameLogic", game_methods,
1091                                            GameLogic_module_documentation,
1092                                            (PyObject*)NULL,PYTHON_API_VERSION);
1093
1094         // Add some symbolic constants to the module
1095         d = PyModule_GetDict(m);
1096         
1097         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
1098         // for now its safe to make sure it exists for other areas such as the web plugin
1099         
1100         PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
1101
1102         ErrorObject = PyString_FromString("GameLogic.error");
1103         PyDict_SetItemString(d, "error", ErrorObject);
1104         Py_DECREF(ErrorObject);
1105         
1106         // XXXX Add constants here
1107         /* To use logic bricks, we need some sort of constants. Here, we associate */
1108         /* constants and sumbolic names. Add them to dictionary d.                 */
1109
1110         /* 1. true and false: needed for everyone                                  */
1111         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
1112         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
1113
1114         /* 2. Property sensor                                                      */
1115         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
1116         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
1117         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
1118         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
1119         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
1120
1121         /* 3. Constraint actuator                                                  */
1122         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
1123         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
1124         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
1125         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
1126         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
1127         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
1128         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
1129         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1130         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1131         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
1132         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1133         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1134         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
1135         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
1136         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
1137         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
1138         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
1139         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
1140         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
1141         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
1142         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
1143
1144         /* 4. Ipo actuator, simple part                                            */
1145         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
1146         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
1147         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
1148         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
1149         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
1150         KX_MACRO_addTypesToDict(d, KX_IPOACT_FROM_PROP,KX_IpoActuator::KX_ACT_IPO_FROM_PROP);
1151
1152         /* 5. Random distribution types                                            */
1153         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
1154         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
1155         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
1156         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
1157         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
1158         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
1159         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
1160         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
1161         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
1162         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
1163
1164         /* 6. Sound actuator                                                      */
1165         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1166         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1167         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1168         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
1169         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1170         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1171
1172         /* 7. Action actuator                                                                                                      */
1173         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
1174         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
1175         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
1176         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
1177         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1178         
1179         /*8. GL_BlendFunc */
1180         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1181         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1182         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1183         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1184         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1185         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1186         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1187         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1188         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1189         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1190         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1191
1192
1193         /* 9. UniformTypes */
1194         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1195         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1196         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1197         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1198         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1199         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1200         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1201         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1202         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1203         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1204         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1205         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1206         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1207         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1208         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1209
1210         /* 10 state actuator */
1211         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1212         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1213         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1214         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1215         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1216         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1217         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1218         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1219         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1220         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1221         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1222         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1223         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1224         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1225         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1226         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1227         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1228         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1229         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1230         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1231         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1232         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1233         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1234         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1235         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1236         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1237         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1238         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1239         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1240         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1241
1242         /* Radar Sensor */
1243         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1244         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1245         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1246         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1247         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1248         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1249
1250         /* Ray Sensor */
1251         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
1252         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
1253         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
1254         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
1255         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_X);
1256         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
1257
1258         /* Dynamic actuator */
1259         KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
1260         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
1261         KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
1262         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
1263         KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
1264
1265         /* Input & Mouse Sensor */
1266         KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
1267         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
1268         KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
1269         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
1270         
1271         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
1272         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
1273         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
1274
1275         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
1276         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
1277         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
1278         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
1279         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
1280         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
1281         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
1282         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
1283         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
1284         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
1285         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
1286         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
1287         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
1288         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
1289         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
1290                 
1291         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1292         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1293         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1294         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
1295         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1296         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1297
1298         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
1299         KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
1300         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
1301         KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
1302
1303         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
1304         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
1305         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
1306         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
1307         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
1308         KX_MACRO_addTypesToDict(d, KX_ACT_CONSTRAINT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
1309
1310         // Check for errors
1311         if (PyErr_Occurred())
1312     {
1313                 Py_FatalError("can't initialize module GameLogic");
1314     }
1315
1316         return m;
1317 }
1318
1319 // Python Sandbox code
1320 // override builtin functions import() and open()
1321
1322
1323 PyObject *KXpy_open(PyObject *self, PyObject *args) {
1324         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
1325         return NULL;
1326 }
1327
1328 PyObject *KXpy_file(PyObject *self, PyObject *args) {
1329         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
1330         return NULL;
1331 }
1332
1333 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
1334         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
1335         return NULL;
1336 }
1337
1338 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
1339         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
1340         return NULL;
1341 }
1342
1343 PyObject *KXpy_import(PyObject *self, PyObject *args)
1344 {
1345         char *name;
1346         int found;
1347         PyObject *globals = NULL;
1348         PyObject *locals = NULL;
1349         PyObject *fromlist = NULL;
1350         PyObject *l, *m, *n;
1351
1352 #if (PY_VERSION_HEX >= 0x02060000)
1353         int dummy_val; /* what does this do?*/
1354         
1355         if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
1356                 &name, &globals, &locals, &fromlist, &dummy_val))
1357             return NULL;
1358 #else
1359         if (!PyArg_ParseTuple(args, "s|OOO:m_import",
1360                 &name, &globals, &locals, &fromlist))
1361             return NULL;
1362 #endif
1363
1364         /* check for builtin modules */
1365         m = PyImport_AddModule("sys");
1366         l = PyObject_GetAttrString(m, "builtin_module_names");
1367         n = PyString_FromString(name);
1368         
1369         if (PySequence_Contains(l, n)) {
1370                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1371         }
1372
1373         /* quick hack for GamePython modules 
1374                 TODO: register builtin modules properly by ExtendInittab */
1375         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
1376                 !strcmp(name, "Rasterizer") || !strcmp(name, "Mathutils") || !strcmp(name, "BGL")) {
1377                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1378         }
1379         
1380         /* Import blender texts as python modules */
1381         m= bpy_text_import(name, &found);
1382         if (m)
1383                 return m;
1384         
1385         if(found==0) /* if its found but could not import then it has its own error */
1386                 PyErr_Format(PyExc_ImportError, "Import of external Module %.20s not allowed.", name);
1387         
1388         return NULL;
1389
1390 }
1391
1392 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
1393         
1394         /* Used to be sandboxed, bettet to allow importing of internal text only */ 
1395 #if 0
1396         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
1397         return NULL;
1398 #endif
1399         int found;
1400         PyObject *module = NULL;
1401         PyObject *newmodule = NULL;
1402
1403         /* check for a module arg */
1404         if( !PyArg_ParseTuple( args, "O:bpy_reload_meth", &module ) )
1405                 return NULL;
1406         
1407         newmodule= bpy_text_reimport( module, &found );
1408         if (newmodule)
1409                 return newmodule;
1410         
1411         if (found==0) /* if its found but could not import then it has its own error */
1412                 PyErr_SetString(PyExc_ImportError, "reload(module): failed to reload from blenders internal text");
1413         
1414         return newmodule;
1415 }
1416
1417 /* override python file type functions */
1418 #if 0
1419 static int
1420 file_init(PyObject *self, PyObject *args, PyObject *kwds)
1421 {
1422         KXpy_file(NULL, NULL);
1423         return -1;
1424 }
1425
1426 static PyObject *
1427 file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1428 {
1429         return KXpy_file(NULL, NULL);
1430 }
1431 #endif
1432
1433 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
1434 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
1435 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
1436 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
1437 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1438
1439 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1440
1441 //static PyObject *g_oldopen = 0;
1442 //static PyObject *g_oldimport = 0;
1443 //static int g_security = 0;
1444
1445 void setSandbox(TPythonSecurityLevel level)
1446 {
1447     PyObject *m = PyImport_AddModule("__builtin__");
1448     PyObject *d = PyModule_GetDict(m);
1449         PyObject *item;
1450         switch (level) {
1451         case psl_Highest:
1452                 //if (!g_security) {
1453                         //g_oldopen = PyDict_GetItemString(d, "open");
1454         
1455                         // functions we cant trust
1456                         PyDict_SetItemString(d, "open", item=PyCFunction_New(meth_open, NULL));                 Py_DECREF(item);
1457                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(meth_reload, NULL));             Py_DECREF(item);
1458                         PyDict_SetItemString(d, "file", item=PyCFunction_New(meth_file, NULL));                 Py_DECREF(item);
1459                         PyDict_SetItemString(d, "execfile", item=PyCFunction_New(meth_execfile, NULL)); Py_DECREF(item);
1460                         PyDict_SetItemString(d, "compile", item=PyCFunction_New(meth_compile, NULL));           Py_DECREF(item);
1461                         
1462                         // our own import
1463                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1464                         //g_security = level;
1465                         
1466                         // Overiding file dosnt stop it being accessed if your sneaky
1467                         //    f =  [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
1468                         //    f.write('...')
1469                         // so overwrite the file types functions. be very careful here still, since python uses python.
1470                         // ps - python devs frown deeply upon this.
1471         
1472                         /* this could mess up pythons internals, if we are serious about sandboxing
1473                          * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
1474 #if 0
1475                         PyFile_Type.tp_init = file_init;
1476                         PyFile_Type.tp_new = file_new;
1477 #endif
1478                 //}
1479                 break;
1480         /*
1481         case psl_Lowest:
1482                 if (g_security) {
1483                         PyDict_SetItemString(d, "open", g_oldopen);
1484                         PyDict_SetItemString(d, "__import__", g_oldimport);
1485                         g_security = level;
1486                 }
1487         */
1488         default:
1489                         /* Allow importing internal text, from bpy_internal_import.py */
1490                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL));         Py_DECREF(item);
1491                         PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL));     Py_DECREF(item);
1492                 break;
1493         }
1494 }
1495
1496 /**
1497  * Python is not initialised.
1498  */
1499 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
1500 {
1501         STR_String pname = progname;
1502         Py_SetProgramName(pname.Ptr());
1503         Py_NoSiteFlag=1;
1504         Py_FrozenFlag=1;
1505         Py_Initialize();
1506         
1507         if(argv) /* browser plugins dont currently set this */
1508                 PySys_SetArgv(argc, argv);
1509         
1510         //importBlenderModules()
1511         
1512         setSandbox(level);
1513         initPyTypes();
1514         
1515         bpy_import_main_set(maggie);
1516         
1517         PyObject* moduleobj = PyImport_AddModule("__main__");
1518         return PyModule_GetDict(moduleobj);
1519 }
1520
1521 void exitGamePlayerPythonScripting()
1522 {
1523         //clearGameModules(); // were closing python anyway
1524         Py_Finalize();
1525         bpy_import_main_set(NULL);
1526 }
1527
1528 /**
1529  * Python is already initialized.
1530  */
1531 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
1532 {
1533         STR_String pname = progname;
1534         Py_SetProgramName(pname.Ptr());
1535         Py_NoSiteFlag=1;
1536         Py_FrozenFlag=1;
1537
1538         setSandbox(level);
1539         initPyTypes();
1540         
1541         bpy_import_main_set(maggie);
1542         
1543         /* run this to clear game modules and user modules which
1544          * may contain references to in game data */
1545         clearGameModules();
1546
1547         PyObject* moduleobj = PyImport_AddModule("__main__");
1548         return PyModule_GetDict(moduleobj);
1549 }
1550
1551 static void clearModule(PyObject *modules, const char *name)
1552 {
1553         PyObject *mod= PyDict_GetItemString(modules, name);
1554         
1555         if (mod==NULL)
1556                 return;
1557         
1558         PyDict_Clear(PyModule_GetDict(mod)); /* incase there are any circular refs */
1559         PyDict_DelItemString(modules, name);
1560 }
1561
1562 static void clearGameModules()
1563 {
1564         /* Note, user modules could still reference these modules
1565          * but since the dict's are cleared their members wont be accessible */
1566         
1567         PyObject *modules= PySys_GetObject((char *)"modules");
1568         clearModule(modules, "Expression");
1569         clearModule(modules, "CValue"); 
1570         clearModule(modules, "PhysicsConstraints");     
1571         clearModule(modules, "GameLogic");      
1572         clearModule(modules, "Rasterizer");     
1573         clearModule(modules, "GameKeys");       
1574         clearModule(modules, "VideoTexture");   
1575         clearModule(modules, "Mathutils");      
1576         clearModule(modules, "BGL");    
1577         PyErr_Clear(); // incase some of these were alredy removed.
1578         
1579         /* clear user defined modules */
1580         bpy_text_clear_modules();
1581 }
1582
1583 void exitGamePythonScripting()
1584 {
1585         clearGameModules();
1586         bpy_import_main_set(NULL);
1587 }
1588
1589
1590
1591 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
1592 {
1593         gp_Canvas = canvas;
1594         gp_Rasterizer = rasty;
1595
1596
1597   PyObject* m;
1598   PyObject* d;
1599   PyObject* item;
1600
1601   // Create the module and add the functions
1602   m = Py_InitModule4("Rasterizer", rasterizer_methods,
1603                      Rasterizer_module_documentation,
1604                      (PyObject*)NULL,PYTHON_API_VERSION);
1605
1606   // Add some symbolic constants to the module
1607   d = PyModule_GetDict(m);
1608   ErrorObject = PyString_FromString("Rasterizer.error");
1609   PyDict_SetItemString(d, "error", ErrorObject);
1610   Py_DECREF(ErrorObject);
1611
1612   /* needed for get/setMaterialType */
1613   KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
1614   KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
1615   KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
1616
1617   // XXXX Add constants here
1618
1619   // Check for errors
1620   if (PyErr_Occurred())
1621     {
1622       Py_FatalError("can't initialize module Rasterizer");
1623     }
1624
1625   return d;
1626 }
1627
1628
1629
1630 /* ------------------------------------------------------------------------- */
1631 /* GameKeys: symbolic constants for key mapping                              */
1632 /* ------------------------------------------------------------------------- */
1633
1634 static char GameKeys_module_documentation[] =
1635 "This modules provides defines for key-codes"
1636 ;
1637
1638 static char gPyEventToString_doc[] =
1639 "EventToString(event) - Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
1640 ;
1641
1642 static PyObject* gPyEventToString(PyObject*, PyObject* value)
1643 {
1644         PyObject* mod, *dict, *key, *val, *ret = NULL;
1645         Py_ssize_t pos = 0;
1646         
1647         mod = PyImport_ImportModule( "GameKeys" );
1648         if (!mod)
1649                 return NULL;
1650         
1651         dict = PyModule_GetDict(mod);
1652         
1653         while (PyDict_Next(dict, &pos, &key, &val)) {
1654                 if (PyObject_Compare(value, val)==0) {
1655                         ret = key;
1656                         break;
1657                 }
1658         }
1659         
1660         PyErr_Clear(); // incase there was an error clearing
1661         Py_DECREF(mod);
1662         if (!ret)       PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
1663         else            Py_INCREF(ret);
1664         
1665         return ret;
1666 }
1667
1668 static char gPyEventToCharacter_doc[] =
1669 "EventToCharacter(event, is_shift) - Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
1670 ;
1671
1672 static PyObject* gPyEventToCharacter(PyObject*, PyObject* args)
1673 {
1674         int event, shift;
1675         if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
1676                 return NULL;
1677         
1678         if(IsPrintable(event)) {
1679                 char ch[2] = {'\0', '\0'};
1680                 ch[0] = ToCharacter(event, (bool)shift);
1681                 return PyString_FromString(ch);
1682         }
1683         else {
1684                 return PyString_FromString("");
1685         }
1686 }
1687
1688
1689 static struct PyMethodDef gamekeys_methods[] = {
1690         {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (PY_METHODCHAR)gPyEventToCharacter_doc},
1691         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (PY_METHODCHAR)gPyEventToString_doc},
1692         { NULL, (PyCFunction) NULL, 0, NULL }
1693 };
1694
1695
1696
1697 PyObject* initGameKeys()
1698 {
1699         PyObject* m;
1700         PyObject* d;
1701         PyObject* item;
1702
1703         // Create the module and add the functions
1704         m = Py_InitModule4("GameKeys", gamekeys_methods,
1705                                            GameKeys_module_documentation,
1706                                            (PyObject*)NULL,PYTHON_API_VERSION);
1707
1708         // Add some symbolic constants to the module
1709         d = PyModule_GetDict(m);
1710
1711         // XXXX Add constants here
1712
1713         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
1714         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
1715         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
1716         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
1717         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
1718         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
1719         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
1720         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
1721         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
1722         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
1723         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
1724         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
1725         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
1726         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
1727         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
1728         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
1729         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
1730         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
1731         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
1732         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
1733         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
1734         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
1735         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
1736         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
1737         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
1738         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
1739         
1740         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
1741         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
1742         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
1743         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
1744         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
1745         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
1746         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
1747         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
1748         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
1749         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
1750                 
1751         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
1752                 
1753         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
1754         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
1755         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
1756         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
1757         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
1758         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
1759                 
1760         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
1761         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
1762         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
1763         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
1764         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
1765         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
1766         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
1767         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
1768         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
1769         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
1770         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
1771         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
1772         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
1773         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
1774         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
1775         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
1776         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
1777         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
1778                 
1779         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
1780         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
1781         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
1782         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
1783         
1784         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
1785         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
1786         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
1787         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
1788                 
1789         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
1790         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
1791         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
1792         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
1793         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
1794                 
1795         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
1796         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
1797         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
1798                 
1799                 
1800         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
1801         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
1802         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
1803         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
1804                 
1805                 
1806         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
1807         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
1808         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
1809         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
1810         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
1811         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
1812         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
1813         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
1814         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
1815         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
1816         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
1817         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
1818                 
1819         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
1820         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
1821         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
1822         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
1823         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
1824         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
1825
1826         // Check for errors
1827         if (PyErr_Occurred())
1828     {
1829                 Py_FatalError("can't initialize module GameKeys");
1830     }
1831
1832         return d;
1833 }
1834
1835 PyObject* initMathutils()
1836 {
1837         return Mathutils_Init("Mathutils"); // Use as a top level module in BGE
1838 }
1839
1840 PyObject* initBGL()
1841 {
1842         return BGL_Init("BGL"); // Use as a top level module in BGE
1843 }
1844
1845 void KX_SetActiveScene(class KX_Scene* scene)
1846 {
1847         gp_KetsjiScene = scene;
1848 }
1849
1850 class KX_Scene* KX_GetActiveScene()
1851 {
1852         return gp_KetsjiScene;
1853 }
1854
1855 class KX_KetsjiEngine* KX_GetActiveEngine()
1856 {
1857         return gp_KetsjiEngine;
1858 }
1859
1860 // utility function for loading and saving the globalDict
1861 int saveGamePythonConfig( char **marshal_buffer)
1862 {
1863         int marshal_length = 0;
1864         PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1865         if (gameLogic) {
1866                 PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
1867                 if (pyGlobalDict) {
1868 #ifdef Py_MARSHAL_VERSION       
1869                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
1870 #else
1871                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict ); 
1872 #endif
1873                         if (pyGlobalDictMarshal) {
1874                                 // for testing only
1875                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
1876
1877                                 marshal_length= PyString_Size(pyGlobalDictMarshal);
1878                                 *marshal_buffer = new char[marshal_length + 1];
1879                                 memcpy(*marshal_buffer, PyString_AsString(pyGlobalDictMarshal), marshal_length);
1880
1881                                 Py_DECREF(pyGlobalDictMarshal);
1882                         } else {
1883                                 printf("Error, GameLogic.globalDict could not be marshal'd\n");
1884                         }
1885                 } else {
1886                         printf("Error, GameLogic.globalDict was removed\n");
1887                 }
1888                 Py_DECREF(gameLogic);
1889         } else {
1890                 PyErr_Clear();
1891                 printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1892         }
1893         return marshal_length;
1894 }
1895
1896 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
1897 {
1898         /* Restore the dict */
1899         if (marshal_buffer) {
1900                 PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1901
1902                 if (gameLogic) {
1903                         PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
1904                         if (pyGlobalDict) {
1905                                 PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
1906                                 if (pyGlobalDict_orig) {
1907                                         PyDict_Clear(pyGlobalDict_orig);
1908                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
1909                                 } else {
1910                                         /* this should not happen, but cant find the original globalDict, just assign it then */
1911                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
1912                                 }
1913                                 Py_DECREF(gameLogic);
1914                                 Py_DECREF(pyGlobalDict);
1915                                 return 1;
1916                         } else {
1917                                 Py_DECREF(gameLogic);
1918                                 PyErr_Clear();
1919                                 printf("Error could not marshall string\n");
1920                         }
1921                 } else {
1922                         PyErr_Clear();
1923                         printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1924                 }       
1925         }
1926         return 0;
1927 }
1928
1929 void pathGamePythonConfig( char *path )
1930 {
1931         int len = strlen(gp_GamePythonPath);
1932         
1933         BLI_strncpy(path, gp_GamePythonPath, sizeof(gp_GamePythonPath));
1934
1935         /* replace extension */
1936         if (BLI_testextensie(path, ".blend")) {
1937                 strcpy(path+(len-6), ".bgeconf");
1938         } else {
1939                 strcpy(path+len, ".bgeconf");
1940         }
1941 }
1942
1943 void setGamePythonPath(char *path)
1944 {
1945         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
1946 }
1947