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