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