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