doxygen: prevent GPL license block from being parsed as doxygen comment.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 #if defined(WIN32) && !defined(FREE_WINDOWS)
34 #pragma warning (disable : 4786)
35 #endif //WIN32
36
37 #ifdef WITH_PYTHON
38
39 #ifdef _POSIX_C_SOURCE
40 #undef _POSIX_C_SOURCE
41 #endif
42
43 #ifdef _XOPEN_SOURCE
44 #undef _XOPEN_SOURCE
45 #endif
46
47 #include <Python.h>
48
49 extern "C" {
50         #include "bpy_internal_import.h"  /* from the blender python api, but we want to import text too! */
51         #include "py_capi_utils.h"
52         #include "mathutils.h" // Blender.Mathutils module copied here so the blenderlayer can use.
53         #include "bgl.h"
54         #include "blf_py_api.h"
55
56         #include "marshal.h" /* python header for loading/saving dicts */
57 }
58
59 #include "AUD_PyInit.h"
60
61 #endif
62
63 #include "KX_PythonInit.h"
64
65 // directory header for py function getBlendFileList
66 #ifndef WIN32
67   #include <dirent.h>
68   #include <stdlib.h>
69 #else
70   #include <io.h>
71   #include "BLI_winstuff.h"
72 #endif
73
74 //python physics binding
75 #include "KX_PyConstraintBinding.h"
76
77 #include "KX_KetsjiEngine.h"
78 #include "KX_RadarSensor.h"
79 #include "KX_RaySensor.h"
80 #include "KX_ArmatureSensor.h"
81 #include "KX_SceneActuator.h"
82 #include "KX_GameActuator.h"
83 #include "KX_ParentActuator.h"
84 #include "KX_SCA_DynamicActuator.h"
85
86 #include "SCA_IInputDevice.h"
87 #include "SCA_PropertySensor.h"
88 #include "SCA_RandomActuator.h"
89 #include "SCA_KeyboardSensor.h" /* IsPrintable, ToCharacter */
90 #include "SCA_PythonKeyboard.h"
91 #include "SCA_PythonMouse.h"
92 #include "KX_ConstraintActuator.h"
93 #include "KX_IpoActuator.h"
94 #include "KX_SoundActuator.h"
95 #include "KX_StateActuator.h"
96 #include "BL_ActionActuator.h"
97 #include "BL_ArmatureObject.h"
98 #include "RAS_IRasterizer.h"
99 #include "RAS_ICanvas.h"
100 #include "RAS_BucketManager.h"
101 #include "RAS_2DFilterManager.h"
102 #include "MT_Vector3.h"
103 #include "MT_Point3.h"
104 #include "ListValue.h"
105 #include "InputParser.h"
106 #include "KX_Scene.h"
107
108 #include "NG_NetworkScene.h" //Needed for sendMessage()
109
110 #include "BL_Shader.h"
111
112 #include "KX_PyMath.h"
113
114 #include "PyObjectPlus.h"
115
116 #include "KX_PythonInitTypes.h" 
117
118 /* we only need this to get a list of libraries from the main struct */
119 #include "DNA_ID.h"
120 #include "DNA_scene_types.h"
121
122 #include "PHY_IPhysicsEnvironment.h"
123 #include "BKE_main.h"
124 #include "BKE_utildefines.h"
125 #include "BKE_global.h"
126 #include "BLI_blenlib.h"
127 #include "GPU_material.h"
128 #include "MEM_guardedalloc.h"
129
130 /* for converting new scenes */
131 #include "KX_BlenderSceneConverter.h"
132 #include "KX_MeshProxy.h" /* for creating a new library of mesh objects */
133 extern "C" {
134         #include "BKE_idcode.h"
135 }
136
137 #include "NG_NetworkScene.h" //Needed for sendMessage()
138
139 // 'local' copy of canvas ptr, for window height/width python scripts
140
141 #ifdef WITH_PYTHON
142
143 static RAS_ICanvas* gp_Canvas = NULL;
144 static char gp_GamePythonPath[FILE_MAXDIR + FILE_MAXFILE] = "";
145 static char gp_GamePythonPathOrig[FILE_MAXDIR + FILE_MAXFILE] = ""; // not super happy about this, but we need to remember the first loaded file for the global/dict load save
146
147 static SCA_PythonKeyboard* gp_PythonKeyboard = NULL;
148 static SCA_PythonMouse* gp_PythonMouse = NULL;
149 #endif // WITH_PYTHON
150
151 static KX_Scene*        gp_KetsjiScene = NULL;
152 static KX_KetsjiEngine* gp_KetsjiEngine = NULL;
153 static RAS_IRasterizer* gp_Rasterizer = NULL;
154
155
156 void KX_SetActiveScene(class KX_Scene* scene)
157 {
158         gp_KetsjiScene = scene;
159 }
160
161 class KX_Scene* KX_GetActiveScene()
162 {
163         return gp_KetsjiScene;
164 }
165
166 class KX_KetsjiEngine* KX_GetActiveEngine()
167 {
168         return gp_KetsjiEngine;
169 }
170
171 /* why is this in python? */
172 void    KX_RasterizerDrawDebugLine(const MT_Vector3& from,const MT_Vector3& to,const MT_Vector3& color)
173 {
174         if (gp_Rasterizer)
175                 gp_Rasterizer->DrawDebugLine(from,to,color);
176 }
177
178 #ifdef WITH_PYTHON
179
180 static PyObject *gp_OrigPythonSysPath= NULL;
181 static PyObject *gp_OrigPythonSysModules= NULL;
182
183 /* Macro for building the keyboard translation */
184 //#define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, PyLong_FromSsize_t(SCA_IInputDevice::KX_##name))
185 #define KX_MACRO_addToDict(dict, name) PyDict_SetItemString(dict, #name, item=PyLong_FromSsize_t(name)); Py_DECREF(item)
186 /* For the defines for types from logic bricks, we do stuff explicitly... */
187 #define KX_MACRO_addTypesToDict(dict, name, name2) PyDict_SetItemString(dict, #name, item=PyLong_FromSsize_t(name2)); Py_DECREF(item)
188
189
190 // temporarily python stuff, will be put in another place later !
191 #include "KX_Python.h"
192 #include "SCA_PythonController.h"
193 // List of methods defined in the module
194
195 static PyObject* ErrorObject;
196 static const char *gPyGetRandomFloat_doc="getRandomFloat returns a random floating point value in the range [0..1]";
197
198 static PyObject* gPyGetRandomFloat(PyObject*)
199 {
200         return PyFloat_FromDouble(MT_random());
201 }
202
203 static PyObject* gPySetGravity(PyObject*, PyObject* value)
204 {
205         MT_Vector3 vec;
206         if (!PyVecTo(value, vec))
207                 return NULL;
208
209         if (gp_KetsjiScene)
210                 gp_KetsjiScene->SetGravity(vec);
211         
212         Py_RETURN_NONE;
213 }
214
215 static char gPyExpandPath_doc[] =
216 "(path) - Converts a blender internal path into a proper file system path.\n\
217 path - the string path to convert.\n\n\
218 Use / as directory separator in path\n\
219 You can use '//' at the start of the string to define a relative path;\n\
220 Blender replaces that string by the directory of the startup .blend or runtime\n\
221 file to make a full path name (doesn't change during the game, even if you load\n\
222 other .blend).\n\
223 The function also converts the directory separator to the local file system format.";
224
225 static PyObject* gPyExpandPath(PyObject*, PyObject* args)
226 {
227         char expanded[FILE_MAXDIR + FILE_MAXFILE];
228         char* filename;
229         
230         if (!PyArg_ParseTuple(args,"s:ExpandPath",&filename))
231                 return NULL;
232
233         BLI_strncpy(expanded, filename, FILE_MAXDIR + FILE_MAXFILE);
234         BLI_path_abs(expanded, gp_GamePythonPath);
235         return PyUnicode_DecodeFSDefault(expanded);
236 }
237
238 static char gPyStartGame_doc[] =
239 "startGame(blend)\n\
240 Loads the blend file";
241
242 static PyObject* gPyStartGame(PyObject*, PyObject* args)
243 {
244         char* blendfile;
245
246         if (!PyArg_ParseTuple(args, "s:startGame", &blendfile))
247                 return NULL;
248
249         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_START_OTHER_GAME);
250         gp_KetsjiEngine->SetNameNextGame(blendfile);
251
252         Py_RETURN_NONE;
253 }
254
255 static char gPyEndGame_doc[] =
256 "endGame()\n\
257 Ends the current game";
258
259 static PyObject* gPyEndGame(PyObject*)
260 {
261         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_QUIT_GAME);
262
263         //printf("%s\n", gp_GamePythonPath);
264
265         Py_RETURN_NONE;
266 }
267
268 static char gPyRestartGame_doc[] =
269 "restartGame()\n\
270 Restarts the current game by reloading the .blend file";
271
272 static PyObject* gPyRestartGame(PyObject*)
273 {
274         gp_KetsjiEngine->RequestExit(KX_EXIT_REQUEST_RESTART_GAME);
275         gp_KetsjiEngine->SetNameNextGame(gp_GamePythonPath);
276
277         Py_RETURN_NONE;
278 }
279
280 static char gPySaveGlobalDict_doc[] =
281         "saveGlobalDict()\n"
282         "Saves bge.logic.globalDict to a file";
283
284 static PyObject* gPySaveGlobalDict(PyObject*)
285 {
286         char marshal_path[512];
287         char *marshal_buffer = NULL;
288         unsigned int marshal_length;
289         FILE *fp = NULL;
290
291         pathGamePythonConfig(marshal_path);
292         marshal_length = saveGamePythonConfig(&marshal_buffer);
293
294         if (marshal_length && marshal_buffer)
295         {
296                 fp = fopen(marshal_path, "wb");
297
298                 if (fp)
299                 {
300                         if (fwrite(marshal_buffer, 1, marshal_length, fp) != marshal_length)
301                                 printf("Warning: could not write marshal data\n");
302
303                         fclose(fp);
304                 } else {
305                         printf("Warning: could not open marshal file\n");
306                 }
307         } else {
308                 printf("Warning: could not create marshal buffer\n");
309         }
310
311         if (marshal_buffer)
312                 delete [] marshal_buffer;
313
314         Py_RETURN_NONE;
315 }
316
317 static char gPyLoadGlobalDict_doc[] =
318         "LoadGlobalDict()\n"
319         "Loads bge.logic.globalDict from a file";
320
321 static PyObject* gPyLoadGlobalDict(PyObject*)
322 {
323         char marshal_path[512];
324         char *marshal_buffer = NULL;
325         unsigned int marshal_length;
326         FILE *fp = NULL;
327         int result;
328
329         pathGamePythonConfig(marshal_path);
330
331         fp = fopen(marshal_path, "rb");
332
333         if (fp) {
334                 // obtain file size:
335                 fseek (fp, 0, SEEK_END);
336                 marshal_length = ftell(fp);
337                 rewind(fp);
338
339                 marshal_buffer = (char*)malloc (sizeof(char)*marshal_length);
340
341                 result = fread(marshal_buffer, 1, marshal_length, fp);
342
343                 if (result == marshal_length) {
344                         loadGamePythonConfig(marshal_buffer, marshal_length);
345                 } else {
346                         printf("Warning: could not read all of '%s'\n", marshal_path);
347                 }
348
349                 free(marshal_buffer);
350                 fclose(fp);
351         } else {
352                 printf("Warning: could not open '%s'\n", marshal_path);
353         }
354
355         Py_RETURN_NONE;
356 }
357
358 static char gPySendMessage_doc[] = 
359 "sendMessage(subject, [body, to, from])\n\
360 sends a message in same manner as a message actuator\
361 subject = Subject of the message\
362 body = Message body\
363 to = Name of object to send the message to\
364 from = Name of object to send the string from";
365
366 static PyObject* gPySendMessage(PyObject*, PyObject* args)
367 {
368         char* subject;
369         char* body = (char *)"";
370         char* to = (char *)"";
371         char* from = (char *)"";
372
373         if (!PyArg_ParseTuple(args, "s|sss:sendMessage", &subject, &body, &to, &from))
374                 return NULL;
375
376         gp_KetsjiScene->GetNetworkScene()->SendMessage(to, from, subject, body);
377
378         Py_RETURN_NONE;
379 }
380
381 // this gets a pointer to an array filled with floats
382 static PyObject* gPyGetSpectrum(PyObject*)
383 {
384         PyObject* resultlist = PyList_New(512);
385
386         for (int index = 0; index < 512; index++)
387         {
388                 PyList_SET_ITEM(resultlist, index, PyFloat_FromDouble(0.0));
389         }
390
391         return resultlist;
392 }
393
394 static PyObject* gPySetLogicTicRate(PyObject*, PyObject* args)
395 {
396         float ticrate;
397         if (!PyArg_ParseTuple(args, "f:setLogicTicRate", &ticrate))
398                 return NULL;
399         
400         KX_KetsjiEngine::SetTicRate(ticrate);
401         Py_RETURN_NONE;
402 }
403
404 static PyObject* gPyGetLogicTicRate(PyObject*)
405 {
406         return PyFloat_FromDouble(KX_KetsjiEngine::GetTicRate());
407 }
408
409 static PyObject* gPySetMaxLogicFrame(PyObject*, PyObject* args)
410 {
411         int frame;
412         if (!PyArg_ParseTuple(args, "i:setMaxLogicFrame", &frame))
413                 return NULL;
414         
415         KX_KetsjiEngine::SetMaxLogicFrame(frame);
416         Py_RETURN_NONE;
417 }
418
419 static PyObject* gPyGetMaxLogicFrame(PyObject*)
420 {
421         return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxLogicFrame());
422 }
423
424 static PyObject* gPySetMaxPhysicsFrame(PyObject*, PyObject* args)
425 {
426         int frame;
427         if (!PyArg_ParseTuple(args, "i:setMaxPhysicsFrame", &frame))
428                 return NULL;
429         
430         KX_KetsjiEngine::SetMaxPhysicsFrame(frame);
431         Py_RETURN_NONE;
432 }
433
434 static PyObject* gPyGetMaxPhysicsFrame(PyObject*)
435 {
436         return PyLong_FromSsize_t(KX_KetsjiEngine::GetMaxPhysicsFrame());
437 }
438
439 static PyObject* gPySetPhysicsTicRate(PyObject*, PyObject* args)
440 {
441         float ticrate;
442         if (!PyArg_ParseTuple(args, "f:setPhysicsTicRate", &ticrate))
443                 return NULL;
444         
445         PHY_GetActiveEnvironment()->setFixedTimeStep(true,ticrate);
446         Py_RETURN_NONE;
447 }
448 #if 0 // unused
449 static PyObject* gPySetPhysicsDebug(PyObject*, PyObject* args)
450 {
451         int debugMode;
452         if (!PyArg_ParseTuple(args, "i:setPhysicsDebug", &debugMode))
453                 return NULL;
454         
455         PHY_GetActiveEnvironment()->setDebugMode(debugMode);
456         Py_RETURN_NONE;
457 }
458 #endif
459
460
461 static PyObject* gPyGetPhysicsTicRate(PyObject*)
462 {
463         return PyFloat_FromDouble(PHY_GetActiveEnvironment()->getFixedTimeStep());
464 }
465
466 static PyObject* gPyGetAverageFrameRate(PyObject*)
467 {
468         return PyFloat_FromDouble(KX_KetsjiEngine::GetAverageFrameRate());
469 }
470
471 static PyObject* gPyGetBlendFileList(PyObject*, PyObject* args)
472 {
473         char cpath[sizeof(gp_GamePythonPath)];
474         char *searchpath = NULL;
475         PyObject* list, *value;
476         
477     DIR *dp;
478     struct dirent *dirp;
479         
480         if (!PyArg_ParseTuple(args, "|s:getBlendFileList", &searchpath))
481                 return NULL;
482         
483         list = PyList_New(0);
484         
485         if (searchpath) {
486                 BLI_strncpy(cpath, searchpath, FILE_MAXDIR + FILE_MAXFILE);
487                 BLI_path_abs(cpath, gp_GamePythonPath);
488         } else {
489                 /* Get the dir only */
490                 BLI_split_dirfile(gp_GamePythonPath, cpath, NULL);
491         }
492         
493     if((dp  = opendir(cpath)) == NULL) {
494                 /* todo, show the errno, this shouldnt happen anyway if the blendfile is readable */
495                 fprintf(stderr, "Could not read directoty (%s) failed, code %d (%s)\n", cpath, errno, strerror(errno));
496                 return list;
497     }
498         
499     while ((dirp = readdir(dp)) != NULL) {
500                 if (BLI_testextensie(dirp->d_name, ".blend")) {
501                         value= PyUnicode_DecodeFSDefault(dirp->d_name);
502                         PyList_Append(list, value);
503                         Py_DECREF(value);
504                 }
505     }
506         
507     closedir(dp);
508     return list;
509 }
510
511 static char gPyAddScene_doc[] = 
512 "addScene(name, [overlay])\n\
513 adds a scene to the game engine\n\
514 name = Name of the scene\n\
515 overlay = Overlay or underlay";
516 static PyObject* gPyAddScene(PyObject*, PyObject* args)
517 {
518         char* name;
519         int overlay = 1;
520         
521         if (!PyArg_ParseTuple(args, "s|i:addScene", &name , &overlay))
522                 return NULL;
523         
524         gp_KetsjiEngine->ConvertAndAddScene(name, (overlay != 0));
525
526         Py_RETURN_NONE;
527 }
528
529 static const char *gPyGetCurrentScene_doc =
530 "getCurrentScene()\n"
531 "Gets a reference to the current scene.\n";
532 static PyObject* gPyGetCurrentScene(PyObject* self)
533 {
534         return gp_KetsjiScene->GetProxy();
535 }
536
537 static const char *gPyGetSceneList_doc =
538 "getSceneList()\n"
539 "Return a list of converted scenes.\n";
540 static PyObject* gPyGetSceneList(PyObject* self)
541 {
542         KX_KetsjiEngine* m_engine = KX_GetActiveEngine();
543         PyObject* list;
544         KX_SceneList* scenes = m_engine->CurrentScenes();
545         int numScenes = scenes->size();
546         int i;
547         
548         list = PyList_New(numScenes);
549         
550         for (i=0;i<numScenes;i++)
551         {
552                 KX_Scene* scene = scenes->at(i);
553                 PyList_SET_ITEM(list, i, scene->GetProxy());
554         }
555
556         return list;
557 }
558
559 static PyObject *pyPrintStats(PyObject *,PyObject *,PyObject *)
560 {
561         gp_KetsjiScene->GetSceneConverter()->PrintStats();
562         Py_RETURN_NONE;
563 }
564
565 static PyObject *pyPrintExt(PyObject *,PyObject *,PyObject *)
566 {
567 #define pprint(x) std::cout << x << std::endl;
568         bool count=0;
569         bool support=0;
570         pprint("Supported Extensions...");
571         pprint(" GL_ARB_shader_objects supported?       "<< (GLEW_ARB_shader_objects?"yes.":"no."));
572         count = 1;
573
574         support= GLEW_ARB_vertex_shader;
575         pprint(" GL_ARB_vertex_shader supported?        "<< (support?"yes.":"no."));
576         count = 1;
577         if(support){
578                 pprint(" ----------Details----------");
579                 int max=0;
580                 glGetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
581                 pprint("  Max uniform components." << max);
582
583                 glGetIntegerv(GL_MAX_VARYING_FLOATS_ARB, (GLint*)&max);
584                 pprint("  Max varying floats." << max);
585
586                 glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
587                 pprint("  Max vertex texture units." << max);
588         
589                 glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, (GLint*)&max);
590                 pprint("  Max combined texture units." << max);
591                 pprint("");
592         }
593
594         support=GLEW_ARB_fragment_shader;
595         pprint(" GL_ARB_fragment_shader supported?      "<< (support?"yes.":"no."));
596         count = 1;
597         if(support){
598                 pprint(" ----------Details----------");
599                 int max=0;
600                 glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB, (GLint*)&max);
601                 pprint("  Max uniform components." << max);
602                 pprint("");
603         }
604
605         support = GLEW_ARB_texture_cube_map;
606         pprint(" GL_ARB_texture_cube_map supported?     "<< (support?"yes.":"no."));
607         count = 1;
608         if(support){
609                 pprint(" ----------Details----------");
610                 int size=0;
611                 glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB, (GLint*)&size);
612                 pprint("  Max cubemap size." << size);
613                 pprint("");
614         }
615
616         support = GLEW_ARB_multitexture;
617         count = 1;
618         pprint(" GL_ARB_multitexture supported?         "<< (support?"yes.":"no."));
619         if(support){
620                 pprint(" ----------Details----------");
621                 int units=0;
622                 glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, (GLint*)&units);
623                 pprint("  Max texture units available.  " << units);
624                 pprint("");
625         }
626
627         pprint(" GL_ARB_texture_env_combine supported?  "<< (GLEW_ARB_texture_env_combine?"yes.":"no."));
628         count = 1;
629
630         if(!count)
631                 pprint("No extenstions are used in this build");
632
633         Py_RETURN_NONE;
634 }
635
636 static PyObject *gLibLoad(PyObject*, PyObject* args)
637 {
638         KX_Scene *kx_scene= gp_KetsjiScene;
639         char *path;
640         char *group;
641         Py_buffer py_buffer;
642         py_buffer.buf = NULL;
643         char *err_str= NULL;
644         
645         if (!PyArg_ParseTuple(args,"ss|y*:LibLoad",&path, &group, &py_buffer))
646                 return NULL;
647
648         if (!py_buffer.buf)
649         {
650                 if(kx_scene->GetSceneConverter()->LinkBlendFilePath(path, group, kx_scene, &err_str)) {
651                         Py_RETURN_TRUE;
652                 }
653         }
654         else
655         {
656
657                 if(kx_scene->GetSceneConverter()->LinkBlendFileMemory(py_buffer.buf, py_buffer.len, path, group, kx_scene, &err_str))   {
658                         PyBuffer_Release(&py_buffer);
659                         Py_RETURN_TRUE;
660                 }
661
662                 PyBuffer_Release(&py_buffer);
663         }
664         
665         if(err_str) {
666                 PyErr_SetString(PyExc_ValueError, err_str);
667                 return NULL;
668         }
669         
670         Py_RETURN_FALSE;
671 }
672
673 static PyObject *gLibNew(PyObject*, PyObject* args)
674 {
675         KX_Scene *kx_scene= gp_KetsjiScene;
676         char *path;
677         char *group;
678         char *name;
679         PyObject *names;
680         int idcode;
681
682         if (!PyArg_ParseTuple(args,"ssO!:LibNew",&path, &group, &PyList_Type, &names))
683                 return NULL;
684         
685         if(kx_scene->GetSceneConverter()->GetMainDynamicPath(path))
686         {
687                 PyErr_SetString(PyExc_KeyError, "the name of the path given exists");
688                 return NULL;
689         }
690         
691         idcode= BKE_idcode_from_name(group);
692         if(idcode==0) {
693                 PyErr_Format(PyExc_ValueError, "invalid group given \"%s\"", group);
694                 return NULL;
695         }
696         
697         Main *maggie= (Main *)MEM_callocN( sizeof(Main), "BgeMain");
698         kx_scene->GetSceneConverter()->GetMainDynamic().push_back(maggie);
699         strncpy(maggie->name, path, sizeof(maggie->name)-1);
700         
701         /* Copy the object into main */
702         if(idcode==ID_ME) {
703                 PyObject *ret= PyList_New(0);
704                 PyObject *item;
705                 for(int i= 0; i < PyList_GET_SIZE(names); i++) {
706                         name= _PyUnicode_AsString(PyList_GET_ITEM(names, i));
707                         if(name) {
708                                 RAS_MeshObject *meshobj= kx_scene->GetSceneConverter()->ConvertMeshSpecial(kx_scene, maggie, name);
709                                 if(meshobj) {
710                                         KX_MeshProxy* meshproxy = new KX_MeshProxy(meshobj);
711                                         item= meshproxy->NewProxy(true);
712                                         PyList_Append(ret, item);
713                                         Py_DECREF(item);
714                                 }
715                         }
716                         else {
717                                 PyErr_Clear(); /* wasnt a string, ignore for now */
718                         }
719                 }
720                 
721                 return ret;
722         }
723         else {
724                 PyErr_Format(PyExc_ValueError, "only \"Mesh\" group currently supported");
725                 return NULL;
726         }
727         
728         Py_RETURN_NONE;
729 }
730
731 static PyObject *gLibFree(PyObject*, PyObject* args)
732 {
733         KX_Scene *kx_scene= gp_KetsjiScene;
734         char *path;
735
736         if (!PyArg_ParseTuple(args,"s:LibFree",&path))
737                 return NULL;
738
739         if (kx_scene->GetSceneConverter()->FreeBlendFile(path))
740         {
741                 Py_RETURN_TRUE;
742         }
743         else {
744                 Py_RETURN_FALSE;
745         }
746 }
747
748 static PyObject *gLibList(PyObject*, PyObject* args)
749 {
750         vector<Main*> &dynMaggie = gp_KetsjiScene->GetSceneConverter()->GetMainDynamic();
751         int i= 0;
752         PyObject *list= PyList_New(dynMaggie.size());
753         
754         for (vector<Main*>::iterator it=dynMaggie.begin(); !(it==dynMaggie.end()); it++)
755         {
756                 PyList_SET_ITEM(list, i++, PyUnicode_FromString( (*it)->name) );
757         }
758         
759         return list;
760 }
761
762 static struct PyMethodDef game_methods[] = {
763         {"expandPath", (PyCFunction)gPyExpandPath, METH_VARARGS, (const char *)gPyExpandPath_doc},
764         {"startGame", (PyCFunction)gPyStartGame, METH_VARARGS, (const char *)gPyStartGame_doc},
765         {"endGame", (PyCFunction)gPyEndGame, METH_NOARGS, (const char *)gPyEndGame_doc},
766         {"restartGame", (PyCFunction)gPyRestartGame, METH_NOARGS, (const char *)gPyRestartGame_doc},
767         {"saveGlobalDict", (PyCFunction)gPySaveGlobalDict, METH_NOARGS, (const char *)gPySaveGlobalDict_doc},
768         {"loadGlobalDict", (PyCFunction)gPyLoadGlobalDict, METH_NOARGS, (const char *)gPyLoadGlobalDict_doc},
769         {"sendMessage", (PyCFunction)gPySendMessage, METH_VARARGS, (const char *)gPySendMessage_doc},
770         {"getCurrentController", (PyCFunction) SCA_PythonController::sPyGetCurrentController, METH_NOARGS, SCA_PythonController::sPyGetCurrentController__doc__},
771         {"getCurrentScene", (PyCFunction) gPyGetCurrentScene, METH_NOARGS, gPyGetCurrentScene_doc},
772         {"getSceneList", (PyCFunction) gPyGetSceneList, METH_NOARGS, (const char *)gPyGetSceneList_doc},
773         {"addScene", (PyCFunction)gPyAddScene, METH_VARARGS, (const char *)gPyAddScene_doc},
774         {"getRandomFloat",(PyCFunction) gPyGetRandomFloat, METH_NOARGS, (const char *)gPyGetRandomFloat_doc},
775         {"setGravity",(PyCFunction) gPySetGravity, METH_O, (const char *)"set Gravitation"},
776         {"getSpectrum",(PyCFunction) gPyGetSpectrum, METH_NOARGS, (const char *)"get audio spectrum"},
777         {"getMaxLogicFrame", (PyCFunction) gPyGetMaxLogicFrame, METH_NOARGS, (const char *)"Gets the max number of logic frame per render frame"},
778         {"setMaxLogicFrame", (PyCFunction) gPySetMaxLogicFrame, METH_VARARGS, (const char *)"Sets the max number of logic frame per render frame"},
779         {"getMaxPhysicsFrame", (PyCFunction) gPyGetMaxPhysicsFrame, METH_NOARGS, (const char *)"Gets the max number of physics frame per render frame"},
780         {"setMaxPhysicsFrame", (PyCFunction) gPySetMaxPhysicsFrame, METH_VARARGS, (const char *)"Sets the max number of physics farme per render frame"},
781         {"getLogicTicRate", (PyCFunction) gPyGetLogicTicRate, METH_NOARGS, (const char *)"Gets the logic tic rate"},
782         {"setLogicTicRate", (PyCFunction) gPySetLogicTicRate, METH_VARARGS, (const char *)"Sets the logic tic rate"},
783         {"getPhysicsTicRate", (PyCFunction) gPyGetPhysicsTicRate, METH_NOARGS, (const char *)"Gets the physics tic rate"},
784         {"setPhysicsTicRate", (PyCFunction) gPySetPhysicsTicRate, METH_VARARGS, (const char *)"Sets the physics tic rate"},
785         {"getAverageFrameRate", (PyCFunction) gPyGetAverageFrameRate, METH_NOARGS, (const char *)"Gets the estimated average frame rate"},
786         {"getBlendFileList", (PyCFunction)gPyGetBlendFileList, METH_VARARGS, (const char *)"Gets a list of blend files in the same directory as the current blend file"},
787         {"PrintGLInfo", (PyCFunction)pyPrintExt, METH_NOARGS, (const char *)"Prints GL Extension Info"},
788         {"PrintMemInfo", (PyCFunction)pyPrintStats, METH_NOARGS, (const char *)"Print engine stastics"},
789         
790         /* library functions */
791         {"LibLoad", (PyCFunction)gLibLoad, METH_VARARGS, (const char *)""},
792         {"LibNew", (PyCFunction)gLibNew, METH_VARARGS, (const char *)""},
793         {"LibFree", (PyCFunction)gLibFree, METH_VARARGS, (const char *)""},
794         {"LibList", (PyCFunction)gLibList, METH_VARARGS, (const char *)""},
795         
796         {NULL, (PyCFunction) NULL, 0, NULL }
797 };
798
799 static PyObject* gPyGetWindowHeight(PyObject*, PyObject* args)
800 {
801         return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetHeight() : 0));
802 }
803
804
805
806 static PyObject* gPyGetWindowWidth(PyObject*, PyObject* args)
807 {
808         return PyLong_FromSsize_t((gp_Canvas ? gp_Canvas->GetWidth() : 0));
809 }
810
811
812
813 // temporarility visibility thing, will be moved to rasterizer/renderer later
814 bool gUseVisibilityTemp = false;
815
816 static PyObject* gPyEnableVisibility(PyObject*, PyObject* args)
817 {
818         int visible;
819         if (!PyArg_ParseTuple(args,"i:enableVisibility",&visible))
820                 return NULL;
821         
822         gUseVisibilityTemp = (visible != 0);
823         Py_RETURN_NONE;
824 }
825
826
827
828 static PyObject* gPyShowMouse(PyObject*, PyObject* args)
829 {
830         int visible;
831         if (!PyArg_ParseTuple(args,"i:showMouse",&visible))
832                 return NULL;
833         
834         if (visible)
835         {
836                 if (gp_Canvas)
837                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
838         } else
839         {
840                 if (gp_Canvas)
841                         gp_Canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
842         }
843         
844         Py_RETURN_NONE;
845 }
846
847
848
849 static PyObject* gPySetMousePosition(PyObject*, PyObject* args)
850 {
851         int x,y;
852         if (!PyArg_ParseTuple(args,"ii:setMousePosition",&x,&y))
853                 return NULL;
854         
855         if (gp_Canvas)
856                 gp_Canvas->SetMousePosition(x,y);
857         
858         Py_RETURN_NONE;
859 }
860
861 static PyObject* gPySetEyeSeparation(PyObject*, PyObject* args)
862 {
863         float sep;
864         if (!PyArg_ParseTuple(args, "f:setEyeSeparation", &sep))
865                 return NULL;
866
867         if (!gp_Rasterizer) {
868                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setEyeSeparation(float), Rasterizer not available");
869                 return NULL;
870         }
871         
872         gp_Rasterizer->SetEyeSeparation(sep);
873         
874         Py_RETURN_NONE;
875 }
876
877 static PyObject* gPyGetEyeSeparation(PyObject*)
878 {
879         if (!gp_Rasterizer) {
880                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getEyeSeparation(), Rasterizer not available");
881                 return NULL;
882         }
883         
884         return PyFloat_FromDouble(gp_Rasterizer->GetEyeSeparation());
885 }
886
887 static PyObject* gPySetFocalLength(PyObject*, PyObject* args)
888 {
889         float focus;
890         if (!PyArg_ParseTuple(args, "f:setFocalLength", &focus))
891                 return NULL;
892         
893         if (!gp_Rasterizer) {
894                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setFocalLength(float), Rasterizer not available");
895                 return NULL;
896         }
897
898         gp_Rasterizer->SetFocalLength(focus);
899         
900         Py_RETURN_NONE;
901 }
902
903 static PyObject* gPyGetFocalLength(PyObject*, PyObject*, PyObject*)
904 {
905         if (!gp_Rasterizer) {
906                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getFocalLength(), Rasterizer not available");
907                 return NULL;
908         }
909         
910         return PyFloat_FromDouble(gp_Rasterizer->GetFocalLength());
911         
912         Py_RETURN_NONE;
913 }
914
915 static PyObject* gPySetBackgroundColor(PyObject*, PyObject* value)
916 {
917         
918         MT_Vector4 vec;
919         if (!PyVecTo(value, vec))
920                 return NULL;
921         
922         if (gp_Canvas)
923         {
924                 gp_Rasterizer->SetBackColor(vec[0], vec[1], vec[2], vec[3]);
925         }
926
927         KX_WorldInfo *wi = gp_KetsjiScene->GetWorldInfo();
928         if (wi->hasWorld())
929                 wi->setBackColor(vec[0], vec[1], vec[2]);
930
931         Py_RETURN_NONE;
932 }
933
934
935
936 static PyObject* gPySetMistColor(PyObject*, PyObject* value)
937 {
938         
939         MT_Vector3 vec;
940         if (!PyVecTo(value, vec))
941                 return NULL;
942         
943         if (!gp_Rasterizer) {
944                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
945                 return NULL;
946         }       
947         gp_Rasterizer->SetFogColor(vec[0], vec[1], vec[2]);
948         
949         Py_RETURN_NONE;
950 }
951
952 static PyObject* gPyDisableMist(PyObject*)
953 {
954         
955         if (!gp_Rasterizer) {
956                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistColor(color), Rasterizer not available");
957                 return NULL;
958         }       
959         gp_Rasterizer->DisableFog();
960         
961         Py_RETURN_NONE;
962 }
963
964 static PyObject* gPySetMistStart(PyObject*, PyObject* args)
965 {
966
967         float miststart;
968         if (!PyArg_ParseTuple(args,"f:setMistStart",&miststart))
969                 return NULL;
970         
971         if (!gp_Rasterizer) {
972                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistStart(float), Rasterizer not available");
973                 return NULL;
974         }
975         
976         gp_Rasterizer->SetFogStart(miststart);
977         
978         Py_RETURN_NONE;
979 }
980
981
982
983 static PyObject* gPySetMistEnd(PyObject*, PyObject* args)
984 {
985
986         float mistend;
987         if (!PyArg_ParseTuple(args,"f:setMistEnd",&mistend))
988                 return NULL;
989         
990         if (!gp_Rasterizer) {
991                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMistEnd(float), Rasterizer not available");
992                 return NULL;
993         }
994         
995         gp_Rasterizer->SetFogEnd(mistend);
996         
997         Py_RETURN_NONE;
998 }
999
1000
1001 static PyObject* gPySetAmbientColor(PyObject*, PyObject* value)
1002 {
1003         
1004         MT_Vector3 vec;
1005         if (!PyVecTo(value, vec))
1006                 return NULL;
1007         
1008         if (!gp_Rasterizer) {
1009                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setAmbientColor(color), Rasterizer not available");
1010                 return NULL;
1011         }       
1012         gp_Rasterizer->SetAmbientColor(vec[0], vec[1], vec[2]);
1013         
1014         Py_RETURN_NONE;
1015 }
1016
1017
1018
1019
1020 static PyObject* gPyMakeScreenshot(PyObject*, PyObject* args)
1021 {
1022         char* filename;
1023         if (!PyArg_ParseTuple(args,"s:makeScreenshot",&filename))
1024                 return NULL;
1025         
1026         if (gp_Canvas)
1027         {
1028                 gp_Canvas->MakeScreenShot(filename);
1029         }
1030         
1031         Py_RETURN_NONE;
1032 }
1033
1034 static PyObject* gPyEnableMotionBlur(PyObject*, PyObject* args)
1035 {
1036         float motionblurvalue;
1037         if (!PyArg_ParseTuple(args,"f:enableMotionBlur",&motionblurvalue))
1038                 return NULL;
1039         
1040         if (!gp_Rasterizer) {
1041                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.enableMotionBlur(float), Rasterizer not available");
1042                 return NULL;
1043         }
1044         
1045         gp_Rasterizer->EnableMotionBlur(motionblurvalue);
1046         
1047         Py_RETURN_NONE;
1048 }
1049
1050 static PyObject* gPyDisableMotionBlur(PyObject*)
1051 {
1052         if (!gp_Rasterizer) {
1053                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.disableMotionBlur(), Rasterizer not available");
1054                 return NULL;
1055         }
1056         
1057         gp_Rasterizer->DisableMotionBlur();
1058         
1059         Py_RETURN_NONE;
1060 }
1061
1062 int getGLSLSettingFlag(char *setting)
1063 {
1064         if(strcmp(setting, "lights") == 0)
1065                 return GAME_GLSL_NO_LIGHTS;
1066         else if(strcmp(setting, "shaders") == 0)
1067                 return GAME_GLSL_NO_SHADERS;
1068         else if(strcmp(setting, "shadows") == 0)
1069                 return GAME_GLSL_NO_SHADOWS;
1070         else if(strcmp(setting, "ramps") == 0)
1071                 return GAME_GLSL_NO_RAMPS;
1072         else if(strcmp(setting, "nodes") == 0)
1073                 return GAME_GLSL_NO_NODES;
1074         else if(strcmp(setting, "extra_textures") == 0)
1075                 return GAME_GLSL_NO_EXTRA_TEX;
1076         else
1077                 return -1;
1078 }
1079
1080 static PyObject* gPySetGLSLMaterialSetting(PyObject*,
1081                                                                                         PyObject* args,
1082                                                                                         PyObject*)
1083 {
1084         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1085         char *setting;
1086         int enable, flag, sceneflag;
1087
1088         if (!PyArg_ParseTuple(args,"si:setGLSLMaterialSetting",&setting,&enable))
1089                 return NULL;
1090         
1091         flag = getGLSLSettingFlag(setting);
1092         
1093         if  (flag==-1) {
1094                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setGLSLMaterialSetting(string): glsl setting is not known");
1095                 return NULL;
1096         }
1097
1098         sceneflag= gm->flag;
1099         
1100         if (enable)
1101                 gm->flag &= ~flag;
1102         else
1103                 gm->flag |= flag;
1104
1105         /* display lists and GLSL materials need to be remade */
1106         if(sceneflag != gm->flag) {
1107                 GPU_materials_free();
1108                 if(gp_KetsjiEngine) {
1109                         KX_SceneList *scenes = gp_KetsjiEngine->CurrentScenes();
1110                         KX_SceneList::iterator it;
1111
1112                         for(it=scenes->begin(); it!=scenes->end(); it++)
1113                                 if((*it)->GetBucketManager()) {
1114                                         (*it)->GetBucketManager()->ReleaseDisplayLists();
1115                                         (*it)->GetBucketManager()->ReleaseMaterials();
1116                                 }
1117                 }
1118         }
1119
1120         Py_RETURN_NONE;
1121 }
1122
1123 static PyObject* gPyGetGLSLMaterialSetting(PyObject*, 
1124                                                                          PyObject* args, 
1125                                                                          PyObject*)
1126 {
1127         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1128         char *setting;
1129         int enabled = 0, flag;
1130
1131         if (!PyArg_ParseTuple(args,"s:getGLSLMaterialSetting",&setting))
1132                 return NULL;
1133         
1134         flag = getGLSLSettingFlag(setting);
1135         
1136         if  (flag==-1) {
1137                 PyErr_SetString(PyExc_ValueError, "Rasterizer.getGLSLMaterialSetting(string): glsl setting is not known");
1138                 return NULL;
1139         }
1140
1141         enabled = ((gm->flag & flag) != 0);
1142         return PyLong_FromSsize_t(enabled);
1143 }
1144
1145 #define KX_TEXFACE_MATERIAL                             0
1146 #define KX_BLENDER_MULTITEX_MATERIAL    1
1147 #define KX_BLENDER_GLSL_MATERIAL                2
1148
1149 static PyObject* gPySetMaterialType(PyObject*,
1150                                                                         PyObject* args,
1151                                                                         PyObject*)
1152 {
1153         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1154         int type;
1155
1156         if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
1157                 return NULL;
1158
1159         if(type == KX_BLENDER_GLSL_MATERIAL)
1160                 gm->matmode= GAME_MAT_GLSL;
1161         else if(type == KX_BLENDER_MULTITEX_MATERIAL)
1162                 gm->matmode= GAME_MAT_MULTITEX;
1163         else if(type == KX_TEXFACE_MATERIAL)
1164                 gm->matmode= GAME_MAT_TEXFACE;
1165         else {
1166                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
1167                 return NULL;
1168         }
1169
1170         Py_RETURN_NONE;
1171 }
1172
1173 static PyObject* gPyGetMaterialType(PyObject*)
1174 {
1175         GameData *gm= &(gp_KetsjiScene->GetBlenderScene()->gm);
1176         int flag;
1177
1178         if(gm->matmode == GAME_MAT_GLSL)
1179                 flag = KX_BLENDER_GLSL_MATERIAL;
1180         else if(gm->matmode == GAME_MAT_MULTITEX)
1181                 flag = KX_BLENDER_MULTITEX_MATERIAL;
1182         else
1183                 flag = KX_TEXFACE_MATERIAL;
1184         
1185         return PyLong_FromSsize_t(flag);
1186 }
1187
1188 static PyObject* gPyDrawLine(PyObject*, PyObject* args)
1189 {
1190         PyObject* ob_from;
1191         PyObject* ob_to;
1192         PyObject* ob_color;
1193
1194         if (!gp_Rasterizer) {
1195                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
1196                 return NULL;
1197         }
1198
1199         if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
1200                 return NULL;
1201
1202         MT_Vector3 from;
1203         MT_Vector3 to;
1204         MT_Vector3 color;
1205         if (!PyVecTo(ob_from, from))
1206                 return NULL;
1207         if (!PyVecTo(ob_to, to))
1208                 return NULL;
1209         if (!PyVecTo(ob_color, color))
1210                 return NULL;
1211
1212         gp_Rasterizer->DrawDebugLine(from,to,color);
1213         
1214         Py_RETURN_NONE;
1215 }
1216
1217 static struct PyMethodDef rasterizer_methods[] = {
1218   {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
1219    METH_VARARGS, "getWindowWidth doc"},
1220    {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
1221    METH_VARARGS, "getWindowHeight doc"},
1222   {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
1223         METH_VARARGS, "make Screenshot doc"},
1224    {"enableVisibility",(PyCFunction) gPyEnableVisibility,
1225    METH_VARARGS, "enableVisibility doc"},
1226         {"showMouse",(PyCFunction) gPyShowMouse,
1227    METH_VARARGS, "showMouse(bool visible)"},
1228    {"setMousePosition",(PyCFunction) gPySetMousePosition,
1229    METH_VARARGS, "setMousePosition(int x,int y)"},
1230   {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
1231         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
1232  {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
1233  {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
1234   {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
1235   {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
1236   {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
1237   {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
1238
1239   
1240   {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
1241   {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
1242   {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
1243   {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
1244   {"setMaterialMode",(PyCFunction) gPySetMaterialType,
1245    METH_VARARGS, "set the material mode to use for OpenGL rendering"},
1246   {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
1247    METH_NOARGS, "get the material mode being used for OpenGL rendering"},
1248   {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
1249    METH_VARARGS, "set the state of a GLSL material setting"},
1250   {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
1251    METH_VARARGS, "get the state of a GLSL material setting"},
1252   {"drawLine", (PyCFunction) gPyDrawLine,
1253    METH_VARARGS, "draw a line on the screen"},
1254   { NULL, (PyCFunction) NULL, 0, NULL }
1255 };
1256
1257 // Initialization function for the module (*must* be called initGameLogic)
1258
1259 static char GameLogic_module_documentation[] =
1260 "This is the Python API for the game engine of bge.logic"
1261 ;
1262
1263 static char Rasterizer_module_documentation[] =
1264 "This is the Python API for the game engine of Rasterizer"
1265 ;
1266
1267 static struct PyModuleDef GameLogic_module_def = {
1268         {}, /* m_base */
1269         "GameLogic",  /* m_name */
1270         GameLogic_module_documentation,  /* m_doc */
1271         0,  /* m_size */
1272         game_methods,  /* m_methods */
1273         0,  /* m_reload */
1274         0,  /* m_traverse */
1275         0,  /* m_clear */
1276         0,  /* m_free */
1277 };
1278
1279 PyObject* initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
1280 {
1281         PyObject* m;
1282         PyObject* d;
1283         PyObject* item; /* temp PyObject* storage */
1284         
1285         gp_KetsjiEngine = engine;
1286         gp_KetsjiScene = scene;
1287
1288         gUseVisibilityTemp=false;
1289         
1290         PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */
1291         
1292         /* Use existing module where possible
1293          * be careful not to init any runtime vars after this */
1294         m = PyImport_ImportModule( "GameLogic" );
1295         if(m) {
1296                 Py_DECREF(m);
1297                 return m;
1298         }
1299         else {
1300                 PyErr_Clear();
1301                 // Create the module and add the functions      
1302                 m = PyModule_Create(&GameLogic_module_def);
1303                 PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
1304         }
1305         
1306         // Add some symbolic constants to the module
1307         d = PyModule_GetDict(m);
1308         
1309         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
1310         // for now its safe to make sure it exists for other areas such as the web plugin
1311         
1312         PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
1313
1314         // Add keyboard and mouse attributes to this module
1315         MT_assert(!gp_PythonKeyboard);
1316         gp_PythonKeyboard = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice());
1317         PyDict_SetItemString(d, "keyboard", gp_PythonKeyboard->NewProxy(true));
1318
1319         MT_assert(!gp_PythonMouse);
1320         gp_PythonMouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas);
1321         PyDict_SetItemString(d, "mouse", gp_PythonMouse->NewProxy(true));
1322
1323         ErrorObject = PyUnicode_FromString("GameLogic.error");
1324         PyDict_SetItemString(d, "error", ErrorObject);
1325         Py_DECREF(ErrorObject);
1326         
1327         // XXXX Add constants here
1328         /* To use logic bricks, we need some sort of constants. Here, we associate */
1329         /* constants and sumbolic names. Add them to dictionary d.                 */
1330
1331         /* 1. true and false: needed for everyone                                  */
1332         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
1333         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
1334
1335         /* 2. Property sensor                                                      */
1336         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
1337         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
1338         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
1339         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
1340         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
1341
1342         /* 3. Constraint actuator                                                  */
1343         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
1344         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
1345         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
1346         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
1347         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
1348         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
1349         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
1350         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1351         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ);
1352         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
1353         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1354         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ);
1355         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
1356         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
1357         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
1358         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
1359         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
1360         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
1361         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
1362         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
1363         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
1364         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
1365         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
1366         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
1367         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
1368         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
1369         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
1370
1371         /* 4. Ipo actuator, simple part                                            */
1372         KX_MACRO_addTypesToDict(d, KX_IPOACT_PLAY,     KX_IpoActuator::KX_ACT_IPO_PLAY);
1373         KX_MACRO_addTypesToDict(d, KX_IPOACT_PINGPONG, KX_IpoActuator::KX_ACT_IPO_PINGPONG);
1374         KX_MACRO_addTypesToDict(d, KX_IPOACT_FLIPPER,  KX_IpoActuator::KX_ACT_IPO_FLIPPER);
1375         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPSTOP, KX_IpoActuator::KX_ACT_IPO_LOOPSTOP);
1376         KX_MACRO_addTypesToDict(d, KX_IPOACT_LOOPEND,  KX_IpoActuator::KX_ACT_IPO_LOOPEND);
1377         KX_MACRO_addTypesToDict(d, KX_IPOACT_FROM_PROP,KX_IpoActuator::KX_ACT_IPO_FROM_PROP);
1378
1379         /* 5. Random distribution types                                            */
1380         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
1381         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
1382         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
1383         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
1384         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
1385         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
1386         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
1387         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
1388         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
1389         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
1390
1391         /* 6. Sound actuator                                                      */
1392         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1393         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1394         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1395         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
1396         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1397         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1398
1399         /* 7. Action actuator                                                                                                      */
1400         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
1401         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PINGPONG,    ACT_ACTION_PINGPONG);
1402         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
1403         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
1404         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
1405         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1406         
1407         /*8. GL_BlendFunc */
1408         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1409         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1410         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1411         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1412         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1413         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1414         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1415         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1416         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1417         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1418         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1419
1420
1421         /* 9. UniformTypes */
1422         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1423         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1424         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1425         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1426         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1427         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1428         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1429         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1430         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1431         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1432         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1433         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1434         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1435         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1436         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1437
1438         /* 10 state actuator */
1439         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1440         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1441         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1442         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1443         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1444         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1445         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1446         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1447         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1448         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1449         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1450         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1451         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1452         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1453         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1454         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1455         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1456         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1457         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1458         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1459         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1460         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1461         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1462         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1463         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1464         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1465         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1466         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1467         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1468         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1469         
1470         /* All Sensors */
1471         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED);
1472         KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE);
1473         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED);
1474         KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE);
1475         
1476         /* Radar Sensor */
1477         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1478         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1479         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1480         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1481         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1482         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1483
1484         /* Ray Sensor */
1485         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
1486         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
1487         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
1488         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
1489         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_X);
1490         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
1491
1492         /* Dynamic actuator */
1493         KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
1494         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
1495         KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
1496         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
1497         KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
1498
1499         /* Input & Mouse Sensor */
1500         KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
1501         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
1502         KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
1503         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
1504         
1505         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
1506         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
1507         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
1508
1509         /* 2D Filter Actuator */
1510         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
1511         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
1512         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
1513         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
1514         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
1515         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
1516         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
1517         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
1518         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
1519         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
1520         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
1521         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
1522         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
1523         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
1524         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
1525
1526         /* Sound Actuator */
1527         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1528         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1529         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1530         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
1531         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1532         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1533
1534         /* State Actuator */
1535         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
1536         KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
1537         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
1538         KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
1539
1540         /* Game Actuator Modes */
1541         KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD);
1542         KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START);
1543         KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART);
1544         KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT);
1545         KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG);
1546         KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG);
1547
1548         /* Scene Actuator Modes */
1549         KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART);
1550         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE);
1551         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA);
1552         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE);
1553         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE);
1554         KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE);
1555         KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND);
1556         KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME);
1557
1558         /* Parent Actuator Modes */
1559         KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET);
1560         KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE);
1561
1562         /* BL_ArmatureConstraint type */
1563         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO);
1564         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC);
1565         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE);
1566         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE);
1567         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX);
1568         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE);
1569         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK);
1570         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO);
1571         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO);
1572         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM);
1573         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT);
1574         /* BL_ArmatureConstraint ik_type */
1575         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE);
1576         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE);
1577         /* BL_ArmatureConstraint ik_mode */
1578         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE);
1579         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE);
1580         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE);
1581         /* BL_ArmatureConstraint ik_flag */
1582         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP);
1583         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT);
1584         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH);
1585         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS);
1586         /* KX_ArmatureSensor type */
1587         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED);
1588         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW);
1589         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE);
1590         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW);
1591         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE);
1592
1593         /* BL_ArmatureActuator type */
1594         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN);
1595         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE);
1596         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE);
1597         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET);
1598         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT);
1599
1600         /* BL_Armature Channel rotation_mode */
1601         KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT);
1602         KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ);
1603         KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY);
1604         KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ);
1605         KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX);
1606         KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY);
1607         KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX);
1608
1609         // Check for errors
1610         if (PyErr_Occurred())
1611     {
1612                 Py_FatalError("can't initialize module bge.logic");
1613     }
1614
1615         return m;
1616 }
1617
1618 // Python Sandbox code
1619 // override builtin functions import() and open()
1620
1621
1622 PyObject *KXpy_open(PyObject *self, PyObject *args) {
1623         PyErr_SetString(PyExc_RuntimeError, "Sandbox: open() function disabled!\nGame Scripts should not use this function.");
1624         return NULL;
1625 }
1626
1627 PyObject *KXpy_file(PyObject *self, PyObject *args) {
1628         PyErr_SetString(PyExc_RuntimeError, "Sandbox: file() function disabled!\nGame Scripts should not use this function.");
1629         return NULL;
1630 }
1631
1632 PyObject *KXpy_execfile(PyObject *self, PyObject *args) {
1633         PyErr_SetString(PyExc_RuntimeError, "Sandbox: execfile() function disabled!\nGame Scripts should not use this function.");
1634         return NULL;
1635 }
1636
1637 PyObject *KXpy_compile(PyObject *self, PyObject *args) {
1638         PyErr_SetString(PyExc_RuntimeError, "Sandbox: compile() function disabled!\nGame Scripts should not use this function.");
1639         return NULL;
1640 }
1641
1642 PyObject *KXpy_import(PyObject *self, PyObject *args)
1643 {
1644         char *name;
1645         int found;
1646         PyObject *globals = NULL;
1647         PyObject *locals = NULL;
1648         PyObject *fromlist = NULL;
1649         PyObject *l, *m, *n;
1650         int level; /* not used yet */
1651         
1652         if (!PyArg_ParseTuple(args, "s|OOOi:m_import",
1653                 &name, &globals, &locals, &fromlist, &level))
1654             return NULL;
1655
1656         /* check for builtin modules */
1657         m = PyImport_AddModule("sys");
1658         l = PyObject_GetAttrString(m, "builtin_module_names");
1659         n = PyUnicode_FromString(name);
1660         
1661         if (PySequence_Contains(l, n)) {
1662                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1663         }
1664
1665         /* quick hack for GamePython modules 
1666                 TODO: register builtin modules properly by ExtendInittab */
1667         if (!strcmp(name, "GameLogic") || !strcmp(name, "GameKeys") || !strcmp(name, "PhysicsConstraints") ||
1668                 !strcmp(name, "Rasterizer") || !strcmp(name, "mathutils") || !strcmp(name, "bgl") || !strcmp(name, "geometry")) {
1669                 return PyImport_ImportModuleEx(name, globals, locals, fromlist);
1670         }
1671         
1672         /* Import blender texts as python modules */
1673         m= bpy_text_import_name(name, &found);
1674         if (m)
1675                 return m;
1676         
1677         if(found==0) /* if its found but could not import then it has its own error */
1678                 PyErr_Format(PyExc_ImportError, "Import of external Module %.20s not allowed.", name);
1679         
1680         return NULL;
1681
1682 }
1683
1684 PyObject *KXpy_reload(PyObject *self, PyObject *args) {
1685         
1686         /* Used to be sandboxed, bettet to allow importing of internal text only */ 
1687 #if 0
1688         PyErr_SetString(PyExc_RuntimeError, "Sandbox: reload() function disabled!\nGame Scripts should not use this function.");
1689         return NULL;
1690 #endif
1691         int found;
1692         PyObject *module = NULL;
1693         PyObject *newmodule = NULL;
1694
1695         /* check for a module arg */
1696         if( !PyArg_ParseTuple( args, "O:bpy_reload_meth", &module ) )
1697                 return NULL;
1698         
1699         newmodule= bpy_text_reimport( module, &found );
1700         if (newmodule)
1701                 return newmodule;
1702         
1703         if (found==0) /* if its found but could not import then it has its own error */
1704                 PyErr_SetString(PyExc_ImportError, "reload(module): failed to reload from blenders internal text");
1705         
1706         return newmodule;
1707 }
1708
1709 /* override python file type functions */
1710 #if 0
1711 static int
1712 file_init(PyObject *self, PyObject *args, PyObject *kwds)
1713 {
1714         KXpy_file(NULL, NULL);
1715         return -1;
1716 }
1717
1718 static PyObject *
1719 file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1720 {
1721         return KXpy_file(NULL, NULL);
1722 }
1723 #endif
1724
1725 static PyMethodDef meth_open[] = {{ "open", KXpy_open, METH_VARARGS, "(disabled)"}};
1726 static PyMethodDef meth_reload[] = {{ "reload", KXpy_reload, METH_VARARGS, "(disabled)"}};
1727 static PyMethodDef meth_file[] = {{ "file", KXpy_file, METH_VARARGS, "(disabled)"}};
1728 static PyMethodDef meth_execfile[] = {{ "execfile", KXpy_execfile, METH_VARARGS, "(disabled)"}};
1729 static PyMethodDef meth_compile[] = {{ "compile", KXpy_compile, METH_VARARGS, "(disabled)"}};
1730
1731 static PyMethodDef meth_import[] = {{ "import", KXpy_import, METH_VARARGS, "our own import"}};
1732
1733 //static PyObject *g_oldopen = 0;
1734 //static PyObject *g_oldimport = 0;
1735 //static int g_security = 0;
1736
1737 static void setSandbox(TPythonSecurityLevel level)
1738 {
1739     PyObject *m = PyImport_AddModule("__builtin__");
1740     PyObject *d = PyModule_GetDict(m);
1741         PyObject *item;
1742         switch (level) {
1743         case psl_Highest:
1744                 //if (!g_security) {
1745                         //g_oldopen = PyDict_GetItemString(d, "open");
1746         
1747                         // functions we cant trust
1748                         PyDict_SetItemString(d, "open", item=PyCFunction_New(meth_open, NULL));                 Py_DECREF(item);
1749                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(meth_reload, NULL));             Py_DECREF(item);
1750                         PyDict_SetItemString(d, "file", item=PyCFunction_New(meth_file, NULL));                 Py_DECREF(item);
1751                         PyDict_SetItemString(d, "execfile", item=PyCFunction_New(meth_execfile, NULL)); Py_DECREF(item);
1752                         PyDict_SetItemString(d, "compile", item=PyCFunction_New(meth_compile, NULL));           Py_DECREF(item);
1753                         
1754                         // our own import
1755                         PyDict_SetItemString(d, "__import__", PyCFunction_New(meth_import, NULL));
1756                         //g_security = level;
1757                         
1758                         // Overiding file dosnt stop it being accessed if your sneaky
1759                         //    f =  [ t for t in (1).__class__.__mro__[-1].__subclasses__() if t.__name__ == 'file'][0]('/some_file.txt', 'w')
1760                         //    f.write('...')
1761                         // so overwrite the file types functions. be very careful here still, since python uses python.
1762                         // ps - python devs frown deeply upon this.
1763         
1764                         /* this could mess up pythons internals, if we are serious about sandboxing
1765                          * issues like the one above need to be solved, possibly modify __subclasses__ is safer? */
1766 #if 0
1767                         PyFile_Type.tp_init = file_init;
1768                         PyFile_Type.tp_new = file_new;
1769 #endif
1770                 //}
1771                 break;
1772         /*
1773         case psl_Lowest:
1774                 if (g_security) {
1775                         PyDict_SetItemString(d, "open", g_oldopen);
1776                         PyDict_SetItemString(d, "__import__", g_oldimport);
1777                         g_security = level;
1778                 }
1779         */
1780         default:
1781                         /* Allow importing internal text, from bpy_internal_import.py */
1782                         PyDict_SetItemString(d, "reload", item=PyCFunction_New(&bpy_reload_meth, NULL));                Py_DECREF(item);
1783                         PyDict_SetItemString(d, "__import__", item=PyCFunction_New(&bpy_import_meth, NULL));    Py_DECREF(item);
1784                 break;
1785         }
1786 }
1787
1788 /* Explanation of 
1789  * 
1790  * - backupPySysObjects()               : stores sys.path in gp_OrigPythonSysPath
1791  * - initPySysObjects(main)     : initializes the blendfile and library paths
1792  * - restorePySysObjects()              : restores sys.path from gp_OrigPythonSysPath
1793  * 
1794  * These exist so the current blend dir "//" can always be used to import modules from.
1795  * the reason we need a few functions for this is that python is not only used by the game engine
1796  * so we cant just add to sys.path all the time, it would leave pythons state in a mess.
1797  * It would also be incorrect since loading blend files for new levels etc would alwasy add to sys.path
1798  * 
1799  * To play nice with blenders python, the sys.path is backed up and the current blendfile along
1800  * with all its lib paths are added to the sys path.
1801  * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top.
1802  */
1803
1804 /**
1805  * So we can have external modules mixed with our blend files.
1806  */
1807 static void backupPySysObjects(void)
1808 {
1809         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1810         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1811         
1812         /* paths */
1813         Py_XDECREF(gp_OrigPythonSysPath); /* just incase its set */
1814         gp_OrigPythonSysPath = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */
1815         
1816         /* modules */
1817         Py_XDECREF(gp_OrigPythonSysModules); /* just incase its set */
1818         gp_OrigPythonSysModules = PyDict_Copy(sys_mods); /* copy the list */
1819         
1820 }
1821
1822 /* for initPySysObjects only,
1823  * takes a blend path and adds a scripts dir from it
1824  *
1825  * "/home/me/foo.blend" -> "/home/me/scripts"
1826  */
1827 static void initPySysObjects__append(PyObject *sys_path, char *filename)
1828 {
1829         PyObject *item;
1830         char expanded[FILE_MAXDIR + FILE_MAXFILE];
1831         
1832         BLI_split_dirfile(filename, expanded, NULL); /* get the dir part of filename only */
1833         BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */
1834         BLI_cleanup_file(gp_GamePythonPath, expanded); /* Dont use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */
1835         item= PyUnicode_DecodeFSDefault(expanded);
1836         
1837 //      printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath);
1838         
1839         if(PySequence_Index(sys_path, item) == -1) {
1840                 PyErr_Clear(); /* PySequence_Index sets a ValueError */
1841                 PyList_Insert(sys_path, 0, item);
1842         }
1843         
1844         Py_DECREF(item);
1845 }
1846 static void initPySysObjects(Main *maggie)
1847 {
1848         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1849         
1850         if (gp_OrigPythonSysPath==NULL) {
1851                 /* backup */
1852                 backupPySysObjects();
1853         }
1854         else {
1855                 /* get the original sys path when the BGE started */
1856                 PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1857         }
1858         
1859         Library *lib= (Library *)maggie->library.first;
1860         
1861         while(lib) {
1862                 /* lib->name wont work in some cases (on win32),
1863                  * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
1864                 initPySysObjects__append(sys_path, lib->filepath);
1865                 lib= (Library *)lib->id.next;
1866         }
1867         
1868         initPySysObjects__append(sys_path, gp_GamePythonPath);
1869         
1870 //      fprintf(stderr, "\nNew Path: %d ", PyList_Size(sys_path));
1871 //      PyObject_Print(sys_path, stderr, 0);
1872 }
1873
1874 static void restorePySysObjects(void)
1875 {
1876         if (gp_OrigPythonSysPath==NULL)
1877                 return;
1878         
1879         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1880         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1881
1882         /* paths */
1883         PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1884         Py_DECREF(gp_OrigPythonSysPath);
1885         gp_OrigPythonSysPath= NULL;
1886         
1887         /* modules */
1888         PyDict_Clear(sys_mods);
1889         PyDict_Update(sys_mods, gp_OrigPythonSysModules);
1890         Py_DECREF(gp_OrigPythonSysModules);
1891         gp_OrigPythonSysModules= NULL;  
1892         
1893         
1894 //      fprintf(stderr, "\nRestore Path: %d ", PyList_Size(sys_path));
1895 //      PyObject_Print(sys_path, stderr, 0);
1896 }
1897
1898 /**
1899  * Python is not initialised.
1900  */
1901 PyObject* initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
1902 {
1903         /* Yet another gotcha in the py api
1904          * Cant run PySys_SetArgv more then once because this adds the
1905          * binary dir to the sys.path each time.
1906          * Id have thaught python being totally restarted would make this ok but
1907          * somehow it remembers the sys.path - Campbell
1908          */
1909         static bool first_time = true;
1910         
1911 #if 0 // TODO - py3
1912         STR_String pname = progname;
1913         Py_SetProgramName(pname.Ptr());
1914 #endif
1915         Py_NoSiteFlag=1;
1916         Py_FrozenFlag=1;
1917         Py_Initialize();
1918         
1919         if(argv && first_time) { /* browser plugins dont currently set this */
1920                 // Until python support ascii again, we use our own.
1921                 // PySys_SetArgv(argc, argv);
1922                 int i;
1923                 PyObject *py_argv= PyList_New(argc);
1924
1925                 for (i=0; i<argc; i++)
1926                         PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
1927
1928                 PySys_SetObject("argv", py_argv);
1929                 Py_DECREF(py_argv);
1930         }
1931         
1932         setSandbox(level);
1933         initPyTypes();
1934         
1935         bpy_import_main_set(maggie);
1936         
1937         initPySysObjects(maggie);
1938         
1939         first_time = false;
1940         
1941         PyObjectPlus::ClearDeprecationWarning();
1942
1943         return PyC_DefaultNameSpace(NULL);
1944 }
1945
1946 void exitGamePlayerPythonScripting()
1947 {       
1948         /* Clean up the Python mouse and keyboard */
1949         delete gp_PythonKeyboard;
1950         gp_PythonKeyboard = NULL;
1951
1952         delete gp_PythonMouse;
1953         gp_PythonMouse = NULL;
1954
1955         /* since python restarts we cant let the python backup of the sys.path hang around in a global pointer */
1956         restorePySysObjects(); /* get back the original sys.path and clear the backup */
1957         
1958         Py_Finalize();
1959         bpy_import_main_set(NULL);
1960         PyObjectPlus::ClearDeprecationWarning();
1961 }
1962
1963
1964
1965 /**
1966  * Python is already initialized.
1967  */
1968 PyObject* initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
1969 {
1970 #if 0 // XXX TODO Py3
1971         STR_String pname = progname;
1972         Py_SetProgramName(pname.Ptr());
1973 #endif
1974         Py_NoSiteFlag=1;
1975         Py_FrozenFlag=1;
1976
1977         setSandbox(level);
1978         initPyTypes();
1979         
1980         bpy_import_main_set(maggie);
1981         
1982         initPySysObjects(maggie);
1983
1984         PyObjectPlus::NullDeprecationWarning();
1985
1986         return PyC_DefaultNameSpace(NULL);
1987 }
1988
1989 void exitGamePythonScripting()
1990 {
1991         /* Clean up the Python mouse and keyboard */
1992         delete gp_PythonKeyboard;
1993         gp_PythonKeyboard = NULL;
1994
1995         delete gp_PythonMouse;
1996         gp_PythonMouse = NULL;
1997
1998         restorePySysObjects(); /* get back the original sys.path and clear the backup */
1999         bpy_import_main_set(NULL);
2000         PyObjectPlus::ClearDeprecationWarning();
2001 }
2002
2003 /* similar to the above functions except it sets up the namespace
2004  * and other more general things */
2005 void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene* startscene, Main *blenderdata, PyObject * pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
2006 {
2007         PyObject* dictionaryobject;
2008
2009         if(argv) /* player only */
2010                 dictionaryobject= initGamePlayerPythonScripting("Ketsji", psl_Lowest, blenderdata, argc, argv);
2011         else
2012                 dictionaryobject= initGamePythonScripting("Ketsji", psl_Lowest, blenderdata);
2013
2014         ketsjiengine->SetPyNamespace(dictionaryobject);
2015         initRasterizer(ketsjiengine->GetRasterizer(), ketsjiengine->GetCanvas());
2016         *gameLogic = initGameLogic(ketsjiengine, startscene);
2017
2018         /* is set in initGameLogic so only set here if we want it to persist between scenes */
2019         if(pyGlobalDict)
2020                 PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2021
2022         *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic));
2023
2024         initGameKeys();
2025         initPythonConstraintBinding();
2026         initMathutils();
2027         initGeometry();
2028         initBGL();
2029         initBLF();
2030         AUD_initPython();
2031         initVideoTexture();
2032
2033         /* could be done a lot more nicely, but for now a quick way to get bge.* working */
2034         PyRun_SimpleString("sys = __import__('sys');mod = sys.modules['bge'] = type(sys)('bge');mod.__dict__.update({'logic':__import__('GameLogic'), 'render':__import__('Rasterizer'), 'events':__import__('GameKeys'), 'constraints':__import__('PhysicsConstraints'), 'types':__import__('GameTypes'), 'texture':__import__('VideoTexture')});");
2035 }
2036
2037 static struct PyModuleDef Rasterizer_module_def = {
2038         {}, /* m_base */
2039         "Rasterizer",  /* m_name */
2040         Rasterizer_module_documentation,  /* m_doc */
2041         0,  /* m_size */
2042         rasterizer_methods,  /* m_methods */
2043         0,  /* m_reload */
2044         0,  /* m_traverse */
2045         0,  /* m_clear */
2046         0,  /* m_free */
2047 };
2048
2049 PyObject* initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
2050 {
2051         gp_Canvas = canvas;
2052         gp_Rasterizer = rasty;
2053
2054
2055   PyObject* m;
2056   PyObject* d;
2057   PyObject* item;
2058
2059         /* Use existing module where possible
2060          * be careful not to init any runtime vars after this */
2061         m = PyImport_ImportModule( "Rasterizer" );
2062         if(m) {
2063                 Py_DECREF(m);
2064                 return m;
2065         }
2066         else {
2067                 PyErr_Clear();
2068         
2069                 // Create the module and add the functions
2070                 m = PyModule_Create(&Rasterizer_module_def);
2071                 PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m);
2072         }
2073
2074   // Add some symbolic constants to the module
2075   d = PyModule_GetDict(m);
2076   ErrorObject = PyUnicode_FromString("Rasterizer.error");
2077   PyDict_SetItemString(d, "error", ErrorObject);
2078   Py_DECREF(ErrorObject);
2079
2080   /* needed for get/setMaterialType */
2081   KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
2082   KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
2083   KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
2084
2085   // XXXX Add constants here
2086
2087   // Check for errors
2088   if (PyErr_Occurred())
2089     {
2090       Py_FatalError("can't initialize module Rasterizer");
2091     }
2092
2093   return d;
2094 }
2095
2096
2097
2098 /* ------------------------------------------------------------------------- */
2099 /* GameKeys: symbolic constants for key mapping                              */
2100 /* ------------------------------------------------------------------------- */
2101
2102 static char GameKeys_module_documentation[] =
2103 "This modules provides defines for key-codes"
2104 ;
2105
2106 static char gPyEventToString_doc[] =
2107 "EventToString(event) - Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
2108 ;
2109
2110 static PyObject* gPyEventToString(PyObject*, PyObject* value)
2111 {
2112         PyObject* mod, *dict, *key, *val, *ret = NULL;
2113         Py_ssize_t pos = 0;
2114         
2115         mod = PyImport_ImportModule( "GameKeys" );
2116         if (!mod)
2117                 return NULL;
2118         
2119         dict = PyModule_GetDict(mod);
2120         
2121         while (PyDict_Next(dict, &pos, &key, &val)) {
2122                 if (PyObject_RichCompareBool(value, val, Py_EQ)) {
2123                         ret = key;
2124                         break;
2125                 }
2126         }
2127         
2128         PyErr_Clear(); // incase there was an error clearing
2129         Py_DECREF(mod);
2130         if (!ret)       PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
2131         else            Py_INCREF(ret);
2132         
2133         return ret;
2134 }
2135
2136 static char gPyEventToCharacter_doc[] =
2137 "EventToCharacter(event, is_shift) - Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
2138 ;
2139
2140 static PyObject* gPyEventToCharacter(PyObject*, PyObject* args)
2141 {
2142         int event, shift;
2143         if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
2144                 return NULL;
2145         
2146         if(IsPrintable(event)) {
2147                 char ch[2] = {'\0', '\0'};
2148                 ch[0] = ToCharacter(event, (bool)shift);
2149                 return PyUnicode_FromString(ch);
2150         }
2151         else {
2152                 return PyUnicode_FromString("");
2153         }
2154 }
2155
2156
2157 static struct PyMethodDef gamekeys_methods[] = {
2158         {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc},
2159         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc},
2160         { NULL, (PyCFunction) NULL, 0, NULL }
2161 };
2162
2163 static struct PyModuleDef GameKeys_module_def = {
2164         {}, /* m_base */
2165         "GameKeys",  /* m_name */
2166         GameKeys_module_documentation,  /* m_doc */
2167         0,  /* m_size */
2168         gamekeys_methods,  /* m_methods */
2169         0,  /* m_reload */
2170         0,  /* m_traverse */
2171         0,  /* m_clear */
2172         0,  /* m_free */
2173 };
2174
2175 PyObject* initGameKeys()
2176 {
2177         PyObject* m;
2178         PyObject* d;
2179         PyObject* item;
2180         
2181         /* Use existing module where possible */
2182         m = PyImport_ImportModule( "GameKeys" );
2183         if(m) {
2184                 Py_DECREF(m);
2185                 return m;
2186         }
2187         else {
2188                 PyErr_Clear();
2189         
2190                 // Create the module and add the functions
2191                 m = PyModule_Create(&GameKeys_module_def);
2192                 PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m);
2193         }
2194
2195         // Add some symbolic constants to the module
2196         d = PyModule_GetDict(m);
2197
2198         // XXXX Add constants here
2199
2200         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
2201         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
2202         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
2203         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
2204         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
2205         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
2206         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
2207         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
2208         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
2209         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
2210         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
2211         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
2212         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
2213         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
2214         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
2215         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
2216         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
2217         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
2218         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
2219         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
2220         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
2221         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
2222         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
2223         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
2224         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
2225         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
2226         
2227         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);              
2228         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);                
2229         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);                
2230         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
2231         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);              
2232         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);              
2233         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);                
2234         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
2235         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
2236         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);              
2237                 
2238         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
2239                 
2240         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);      
2241         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);                
2242         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);      
2243         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);    
2244         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);  
2245         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
2246                 
2247         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
2248         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
2249         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
2250         KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY);
2251         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
2252         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);              
2253         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
2254         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
2255         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
2256         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);          
2257         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);            
2258         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);            
2259         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);        
2260         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);            
2261         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);            
2262         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
2263         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);            
2264         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);        
2265         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);      
2266                 
2267         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
2268         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
2269         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);  
2270         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);                
2271         
2272         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
2273         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
2274         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
2275         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
2276                 
2277         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
2278         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
2279         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
2280         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
2281         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
2282                 
2283         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
2284         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
2285         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
2286                 
2287                 
2288         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
2289         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
2290         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
2291         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
2292                 
2293                 
2294         KX_MACRO_addTypesToDict(d, F1KEY , SCA_IInputDevice::KX_F1KEY);
2295         KX_MACRO_addTypesToDict(d, F2KEY , SCA_IInputDevice::KX_F2KEY);
2296         KX_MACRO_addTypesToDict(d, F3KEY , SCA_IInputDevice::KX_F3KEY);
2297         KX_MACRO_addTypesToDict(d, F4KEY , SCA_IInputDevice::KX_F4KEY);
2298         KX_MACRO_addTypesToDict(d, F5KEY , SCA_IInputDevice::KX_F5KEY);
2299         KX_MACRO_addTypesToDict(d, F6KEY , SCA_IInputDevice::KX_F6KEY);
2300         KX_MACRO_addTypesToDict(d, F7KEY , SCA_IInputDevice::KX_F7KEY);
2301         KX_MACRO_addTypesToDict(d, F8KEY , SCA_IInputDevice::KX_F8KEY);
2302         KX_MACRO_addTypesToDict(d, F9KEY , SCA_IInputDevice::KX_F9KEY);
2303         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
2304         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
2305         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
2306         KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY);
2307         KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY);
2308         KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY);
2309         KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY);
2310         KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY);
2311         KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY);
2312         KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY);
2313                 
2314         KX_MACRO_addTypesToDict(d, PAUSEKEY, SCA_IInputDevice::KX_PAUSEKEY);
2315         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
2316         KX_MACRO_addTypesToDict(d, HOMEKEY , SCA_IInputDevice::KX_HOMEKEY);
2317         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
2318         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
2319         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
2320
2321         // MOUSE
2322         KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE);
2323         KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE);
2324         KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE);
2325         KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE);
2326         KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE);
2327         KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX);
2328         KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY);
2329
2330         // Check for errors
2331         if (PyErr_Occurred())
2332     {
2333                 Py_FatalError("can't initialize module GameKeys");
2334     }
2335
2336         return d;
2337 }
2338
2339 PyObject* initMathutils()
2340 {
2341         return BPyInit_mathutils();
2342 }
2343
2344 PyObject* initGeometry()
2345 {
2346         return BPyInit_mathutils_geometry();
2347 }
2348
2349 PyObject* initBGL()
2350 {
2351         return BPyInit_bgl();
2352 }
2353
2354 PyObject* initBLF()
2355 {
2356         return BPyInit_blf();
2357 }
2358
2359 // utility function for loading and saving the globalDict
2360 int saveGamePythonConfig( char **marshal_buffer)
2361 {
2362         int marshal_length = 0;
2363         PyObject* gameLogic = PyImport_ImportModule("GameLogic");
2364         if (gameLogic) {
2365                 PyObject* pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
2366                 if (pyGlobalDict) {
2367 #ifdef Py_MARSHAL_VERSION       
2368                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
2369 #else
2370                         PyObject* pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict ); 
2371 #endif
2372                         if (pyGlobalDictMarshal) {
2373                                 // for testing only
2374                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
2375                                 char *marshal_cstring;
2376                                 
2377                                 marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays
2378                                 marshal_length= PyBytes_Size(pyGlobalDictMarshal);
2379                                 *marshal_buffer = new char[marshal_length + 1];
2380                                 memcpy(*marshal_buffer, marshal_cstring, marshal_length);
2381                                 Py_DECREF(pyGlobalDictMarshal);
2382                         } else {
2383                                 printf("Error, bge.logic.globalDict could not be marshal'd\n");
2384                         }
2385                 } else {
2386                         printf("Error, bge.logic.globalDict was removed\n");
2387                 }
2388                 Py_DECREF(gameLogic);
2389         } else {
2390                 PyErr_Clear();
2391                 printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2392         }
2393         return marshal_length;
2394 }
2395
2396 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
2397 {
2398         /* Restore the dict */
2399         if (marshal_buffer) {
2400                 PyObject* gameLogic = PyImport_ImportModule("GameLogic");
2401
2402                 if (gameLogic) {
2403                         PyObject* pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
2404                         if (pyGlobalDict) {
2405                                 PyObject* pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
2406                                 if (pyGlobalDict_orig) {
2407                                         PyDict_Clear(pyGlobalDict_orig);
2408                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
2409                                 } else {
2410                                         /* this should not happen, but cant find the original globalDict, just assign it then */
2411                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2412                                 }
2413                                 Py_DECREF(gameLogic);
2414                                 Py_DECREF(pyGlobalDict);
2415                                 return 1;
2416                         } else {
2417                                 Py_DECREF(gameLogic);
2418                                 PyErr_Clear();
2419                                 printf("Error could not marshall string\n");
2420                         }
2421                 } else {
2422                         PyErr_Clear();
2423                         printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2424                 }       
2425         }
2426         return 0;
2427 }
2428
2429 void pathGamePythonConfig( char *path )
2430 {
2431         int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename
2432         
2433         BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig));
2434
2435         /* replace extension */
2436         if (BLI_testextensie(path, ".blend")) {
2437                 strcpy(path+(len-6), ".bgeconf");
2438         } else {
2439                 strcpy(path+len, ".bgeconf");
2440         }
2441 }
2442
2443 void setGamePythonPath(char *path)
2444 {
2445         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
2446         BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */
2447         
2448         if (gp_GamePythonPathOrig[0] == '\0')
2449                 BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig));
2450 }
2451
2452 // we need this so while blender is open (not blenderplayer)
2453 // loading new blendfiles will reset this on starting the
2454 // engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig
2455 void resetGamePythonPath()
2456 {
2457         gp_GamePythonPathOrig[0] = '\0';
2458 }
2459
2460 #endif // WITH_PYTHON