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