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