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