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