53b141a9bfe363ec0eb9476d527f0009c8d26c2f
[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
51 #include "SCA_IInputDevice.h"
52 #include "SCA_PropertySensor.h"
53 #include "SCA_RandomActuator.h"
54 #include "KX_ConstraintActuator.h"
55 #include "KX_IpoActuator.h"
56 #include "KX_SoundActuator.h"
57 #include "BL_ActionActuator.h"
58 #include "RAS_IRasterizer.h"
59 #include "RAS_ICanvas.h"
60 #include "RAS_BucketManager.h"
61 #include "MT_Vector3.h"
62 #include "MT_Point3.h"
63 #include "ListValue.h"
64 #include "KX_Scene.h"
65 #include "SND_DeviceManager.h"
66
67 #include "BL_Shader.h"
68
69 #include "KX_PyMath.h"
70
71 #include "PyObjectPlus.h" 
72
73 extern "C" {
74         #include "Mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
75 }
76
77 #include "marshal.h" /* python header for loading/saving dicts */
78
79 #include "PHY_IPhysicsEnvironment.h"
80 // FIXME: Enable for access to blender python modules.  This is disabled because
81 // python has dependencies on a lot of other modules and is a pain to link.
82 //#define USE_BLENDER_PYTHON
83 #ifdef USE_BLENDER_PYTHON
84 //#include "BPY_extern.h"
85 #endif 
86
87 #include "BKE_utildefines.h"
88 #include "BKE_global.h"
89 #include "BLI_blenlib.h"
90 #include "GPU_material.h"
91
92 static void setSandbox(TPythonSecurityLevel level);
93
94
95 // 'local' copy of canvas ptr, for window height/width python scripts
96 static RAS_ICanvas* gp_Canvas = NULL;
97 static KX_Scene*        gp_KetsjiScene = NULL;
98 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
99 static RAS_IRasterizer* gp_Rasterizer = NULL;
100
101 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
102 {
103         if (gp_Rasterizer)
104                 gp_Rasterizer->DrawDebugLine(from,to,color);
105 }
106
107 /* Macro for building the keyboard translation */
108 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(SCA_IInputDevice::KX_##name))
109 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyInt_FromLong(name))
110 /* For the defines for types from logic bricks, we do stuff explicitly... */
111 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, PyInt_FromLong(name2))
112
113
114 // temporarily python stuff, will be put in another place later !
115 #include "KX_Python.h"
116 #include "SCA_PythonController.h"
117 // List of methods defined in the module
118
119 static PyObject* ErrorObject;
120 STR_String gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1)";
121
122 static PyObject* gPyGetRandomFloat(PyObject*)
123 {
124         return PyFloat_FromDouble(MT_random());
125 }
126
127 static PyObject* gPySetGravity(PyObject*, PyObject* args)
128 {
129         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
130         if (!PyVecArgTo(args, vec))
131                 return NULL;
132
133         if (gp_KetsjiScene)
134                 gp_KetsjiScene->SetGravity(vec);
135         
136         Py_RETURN_NONE;
137 }
138
139 static char gPyExpandPath_doc[] =
140 "(path) - Converts a blender internal path into a proper file system path.\n\
141 path - the string path to convert.\n\n\
142 Use / as directory separator in path\n\
143 You can use '//' at the start of the string to define a relative path;\n\
144 Blender replaces that string by the directory of the startup .blend or runtime\n\
145 file to make a full path name (doesn't change during the game, even if you load\n\
146 other .blend).\n\
147 The function also converts the directory separator to the local file system format.";
148
149 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
150 {
151         char expanded[FILE_MAXDIR + FILE_MAXFILE];
152         char* filename;
153         
154         if (!PyArg_ParseTuple(args,"s",&filename))
155                 return NULL;
156
157         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
158         BLI_convertstringcode(expanded, G.sce);
159         return PyString_FromString(expanded);
160 }
161
162
163 static bool usedsp = false;
164
165 // this gets a pointer to an array filled with floats
166 static PyObject* gPyGetSpectrum(PyObject*)
167 {
168         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
169
170         PyObject* resultlist = PyList_New(512);
171
172         if (audiodevice)
173         {
174                 if (!usedsp)
175                 {
176                         audiodevice->StartUsingDSP();
177                         usedsp = true;
178                 }
179                         
180                 float* spectrum = audiodevice->GetSpectrum();
181
182                 for (int index = 0; index < 512; index++)
183                 {
184                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(spectrum[index]));
185                 }
186         }
187         else {
188                 for (int index = 0; index < 512; index++)
189                 {
190                         PyList_SetItem(resultlist, index, PyFloat_FromDouble(0.0));
191                 }
192         }
193
194         return resultlist;
195 }
196
197
198
199 static PyObject* gPyStartDSP(PyObject*, PyObject* args)
200 {
201         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
202
203         if (!audiodevice) {
204                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
205                 return NULL;
206         }
207         
208         if (!usedsp) {
209                 audiodevice->StartUsingDSP();
210                 usedsp = true;
211         }
212         
213         Py_RETURN_NONE;
214 }
215
216
217
218 static PyObject* gPyStopDSP(PyObject*, PyObject* args)
219 {
220         SND_IAudioDevice* audiodevice = SND_DeviceManager::Instance();
221
222         if (!audiodevice) {
223                 PyErr_SetString(PyExc_RuntimeError, "no audio device available");
224                 return NULL;
225         }
226         
227         if (usedsp) {
228                 audiodevice->StopUsingDSP();
229                 usedsp = true;
230         }
231         
232         Py_RETURN_NONE;
233 }
234
235 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
236 {
237         float ticrate;
238         if (!PyArg_ParseTuple(args, "f", &ticrate))
239                 return NULL;
240         
241         KX_KetsjiEngine::SetTicRate(ticrate);
242         Py_RETURN_NONE;
243 }
244
245 static PyObject* gPyGetLogicTicRate(PyObject*)
246 {
247         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
248 }
249
250 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
251 {
252         float ticrate;
253         if (!PyArg_ParseTuple(args, "f", &ticrate))
254                 return NULL;
255         
256         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
257         Py_RETURN_NONE;
258 }
259
260 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
261 {
262         int debugMode;
263         if (!PyArg_ParseTuple(args, "i", &debugMode))
264                 return NULL;
265         
266         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
267         Py_RETURN_NONE;
268 }
269
270
271
272 static PyObject* gPyGetPhysicsTicRate(PyObject*)
273 {
274         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
275 }
276
277 static PyObject* gPyGetAverageFrameRate(PyObject*)
278 {
279         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
280 }
281
282 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
283 {
284         char cpath[sizeof(G.sce)];
285         char *searchpath = NULL;
286         PyObject* list, *value;
287         
288     DIR *dp;
289     struct dirent *dirp;
290         
291         if (!PyArg_ParseTuple(args, "|s", &searchpath))
292                 return NULL;
293         
294         list = PyList_New(0);
295         
296         if (searchpath) {
297                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
298                 BLI_convertstringcode(cpath, G.sce);
299         } else {
300                 /* Get the dir only */
301                 BLI_split_dirfile_basic(G.sce, cpath, NULL);
302         }
303         
304     if((dp  = opendir(cpath)) == NULL) {
305                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
306                 fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
307                 return list;
308     }
309         
310     while ((dirp = readdir(dp)) != NULL) {
311                 if (BLI_testextensie(dirp->d_name, ".blend")) {
312                         value = PyString_FromString(dirp->d_name);
313                         PyList_Append(list, value);
314                         Py_DECREF(value);
315                 }
316     }
317         
318     closedir(dp);
319     return list;
320 }
321
322 static STR_String gPyGetCurrentScene_doc =  
323 "getCurrentScene()\n"
324 "Gets a reference to the current scene.\n";
325 static PyObject* gPyGetCurrentScene(PyObject* self)
326 {
327         Py_INCREF(gp_KetsjiScene);
328         return (PyObject*) gp_KetsjiScene;
329 }
330
331 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
332 {
333 #define pprint(x) std::cout << x << std::endl;
334         bool count=0;
335         bool support=0;
336         pprint("Supported Extensions...");
337         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
338         count = 1;
339
340         support= GLEW_ARB_vertex_shader;
341         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
342         count = 1;
343         if(support){
344                 pprint(" ----------Details----------");
345                 int max=0;
346                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
347                 pprint("  Max uniform components." << max);
348
349                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
350                 pprint("  Max varying floats." << max);
351
352                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
353                 pprint("  Max vertex texture units." << max);
354         
355                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
356                 pprint("  Max combined texture units." << max);
357                 pprint("");
358         }
359
360         support=GLEW_ARB_fragment_shader;
361         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
362         count = 1;
363         if(support){
364                 pprint(" ----------Details----------");
365                 int max=0;
366                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
367                 pprint("  Max uniform components." << max);
368                 pprint("");
369         }
370
371         support = GLEW_ARB_texture_cube_map;
372         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
373         count = 1;
374         if(support){
375                 pprint(" ----------Details----------");
376                 int size=0;
377                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
378                 pprint("  Max cubemap size." << size);
379                 pprint("");
380         }
381
382         support = GLEW_ARB_multitexture;
383         count = 1;
384         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
385         if(support){
386                 pprint(" ----------Details----------");
387                 int units=0;
388                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
389                 pprint("  Max texture units available.  " << units);
390                 pprint("");
391         }
392
393         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
394         count = 1;
395
396         if(!count)
397                 pprint("No extenstions are used in this build");
398
399         Py_RETURN_NONE;
400 }
401
402
403 static struct PyMethodDef game_methods[] = {
404         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (PY_METHODCHAR)gPyExpandPath_doc},
405         {"getCurrentController",
406         (PyCFunction) SCA_PythonController::sPyGetCurrentController,
407         METH_NOARGS, (PY_METHODCHAR)SCA_PythonController::sPyGetCurrentController__doc__},
408         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene,
409         METH_NOARGS, (PY_METHODCHAR)gPyGetCurrentScene_doc.Ptr()},
410         {"addActiveActuator",(PyCFunction) SCA_PythonController::sPyAddActiveActuator,
411         METH_VARARGS, (PY_METHODCHAR)SCA_PythonController::sPyAddActiveActuator__doc__},
412         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat,
413         METH_NOARGS, (PY_METHODCHAR)gPyGetRandomFloat_doc.Ptr()},
414         {"setGravity",(PyCFunction) gPySetGravity, METH_VARARGS, (PY_METHODCHAR)"set Gravitation"},
415         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (PY_METHODCHAR)"get audio spectrum"},
416         {"stopDSP",(PyCFunction) gPyStopDSP, METH_VARARGS, (PY_METHODCHAR)"stop using the audio dsp (for performance reasons)"},
417         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the logic tic rate"},
418         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the logic tic rate"},
419         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (PY_METHODCHAR)"Gets the physics tic rate"},
420         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (PY_METHODCHAR)"Sets the physics tic rate"},
421         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (PY_METHODCHAR)"Gets the estimated average frame rate"},
422         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (PY_METHODCHAR)"Gets a list of blend files in the same directory as the current blend file"},
423         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (PY_METHODCHAR)"Prints GL Extension Info"},
424         {NULL, (PyCFunction) NULL, 0, NULL }
425 };
426
427
428 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
429 {
430         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetHeight() : 0));
431 }
432
433
434
435 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
436 {
437         return PyInt_FromLong((gp_Canvas ? gp_Canvas->GetWidth() : 0));
438 }
439
440
441
442 // temporarility visibility thing, will be moved to rasterizer/renderer later
443 bool gUseVisibilityTemp = false;
444
445 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
446 {
447         int visible;
448         if (!PyArg_ParseTuple(args,"i",&visible))
449                 return NULL;
450         
451         gUseVisibilityTemp = (visible != 0);
452         Py_RETURN_NONE;
453 }
454
455
456
457 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
458 {
459         int visible;
460         if (!PyArg_ParseTuple(args,"i",&visible))
461                 return NULL;
462         
463         if (visible)
464         {
465                 if (gp_Canvas)
466                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
467         } else
468         {
469                 if (gp_Canvas)
470                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
471         }
472         
473         Py_RETURN_NONE;
474 }
475
476
477
478 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
479 {
480         int x,y;
481         if (!PyArg_ParseTuple(args,"ii",&x,&y))
482                 return NULL;
483         
484         if (gp_Canvas)
485                 gp_Canvas->SetMousePosition(x,y);
486         
487         Py_RETURN_NONE;
488 }
489
490 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
491 {
492         float sep;
493         if (!PyArg_ParseTuple(args, "f", &sep))
494                 return NULL;
495
496         if (!gp_Rasterizer) {
497                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
498                 return NULL;
499         }
500         
501         gp_Rasterizer->SetEyeSeparation(sep);
502         
503         Py_RETURN_NONE;
504 }
505
506 static PyObject* gPyGetEyeSeparation(PyObject*, PyObject*, PyObject*)
507 {
508         if (!gp_Rasterizer) {
509                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
510                 return NULL;
511         }
512         
513         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
514 }
515
516 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
517 {
518         float focus;
519         if (!PyArg_ParseTuple(args, "f", &focus))
520                 return NULL;
521         
522         if (!gp_Rasterizer) {
523                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
524                 return NULL;
525         }
526
527         gp_Rasterizer->SetFocalLength(focus);
528         
529         Py_RETURN_NONE;
530 }
531
532 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
533 {
534         if (!gp_Rasterizer) {
535                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
536                 return NULL;
537         }
538         
539         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
540         
541         Py_RETURN_NONE;
542 }
543
544 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* args)
545 {
546         
547         MT_Vector4 vec = MT_Vector4(0., 0., 0.3, 0.);
548         if (!PyVecArgTo(args, vec))
549                 return NULL;
550         
551         if (gp_Canvas)
552         {
553                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
554         }
555         Py_RETURN_NONE;
556 }
557
558
559
560 static PyObject* gPySetMistColor(PyObject*, PyObject* args)
561 {
562         
563         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
564         if (!PyVecArgTo(args, vec))
565                 return NULL;
566         
567         if (!gp_Rasterizer) {
568                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
569                 return NULL;
570         }       
571         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
572         
573         Py_RETURN_NONE;
574 }
575
576
577
578 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
579 {
580
581         float miststart;
582         if (!PyArg_ParseTuple(args,"f",&miststart))
583                 return NULL;
584         
585         if (!gp_Rasterizer) {
586                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
587                 return NULL;
588         }
589         
590         gp_Rasterizer->SetFogStart(miststart);
591         
592         Py_RETURN_NONE;
593 }
594
595
596
597 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
598 {
599
600         float mistend;
601         if (!PyArg_ParseTuple(args,"f",&mistend))
602                 return NULL;
603         
604         if (!gp_Rasterizer) {
605                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
606                 return NULL;
607         }
608         
609         gp_Rasterizer->SetFogEnd(mistend);
610         
611         Py_RETURN_NONE;
612 }
613
614
615 static PyObject* gPySetAmbientColor(PyObject*, PyObject* args)
616 {
617         
618         MT_Vector3 vec = MT_Vector3(0., 0., 0.);
619         if (!PyVecArgTo(args, vec))
620                 return NULL;
621         
622         if (!gp_Rasterizer) {
623                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
624                 return NULL;
625         }       
626         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
627         
628         Py_RETURN_NONE;
629 }
630
631
632
633
634 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
635 {
636         char* filename;
637         if (!PyArg_ParseTuple(args,"s",&filename))
638                 return NULL;
639         
640         if (gp_Canvas)
641         {
642                 gp_Canvas->MakeScreenShot(filename);
643         }
644         
645         Py_RETURN_NONE;
646 }
647
648 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
649 {
650         float motionblurvalue;
651         if (!PyArg_ParseTuple(args,"f",&motionblurvalue))
652                 return NULL;
653         
654         if (!gp_Rasterizer) {
655                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
656                 return NULL;
657         }
658         
659         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
660         
661         Py_RETURN_NONE;
662 }
663
664 static PyObject* gPyDisableMotionBlur(PyObject*, PyObject* args)
665 {
666         if (!gp_Rasterizer) {
667                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
668                 return NULL;
669         }
670         
671         gp_Rasterizer->DisableMotionBlur();
672         
673         Py_RETURN_NONE;
674 }
675
676 int getGLSLSettingFlag(char *setting)
677 {
678         if(strcmp(setting, "lights") == 0)
679                 return G_FILE_GLSL_NO_LIGHTS;
680         else if(strcmp(setting, "shaders") == 0)
681                 return G_FILE_GLSL_NO_SHADERS;
682         else if(strcmp(setting, "shadows") == 0)
683                 return G_FILE_GLSL_NO_SHADOWS;
684         else if(strcmp(setting, "ramps") == 0)
685                 return G_FILE_GLSL_NO_RAMPS;
686         else if(strcmp(setting, "nodes") == 0)
687                 return G_FILE_GLSL_NO_NODES;
688         else if(strcmp(setting, "extra_textures") == 0)
689                 return G_FILE_GLSL_NO_EXTRA_TEX;
690         else
691                 return -1;
692 }
693
694 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
695                                                                                         PyObject* args,
696                                                                                         PyObject*)
697 {
698         char *setting;
699         int enable, flag, fileflags;
700
701         if (!PyArg_ParseTuple(args,"si",&setting,&enable))
702                 return NULL;
703         
704         flag = getGLSLSettingFlag(setting);
705         
706         if  (flag==-1) {
707                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
708                 return NULL;
709         }
710
711         fileflags = G.fileflags;
712         
713         if (enable)
714                 G.fileflags &= ~flag;
715         else
716                 G.fileflags |= flag;
717
718         /* display lists and GLSL materials need to be remade */
719         if(G.fileflags != fileflags) {
720                 if(gp_KetsjiEngine) {
721                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
722                         KX_SceneList::iterator it;
723
724                         for(it=scenes->begin(); it!=scenes->end(); it++)
725                                 if((*it)->GetBucketManager())
726                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
727                 }
728
729                 GPU_materials_free();
730         }
731
732         Py_RETURN_NONE;
733 }
734
735 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
736                                                                          PyObject* args, 
737                                                                          PyObject*)
738 {
739         char *setting;
740         int enabled = 0, flag;
741
742         if (!PyArg_ParseTuple(args,"s",&setting))
743                 return NULL;
744         
745         flag = getGLSLSettingFlag(setting);
746         
747         if  (flag==-1) {
748                 PyErr_SetString(PyExc_ValueError, "glsl setting is not known");
749                 return NULL;
750         }
751
752         enabled = ((G.fileflags & flag) != 0);
753         return PyInt_FromLong(enabled);
754 }
755
756 #define KX_TEXFACE_MATERIAL                             0
757 #define KX_BLENDER_MULTITEX_MATERIAL    1
758 #define KX_BLENDER_GLSL_MATERIAL                2
759
760 static PyObject* gPySetMaterialType(PyObject*,
761                                                                         PyObject* args,
762                                                                         PyObject*)
763 {
764         int flag, type;
765
766         if (!PyArg_ParseTuple(args,"i",&type))
767                 return NULL;
768
769         if(type == KX_BLENDER_GLSL_MATERIAL)
770                 flag = G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL;
771         else if(type == KX_BLENDER_MULTITEX_MATERIAL)
772                 flag = G_FILE_GAME_MAT;
773         else if(type == KX_TEXFACE_MATERIAL)
774                 flag = 0;
775         else {
776                 PyErr_SetString(PyExc_ValueError, "material type is not known");
777                 return NULL;
778         }
779
780         G.fileflags &= ~(G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL);
781         G.fileflags |= flag;
782
783         Py_RETURN_NONE;
784 }
785
786 static PyObject* gPyGetMaterialType(PyObject*)
787 {
788         int flag;
789
790         if(G.fileflags & (G_FILE_GAME_MAT|G_FILE_GAME_MAT_GLSL))
791                 flag = KX_BLENDER_GLSL_MATERIAL;
792         else if(G.fileflags & G_FILE_GAME_MAT)
793                 flag = KX_BLENDER_MULTITEX_MATERIAL;
794         else
795                 flag = KX_TEXFACE_MATERIAL;
796         
797         return PyInt_FromLong(flag);
798 }
799
800 static PyObject* gPyDrawLine(PyObject*, PyObject* args)
801 {
802         PyObject* ob_from;
803         PyObject* ob_to;
804         PyObject* ob_color;
805
806         if (!gp_Rasterizer) {
807                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer not available");
808                 return NULL;
809         }
810
811         if (!PyArg_ParseTuple(args,"OOO",&ob_from,&ob_to,&ob_color))
812                 return NULL;
813
814         MT_Vector3 from(0., 0., 0.);
815         MT_Vector3 to(0., 0., 0.);
816         MT_Vector3 color(0., 0., 0.);
817         if (!PyVecTo(ob_from, from))
818                 return NULL;
819         if (!PyVecTo(ob_to, to))
820                 return NULL;
821         if (!PyVecTo(ob_color, color))
822                 return NULL;
823
824         gp_Rasterizer->DrawDebugLine(from,to,color);
825         
826         Py_RETURN_NONE;
827 }
828
829 static struct PyMethodDef rasterizer_methods[] = {
830   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
831    METH_VARARGS, "getWindowWidth doc"},
832    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
833    METH_VARARGS, "getWindowHeight doc"},
834   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
835         METH_VARARGS, "make Screenshot doc"},
836    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
837    METH_VARARGS, "enableVisibility doc"},
838         {"showMouse",(PyCFunction) gPyShowMouse,
839    METH_VARARGS, "showMouse(bool visible)"},
840    {"setMousePosition",(PyCFunction) gPySetMousePosition,
841    METH_VARARGS, "setMousePosition(int x,int y)"},
842   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_VARARGS,"set Background Color (rgb)"},
843         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_VARARGS,"set Ambient Color (rgb)"},
844  {"setMistColor",(PyCFunction)gPySetMistColor,METH_VARARGS,"set Mist Color (rgb)"},
845   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
846   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
847   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
848   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_VARARGS,"disable motion blur"},
849
850   
851   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
852   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_VARARGS, "get the eye separation for stereo mode"},
853   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
854   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
855   {"setMaterialMode",(PyCFunction) gPySetMaterialType,
856    METH_VARARGS, "set the material mode to use for OpenGL rendering"},
857   {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
858    METH_NOARGS, "get the material mode being used for OpenGL rendering"},
859   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
860    METH_VARARGS, "set the state of a GLSL material setting"},
861   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
862    METH_VARARGS, "get the state of a GLSL material setting"},
863   {"drawLine", (PyCFunction) gPyDrawLine,
864    METH_VARARGS, "draw a line on the screen"},
865   { NULL, (PyCFunction) NULL, 0, NULL }
866 };
867
868 // Initialization function for the module (*must* be called initGameLogic)
869
870 static char GameLogic_module_documentation[] =
871 "This is the Python API for the game engine of GameLogic"
872 ;
873
874 static char Rasterizer_module_documentation[] =
875 "This is the Python API for the game engine of Rasterizer"
876 ;
877
878
879
880 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
881 {
882         PyObject* m;
883         PyObject* d;
884
885         gp_KetsjiEngine = engine;
886         gp_KetsjiScene = scene;
887
888         gUseVisibilityTemp=false;
889
890         // Create the module and add the functions
891         m = Py_InitModule4("GameLogic", game_methods,
892                                            GameLogic_module_documentation,
893                                            (PyObject*)NULL,PYTHON_API_VERSION);
894
895         // Add some symbolic constants to the module
896         d = PyModule_GetDict(m);
897         
898         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
899         // for now its safe to make sure it exists for other areas such as the web plugin
900         PyDict_SetItemString(d, "globalDict", PyDict_New());
901
902         ErrorObject = PyString_FromString("GameLogic.error");
903         PyDict_SetItemString(d, "error", ErrorObject);
904         
905         // XXXX Add constants here
906         /* To use logic bricks, we need some sort of constants. Here, we associate */
907         /* constants and sumbolic names. Add them to dictionary d.                 */
908
909         /* 1. true and false: needed for everyone                                  */
910         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
911         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
912
913         /* 2. Property sensor                                                      */
914         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
915         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
916         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
917         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
918         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
919
920         /* 3. Constraint actuator                                                  */
921         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
922         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
923         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
924         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
925         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
926         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
927         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
928         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
929         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
930         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
931         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
932         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
933         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
934         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
935         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
936
937         /* 4. Ipo actuator, simple part                                            */
938         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
939         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
940         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
941         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
942         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
943
944         /* 5. Random distribution types                                            */
945         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
946         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
947         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
948         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
949         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
950         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
951         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
952         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
953         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
954         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
955
956         /* 6. Sound actuator                                                      */
957         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
958         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
959         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
960         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
961         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
962         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
963
964         /* 7. Action actuator                                                                                                      */
965         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,     BL_ActionActuator::KX_ACT_ACTION_PLAY);
966         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     BL_ActionActuator::KX_ACT_ACTION_FLIPPER);
967         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,     BL_ActionActuator::KX_ACT_ACTION_LOOPSTOP);
968         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     BL_ActionActuator::KX_ACT_ACTION_LOOPEND);
969         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,     BL_ActionActuator::KX_ACT_ACTION_PROPERTY);
970         
971         /*8. GL_BlendFunc */
972         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
973         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
974         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
975         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
976         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
977         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
978         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
979         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
980         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
981         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
982         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
983
984
985         /* 9. UniformTypes */
986         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
987         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
988         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
989         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
990         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
991         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
992         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
993         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
994         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
995         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
996         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
997         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
998         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
999         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1000         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1001
1002         /* 10 state actuator */
1003         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1004         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1005         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1006         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1007         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1008         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1009         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1010         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1011         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1012         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1013         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1014         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1015         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1016         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1017         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1018         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1019         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1020         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1021         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1022         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1023         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1024         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1025         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1026         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1027         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1028         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1029         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1030         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1031         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1032         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1033
1034         // Check for errors
1035         if (PyErr_Occurred())
1036     {
1037                 Py_FatalError("can't initialize module GameLogic");
1038     }
1039
1040         return m;
1041 }
1042
1043 // Python Sandbox code
1044 // override builtin functions import() and open()
1045
1046
1047 PyObject *KXpy_open(PyObject *self, PyObject *args) {
1048         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
1049         return NULL;
1050 }
1051
1052 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
1053         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
1054         return NULL;
1055 }
1056
1057 PyObject *KXpy_file(PyObject *self, PyObject *args) {
1058         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
1059         return NULL;
1060 }
1061
1062 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
1063         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
1064         return NULL;
1065 }
1066
1067 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
1068         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
1069         return NULL;
1070 }
1071
1072 PyObject *KXpy_import(PyObject *self, PyObject *args)
1073 {
1074         char *name;
1075         PyObject *globals = NULL;
1076         PyObject *locals = NULL;
1077         PyObject *fromlist = NULL;
1078         PyObject *l, *m, *n;
1079
1080         if (!PyArg_ParseTuple(args, "s|OOO:m_import",
1081                 &name, &globals, &locals, &fromlist))
1082             return NULL;
1083
1084         /* check for builtin modules */
1085         m = PyImport_AddModule("sys");
1086         l = PyObject_GetAttrString(m, "builtin_module_names");
1087         n = PyString_FromString(name);
1088         
1089         if (PySequence_Contains(l, n)) {
1090                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1091         }
1092
1093         /* quick hack for GamePython modules 
1094                 TODO: register builtin modules properly by ExtendInittab */
1095         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
1096                 !strcmp(name, "Rasterizer") || !strcmp(name, "Mathutils")) {
1097                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1098         }
1099                 
1100         PyErr_Format(PyExc_ImportError,
1101                  "Import of external Module %.20s not allowed.", name);
1102         return NULL;
1103
1104 }
1105
1106 /* override python file type functions */
1107 #if 0
1108 static int
1109 file_init(PyObject *self, PyObject *args, PyObject *kwds)
1110 {
1111         KXpy_file(NULL, NULL);
1112         return -1;
1113 }
1114
1115 static PyObject *
1116 file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1117 {
1118         return KXpy_file(NULL, NULL);
1119 }
1120 #endif
1121
1122 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
1123 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
1124 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
1125 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
1126 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1127
1128 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1129
1130 //static PyObject *g_oldopen = 0;
1131 //static PyObject *g_oldimport = 0;
1132 //static int g_security = 0;
1133
1134 void setSandbox(TPythonSecurityLevel level)
1135 {
1136     PyObject *m = PyImport_AddModule("__builtin__");
1137     PyObject *d = PyModule_GetDict(m);
1138
1139         switch (level) {
1140         case psl_Highest:
1141                 //if (!g_security) {
1142                         //g_oldopen = PyDict_GetItemString(d, "open");
1143         
1144                         // functions we cant trust
1145                         PyDict_SetItemString(d, "open", PyCFunction_New(meth_open, NULL));
1146                         PyDict_SetItemString(d, "reload", PyCFunction_New(meth_reload, NULL));
1147                         PyDict_SetItemString(d, "file", PyCFunction_New(meth_file, NULL));
1148                         PyDict_SetItemString(d, "execfile", PyCFunction_New(meth_execfile, NULL));
1149                         PyDict_SetItemString(d, "compile", PyCFunction_New(meth_compile, NULL));
1150                         
1151                         // our own import
1152                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1153                         //g_security = level;
1154                         
1155                         // Overiding file dosnt stop it being accessed if your sneaky
1156                         //    f =  [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
1157                         //    f.write('...')
1158                         // so overwrite the file types functions. be very careful here still, since python uses python.
1159                         // ps - python devs frown deeply upon this.
1160         
1161                         /* this could mess up pythons internals, if we are serious about sandboxing
1162                          * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
1163 #if 0
1164                         PyFile_Type.tp_init = file_init;
1165                         PyFile_Type.tp_new = file_new;
1166 #endif
1167                 //}
1168                 break;
1169         /*
1170         case psl_Lowest:
1171                 if (g_security) {
1172                         PyDict_SetItemString(d, "open", g_oldopen);
1173                         PyDict_SetItemString(d, "__import__", g_oldimport);
1174                         g_security = level;
1175                 }
1176         */
1177         default:
1178                 break;
1179         }
1180 }
1181
1182 /**
1183  * Python is not initialised.
1184  */
1185 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1186 {
1187         STR_String pname = progname;
1188         Py_SetProgramName(pname.Ptr());
1189         Py_NoSiteFlag=1;
1190         Py_FrozenFlag=1;
1191         Py_Initialize();
1192
1193         //importBlenderModules()
1194         
1195         setSandbox(level);
1196
1197         PyObject* moduleobj = PyImport_AddModule("__main__");
1198         return PyModule_GetDict(moduleobj);
1199 }
1200
1201 void exitGamePlayerPythonScripting()
1202 {
1203         Py_Finalize();
1204 }
1205
1206 /**
1207  * Python is already initialized.
1208  */
1209 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level)
1210 {
1211         STR_String pname = progname;
1212         Py_SetProgramName(pname.Ptr());
1213         Py_NoSiteFlag=1;
1214         Py_FrozenFlag=1;
1215
1216         setSandbox(level);
1217
1218         PyObject* moduleobj = PyImport_AddModule("__main__");
1219         return PyModule_GetDict(moduleobj);
1220 }
1221
1222
1223
1224 void exitGamePythonScripting()
1225 {
1226 }
1227
1228
1229
1230 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
1231 {
1232         gp_Canvas = canvas;
1233         gp_Rasterizer = rasty;
1234
1235
1236   PyObject* m;
1237   PyObject* d;
1238
1239   // Create the module and add the functions
1240   m = Py_InitModule4("Rasterizer", rasterizer_methods,
1241                      Rasterizer_module_documentation,
1242                      (PyObject*)NULL,PYTHON_API_VERSION);
1243
1244   // Add some symbolic constants to the module
1245   d = PyModule_GetDict(m);
1246   ErrorObject = PyString_FromString("Rasterizer.error");
1247   PyDict_SetItemString(d, "error", ErrorObject);
1248
1249   /* needed for get/setMaterialType */
1250   KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
1251   KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
1252   KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
1253
1254   // XXXX Add constants here
1255
1256   // Check for errors
1257   if (PyErr_Occurred())
1258     {
1259       Py_FatalError("can't initialize module Rasterizer");
1260     }
1261
1262   return d;
1263 }
1264
1265
1266
1267 /* ------------------------------------------------------------------------- */
1268 /* GameKeys: symbolic constants for key mapping                              */
1269 /* ------------------------------------------------------------------------- */
1270
1271 static char GameKeys_module_documentation[] =
1272 "This modules provides defines for key-codes"
1273 ;
1274
1275 static char gPyEventToString_doc[] =
1276 "Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
1277 ;
1278
1279 static PyObject* gPyEventToString(PyObject*, PyObject* value)
1280 {
1281         PyObject* mod, *dict, *key, *val, *ret = NULL;
1282         Py_ssize_t pos = 0;
1283         
1284         mod = PyImport_ImportModule( "GameKeys" );
1285         if (!mod)
1286                 return NULL;
1287         
1288         dict = PyModule_GetDict(mod);
1289         
1290         while (PyDict_Next(dict, &pos, &key, &val)) {
1291                 if (PyObject_Compare(value, val)==0) {
1292                         ret = key;
1293                         break;
1294                 }
1295         }
1296         
1297         PyErr_Clear(); // incase there was an error clearing
1298         Py_DECREF(mod);
1299         if (!ret)       PyErr_SetString(PyExc_ValueError, "expected a valid int keyboard event");
1300         else            Py_INCREF(ret);
1301         
1302         return ret;
1303 }
1304
1305 static struct PyMethodDef gamekeys_methods[] = {
1306         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (PY_METHODCHAR)gPyEventToString_doc},
1307         { NULL, (PyCFunction) NULL, 0, NULL }
1308 };
1309
1310
1311
1312 PyObject* initGameKeys()
1313 {
1314         PyObject* m;
1315         PyObject* d;
1316
1317         // Create the module and add the functions
1318         m = Py_InitModule4("GameKeys", gamekeys_methods,
1319                                            GameKeys_module_documentation,
1320                                            (PyObject*)NULL,PYTHON_API_VERSION);
1321
1322         // Add some symbolic constants to the module
1323         d = PyModule_GetDict(m);
1324
1325         // XXXX Add constants here
1326
1327         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
1328         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
1329         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
1330         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
1331         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
1332         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
1333         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
1334         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
1335         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
1336         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
1337         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
1338         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
1339         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
1340         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
1341         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
1342         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
1343         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
1344         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
1345         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
1346         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
1347         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
1348         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
1349         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
1350         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
1351         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
1352         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
1353         
1354         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
1355         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
1356         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
1357         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
1358         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
1359         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
1360         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
1361         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
1362         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
1363         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
1364                 
1365         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
1366                 
1367         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
1368         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
1369         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
1370         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
1371         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
1372         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
1373                 
1374         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
1375         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
1376         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
1377         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
1378         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
1379         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
1380         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
1381         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
1382         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
1383         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
1384         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
1385         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
1386         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
1387         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
1388         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
1389         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
1390         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
1391         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
1392                 
1393         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
1394         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
1395         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
1396         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
1397         
1398         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
1399         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
1400         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
1401         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
1402                 
1403         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
1404         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
1405         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
1406         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
1407         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
1408                 
1409         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
1410         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
1411         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
1412                 
1413                 
1414         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
1415         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
1416         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
1417         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
1418                 
1419                 
1420         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
1421         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
1422         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
1423         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
1424         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
1425         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
1426         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
1427         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
1428         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
1429         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
1430         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
1431         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
1432                 
1433         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
1434         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
1435         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
1436         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
1437         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
1438         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
1439
1440
1441         // Check for errors
1442         if (PyErr_Occurred())
1443     {
1444                 Py_FatalError("can't initialize module GameKeys");
1445     }
1446
1447         return d;
1448 }
1449
1450 PyObject* initMathutils()
1451 {
1452         return Mathutils_Init("Mathutils"); // Use as a top level module in BGE
1453 }
1454
1455 void PHY_SetActiveScene(class KX_Scene* scene)
1456 {
1457         gp_KetsjiScene = scene;
1458 }
1459
1460 class KX_Scene* PHY_GetActiveScene()
1461 {
1462         return gp_KetsjiScene;
1463 }
1464
1465 // utility function for loading and saving the globalDict
1466 int saveGamePythonConfig( char **marshal_buffer)
1467 {
1468         int marshal_length = 0;
1469         PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1470         if (gameLogic) {
1471                 PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
1472                 if (pyGlobalDict) {
1473 #ifdef Py_MARSHAL_VERSION       
1474                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
1475 #else
1476                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict ); 
1477 #endif
1478                         if (pyGlobalDictMarshal) {
1479                                 // for testing only
1480                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
1481
1482                                 marshal_length= PyString_Size(pyGlobalDictMarshal);
1483                                 *marshal_buffer = new char[marshal_length + 1];
1484                                 memcpy(*marshal_buffer, PyString_AsString(pyGlobalDictMarshal), marshal_length);
1485
1486                                 Py_DECREF(pyGlobalDictMarshal);
1487                         } else {
1488                                 printf("Error, GameLogic.globalDict could not be marshal'd\n");
1489                         }
1490                 } else {
1491                         printf("Error, GameLogic.globalDict was removed\n");
1492                 }
1493                 Py_DECREF(gameLogic);
1494         } else {
1495                 printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1496         }
1497         return marshal_length;
1498 }
1499
1500 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
1501 {
1502         /* Restore the dict */
1503         if (marshal_buffer) {
1504                 PyObject* gameLogic = PyImport_ImportModule("GameLogic");
1505
1506                 if (gameLogic) {
1507                         PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
1508                         if (pyGlobalDict) {
1509                                 PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
1510                                 if (pyGlobalDict_orig) {
1511                                         PyDict_Clear(pyGlobalDict_orig);
1512                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
1513                                 } else {
1514                                         /* this should not happen, but cant find the original globalDict, just assign it then */
1515                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
1516                                 }
1517                                 Py_DECREF(gameLogic);
1518                                 Py_DECREF(pyGlobalDict);
1519                                 return 1;
1520                         } else {
1521                                 Py_DECREF(gameLogic);
1522                                 PyErr_Clear();
1523                                 printf("Error could not marshall string\n");
1524                         }
1525                 } else {
1526                         printf("Error, GameLogic failed to import GameLogic.globalDict will be lost\n");
1527                 }       
1528         }
1529         return 0;
1530 }
1531
1532 void pathGamePythonConfig( char *path )
1533 {
1534         int len = strlen(G.sce);
1535         
1536         strncpy(path, G.sce, sizeof(G.sce));
1537         /* replace extension */
1538         if (BLI_testextensie(path, ".blend")) {
1539                 strcpy(path+(len-6), ".bgeconf");
1540         } else {
1541                 strcpy(path+len, ".bgeconf");
1542         }
1543 }