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