BGE: Cleaning up the vsync code a little.
[blender-staging.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 directoty (%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_TEXFACE_MATERIAL                             0
1230 #define KX_BLENDER_MULTITEX_MATERIAL    1
1231 #define KX_BLENDER_GLSL_MATERIAL                2
1232
1233 static PyObject *gPySetMaterialType(PyObject *,
1234                                     PyObject *args,
1235                                     PyObject *)
1236 {
1237         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1238         int type;
1239
1240         if (!PyArg_ParseTuple(args,"i:setMaterialType",&type))
1241                 return NULL;
1242
1243         if (type == KX_BLENDER_GLSL_MATERIAL)
1244                 gs->matmode= GAME_MAT_GLSL;
1245         else if (type == KX_BLENDER_MULTITEX_MATERIAL)
1246                 gs->matmode= GAME_MAT_MULTITEX;
1247         else if (type == KX_TEXFACE_MATERIAL)
1248                 gs->matmode= GAME_MAT_TEXFACE;
1249         else {
1250                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMaterialType(int): material type is not known");
1251                 return NULL;
1252         }
1253
1254         Py_RETURN_NONE;
1255 }
1256
1257 static PyObject *gPyGetMaterialType(PyObject *)
1258 {
1259         GlobalSettings *gs= gp_KetsjiEngine->GetGlobalSettings();
1260         int flag;
1261
1262         if (gs->matmode == GAME_MAT_GLSL)
1263                 flag = KX_BLENDER_GLSL_MATERIAL;
1264         else if (gs->matmode == GAME_MAT_MULTITEX)
1265                 flag = KX_BLENDER_MULTITEX_MATERIAL;
1266         else
1267                 flag = KX_TEXFACE_MATERIAL;
1268         
1269         return PyLong_FromLong(flag);
1270 }
1271
1272 static PyObject *gPySetAnisotropicFiltering(PyObject *, PyObject *args)
1273 {
1274         short level;
1275
1276         if (!PyArg_ParseTuple(args, "h:setAnisotropicFiltering", &level))
1277                 return NULL;
1278
1279         if (level != 1 && level != 2 && level != 4 && level != 8 && level != 16) {
1280                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setAnisotropicFiltering(level): Expected value of 1, 2, 4, 8, or 16 for value");
1281                 return NULL;
1282         }
1283
1284         gp_Rasterizer->SetAnisotropicFiltering(level);
1285
1286         Py_RETURN_NONE;
1287 }
1288
1289 static PyObject *gPyGetAnisotropicFiltering(PyObject *, PyObject *args)
1290 {
1291         return PyLong_FromLong(gp_Rasterizer->GetAnisotropicFiltering());
1292 }
1293
1294 static PyObject *gPyDrawLine(PyObject *, PyObject *args)
1295 {
1296         PyObject *ob_from;
1297         PyObject *ob_to;
1298         PyObject *ob_color;
1299
1300         if (!gp_Rasterizer) {
1301                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.drawLine(obFrom, obTo, color): Rasterizer not available");
1302                 return NULL;
1303         }
1304
1305         if (!PyArg_ParseTuple(args,"OOO:drawLine",&ob_from,&ob_to,&ob_color))
1306                 return NULL;
1307
1308         MT_Vector3 from;
1309         MT_Vector3 to;
1310         MT_Vector3 color;
1311         if (!PyVecTo(ob_from, from))
1312                 return NULL;
1313         if (!PyVecTo(ob_to, to))
1314                 return NULL;
1315         if (!PyVecTo(ob_color, color))
1316                 return NULL;
1317
1318         gp_Rasterizer->DrawDebugLine(from,to,color);
1319         
1320         Py_RETURN_NONE;
1321 }
1322
1323 static PyObject *gPySetWindowSize(PyObject *, PyObject *args)
1324 {
1325         int width, height;
1326         if (!PyArg_ParseTuple(args, "ii:resize", &width, &height))
1327                 return NULL;
1328
1329         gp_Canvas->ResizeWindow(width, height);
1330         Py_RETURN_NONE;
1331 }
1332
1333 static PyObject *gPySetFullScreen(PyObject *, PyObject *value)
1334 {
1335         gp_Canvas->SetFullScreen(PyObject_IsTrue(value));
1336         Py_RETURN_NONE;
1337 }
1338
1339 static PyObject *gPyGetFullScreen(PyObject *)
1340 {
1341         return PyBool_FromLong(gp_Canvas->GetFullScreen());
1342 }
1343
1344 static PyObject *gPySetMipmapping(PyObject *, PyObject *args)
1345 {
1346         int val = 0;
1347
1348         if (!PyArg_ParseTuple(args, "i:setMipmapping", &val))
1349                 return NULL;
1350
1351         if (val < 0 || val > RAS_IRasterizer::RAS_MIPMAP_MAX) {
1352                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setMipmapping(val): invalid mipmaping option");
1353                 return NULL;
1354         }
1355
1356         if (!gp_Rasterizer) {
1357                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.setMipmapping(val): Rasterizer not available");
1358                 return NULL;
1359         }
1360
1361         gp_Rasterizer->SetMipmapping((RAS_IRasterizer::MipmapOption)val);
1362         Py_RETURN_NONE;
1363 }
1364
1365 static PyObject *gPyGetMipmapping(PyObject *)
1366 {
1367         if (!gp_Rasterizer) {
1368                 PyErr_SetString(PyExc_RuntimeError, "Rasterizer.getMipmapping(): Rasterizer not available");
1369                 return NULL;
1370         }
1371         return PyLong_FromLong(gp_Rasterizer->GetMipmapping());
1372 }
1373
1374 static PyObject *gPySetVsync(PyObject *, PyObject *args)
1375 {
1376         int interval;
1377
1378         if (!PyArg_ParseTuple(args, "i:setVsync", &interval))
1379                 return NULL;
1380
1381         if (interval < 0 || interval > VSYNC_ADAPTIVE) {
1382                 PyErr_SetString(PyExc_ValueError, "Rasterizer.setVsync(value): value must be VSYNC_OFF, VSYNC_ON, or VSYNC_ADAPTIVE");
1383                 return NULL;
1384         }
1385
1386         if (interval == VSYNC_ADAPTIVE)
1387                 interval = -1;
1388         gp_Canvas->SetSwapInterval((interval == VSYNC_ON) ? 1 : 0);
1389         Py_RETURN_NONE;
1390 }
1391
1392 static PyObject *gPyGetVsync(PyObject *)
1393 {
1394         return PyLong_FromLong(gp_Canvas->GetSwapInterval());
1395 }
1396
1397 static struct PyMethodDef rasterizer_methods[] = {
1398         {"getWindowWidth",(PyCFunction) gPyGetWindowWidth,
1399          METH_VARARGS, "getWindowWidth doc"},
1400         {"getWindowHeight",(PyCFunction) gPyGetWindowHeight,
1401          METH_VARARGS, "getWindowHeight doc"},
1402         {"makeScreenshot",(PyCFunction)gPyMakeScreenshot,
1403          METH_VARARGS, "make Screenshot doc"},
1404         {"enableVisibility",(PyCFunction) gPyEnableVisibility,
1405          METH_VARARGS, "enableVisibility doc"},
1406         {"showMouse",(PyCFunction) gPyShowMouse,
1407          METH_VARARGS, "showMouse(bool visible)"},
1408         {"setMousePosition",(PyCFunction) gPySetMousePosition,
1409          METH_VARARGS, "setMousePosition(int x,int y)"},
1410         {"setBackgroundColor",(PyCFunction)gPySetBackgroundColor,METH_O,"set Background Color (rgb)"},
1411         {"setAmbientColor",(PyCFunction)gPySetAmbientColor,METH_O,"set Ambient Color (rgb)"},
1412         {"disableMist",(PyCFunction)gPyDisableMist,METH_NOARGS,"turn off mist"},
1413         {"setMistColor",(PyCFunction)gPySetMistColor,METH_O,"set Mist Color (rgb)"},
1414         {"setMistStart",(PyCFunction)gPySetMistStart,METH_VARARGS,"set Mist Start(rgb)"},
1415         {"setMistEnd",(PyCFunction)gPySetMistEnd,METH_VARARGS,"set Mist End(rgb)"},
1416         {"enableMotionBlur",(PyCFunction)gPyEnableMotionBlur,METH_VARARGS,"enable motion blur"},
1417         {"disableMotionBlur",(PyCFunction)gPyDisableMotionBlur,METH_NOARGS,"disable motion blur"},
1418
1419         {"setEyeSeparation", (PyCFunction) gPySetEyeSeparation, METH_VARARGS, "set the eye separation for stereo mode"},
1420         {"getEyeSeparation", (PyCFunction) gPyGetEyeSeparation, METH_NOARGS, "get the eye separation for stereo mode"},
1421         {"setFocalLength", (PyCFunction) gPySetFocalLength, METH_VARARGS, "set the focal length for stereo mode"},
1422         {"getFocalLength", (PyCFunction) gPyGetFocalLength, METH_VARARGS, "get the focal length for stereo mode"},
1423         {"setMaterialMode",(PyCFunction) gPySetMaterialType,
1424          METH_VARARGS, "set the material mode to use for OpenGL rendering"},
1425         {"getMaterialMode",(PyCFunction) gPyGetMaterialType,
1426          METH_NOARGS, "get the material mode being used for OpenGL rendering"},
1427         {"setGLSLMaterialSetting",(PyCFunction) gPySetGLSLMaterialSetting,
1428          METH_VARARGS, "set the state of a GLSL material setting"},
1429         {"getGLSLMaterialSetting",(PyCFunction) gPyGetGLSLMaterialSetting,
1430          METH_VARARGS, "get the state of a GLSL material setting"},
1431         {"setAnisotropicFiltering", (PyCFunction) gPySetAnisotropicFiltering,
1432          METH_VARARGS, "set the anisotropic filtering level (must be one of 1, 2, 4, 8, 16)"},
1433         {"getAnisotropicFiltering", (PyCFunction) gPyGetAnisotropicFiltering,
1434          METH_VARARGS, "get the anisotropic filtering level"},
1435         {"drawLine", (PyCFunction) gPyDrawLine,
1436          METH_VARARGS, "draw a line on the screen"},
1437         {"setWindowSize", (PyCFunction) gPySetWindowSize, METH_VARARGS, ""},
1438         {"setFullScreen", (PyCFunction) gPySetFullScreen, METH_O, ""},
1439         {"getFullScreen", (PyCFunction) gPyGetFullScreen, METH_NOARGS, ""},
1440         {"setMipmapping", (PyCFunction) gPySetMipmapping, METH_VARARGS, ""},
1441         {"getMipmapping", (PyCFunction) gPyGetMipmapping, METH_NOARGS, ""},
1442         {"setVsync", (PyCFunction) gPySetVsync, METH_VARARGS, ""},
1443         {"getVsync", (PyCFunction) gPyGetVsync, METH_NOARGS, ""},
1444         { NULL, (PyCFunction) NULL, 0, NULL }
1445 };
1446
1447 // Initialization function for the module (*must* be called initGameLogic)
1448
1449 static char GameLogic_module_documentation[] =
1450 "This is the Python API for the game engine of bge.logic"
1451 ;
1452
1453 static char Rasterizer_module_documentation[] =
1454 "This is the Python API for the game engine of Rasterizer"
1455 ;
1456
1457 static struct PyModuleDef GameLogic_module_def = {
1458         {}, /* m_base */
1459         "GameLogic",  /* m_name */
1460         GameLogic_module_documentation,  /* m_doc */
1461         0,  /* m_size */
1462         game_methods,  /* m_methods */
1463         0,  /* m_reload */
1464         0,  /* m_traverse */
1465         0,  /* m_clear */
1466         0,  /* m_free */
1467 };
1468
1469 PyObject *initGameLogic(KX_KetsjiEngine *engine, KX_Scene* scene) // quick hack to get gravity hook
1470 {
1471         PyObject *m;
1472         PyObject *d;
1473         PyObject *item; /* temp PyObject *storage */
1474         
1475         gp_KetsjiEngine = engine;
1476         gp_KetsjiScene = scene;
1477
1478         gUseVisibilityTemp=false;
1479         
1480         PyObjectPlus::ClearDeprecationWarning(); /* Not that nice to call here but makes sure warnings are reset between loading scenes */
1481         
1482         /* Use existing module where possible
1483          * be careful not to init any runtime vars after this */
1484         m = PyImport_ImportModule( "GameLogic" );
1485         if (m) {
1486                 Py_DECREF(m);
1487                 return m;
1488         }
1489         else {
1490                 PyErr_Clear();
1491                 // Create the module and add the functions
1492                 m = PyModule_Create(&GameLogic_module_def);
1493                 PyDict_SetItemString(PySys_GetObject("modules"), GameLogic_module_def.m_name, m);
1494         }
1495         
1496         // Add some symbolic constants to the module
1497         d = PyModule_GetDict(m);
1498         
1499         // can be overwritten later for gameEngine instances that can load new blend files and re-initialize this module
1500         // for now its safe to make sure it exists for other areas such as the web plugin
1501         
1502         PyDict_SetItemString(d, "globalDict", item=PyDict_New()); Py_DECREF(item);
1503
1504         // Add keyboard and mouse attributes to this module
1505         MT_assert(!gp_PythonKeyboard);
1506         gp_PythonKeyboard = new SCA_PythonKeyboard(gp_KetsjiEngine->GetKeyboardDevice());
1507         PyDict_SetItemString(d, "keyboard", gp_PythonKeyboard->NewProxy(true));
1508
1509         MT_assert(!gp_PythonMouse);
1510         gp_PythonMouse = new SCA_PythonMouse(gp_KetsjiEngine->GetMouseDevice(), gp_Canvas);
1511         PyDict_SetItemString(d, "mouse", gp_PythonMouse->NewProxy(true));
1512
1513         PyObject* joylist = PyList_New(JOYINDEX_MAX);
1514         for (int i=0; i<JOYINDEX_MAX; ++i) {
1515                 SCA_Joystick* joy = SCA_Joystick::GetInstance(i);
1516                 if (joy && joy->Connected()) {
1517                         gp_PythonJoysticks[i] = new SCA_PythonJoystick(joy);
1518                         PyObject* tmp = gp_PythonJoysticks[i]->NewProxy(true);
1519                         Py_INCREF(tmp);
1520                         PyList_SET_ITEM(joylist, i, tmp);
1521                 } else  {
1522                         joy->ReleaseInstance();
1523                         Py_INCREF(Py_None);
1524                         PyList_SET_ITEM(joylist, i, Py_None);
1525                 }
1526         }
1527         PyDict_SetItemString(d, "joysticks", joylist);
1528
1529         ErrorObject = PyUnicode_FromString("GameLogic.error");
1530         PyDict_SetItemString(d, "error", ErrorObject);
1531         Py_DECREF(ErrorObject);
1532         
1533         // XXXX Add constants here
1534         /* To use logic bricks, we need some sort of constants. Here, we associate */
1535         /* constants and sumbolic names. Add them to dictionary d.                 */
1536
1537         /* 1. true and false: needed for everyone                                  */
1538         KX_MACRO_addTypesToDict(d, KX_TRUE,  SCA_ILogicBrick::KX_TRUE);
1539         KX_MACRO_addTypesToDict(d, KX_FALSE, SCA_ILogicBrick::KX_FALSE);
1540
1541         /* 2. Property sensor                                                      */
1542         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EQUAL,      SCA_PropertySensor::KX_PROPSENSOR_EQUAL);
1543         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_NOTEQUAL,   SCA_PropertySensor::KX_PROPSENSOR_NOTEQUAL);
1544         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_INTERVAL,   SCA_PropertySensor::KX_PROPSENSOR_INTERVAL);
1545         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_CHANGED,    SCA_PropertySensor::KX_PROPSENSOR_CHANGED);
1546         KX_MACRO_addTypesToDict(d, KX_PROPSENSOR_EXPRESSION, SCA_PropertySensor::KX_PROPSENSOR_EXPRESSION);
1547
1548         /* 3. Constraint actuator                                                  */
1549         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCX);
1550         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCY);
1551         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCZ);
1552         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTX);
1553         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTY);
1554         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ROTZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ROTZ);
1555         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPX);
1556         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPY);
1557         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRPZ);
1558         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNX);
1559         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNY);
1560         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DIRNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DIRNZ);
1561         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIX);
1562         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIY);
1563         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_ORIZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_ORIZ);
1564         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPX);
1565         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPY);
1566         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHPZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHPZ);
1567         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNX, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNX);
1568         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNY, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNY);
1569         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_FHNZ, KX_ConstraintActuator::KX_ACT_CONSTRAINT_FHNZ);
1570         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_NORMAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_NORMAL);
1571         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_MATERIAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_MATERIAL);
1572         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_PERMANENT, KX_ConstraintActuator::KX_ACT_CONSTRAINT_PERMANENT);
1573         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DISTANCE, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DISTANCE);
1574         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_LOCAL, KX_ConstraintActuator::KX_ACT_CONSTRAINT_LOCAL);
1575         KX_MACRO_addTypesToDict(d, KX_CONSTRAINTACT_DOROTFH, KX_ConstraintActuator::KX_ACT_CONSTRAINT_DOROTFH);
1576
1577         /* 4. Random distribution types                                            */
1578         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_CONST,      SCA_RandomActuator::KX_RANDOMACT_BOOL_CONST);
1579         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_UNIFORM,    SCA_RandomActuator::KX_RANDOMACT_BOOL_UNIFORM);
1580         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_BOOL_BERNOUILLI, SCA_RandomActuator::KX_RANDOMACT_BOOL_BERNOUILLI);
1581         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_CONST,       SCA_RandomActuator::KX_RANDOMACT_INT_CONST);
1582         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_UNIFORM,     SCA_RandomActuator::KX_RANDOMACT_INT_UNIFORM);
1583         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_INT_POISSON,     SCA_RandomActuator::KX_RANDOMACT_INT_POISSON);
1584         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_CONST,     SCA_RandomActuator::KX_RANDOMACT_FLOAT_CONST);
1585         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_UNIFORM,   SCA_RandomActuator::KX_RANDOMACT_FLOAT_UNIFORM);
1586         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NORMAL,    SCA_RandomActuator::KX_RANDOMACT_FLOAT_NORMAL);
1587         KX_MACRO_addTypesToDict(d, KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL, SCA_RandomActuator::KX_RANDOMACT_FLOAT_NEGATIVE_EXPONENTIAL);
1588
1589         /* 5. Sound actuator                                                      */
1590         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP,              KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1591         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND,               KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1592         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP,              KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1593         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND,               KX_SoundActuator::KX_SOUNDACT_LOOPEND);
1594         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1595         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP,     KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1596
1597         /* 6. Action actuator                                                                                                      */
1598         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PLAY,        ACT_ACTION_PLAY);
1599         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PINGPONG,    ACT_ACTION_PINGPONG);
1600         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_FLIPPER,     ACT_ACTION_FLIPPER);
1601         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPSTOP,    ACT_ACTION_LOOP_STOP);
1602         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_LOOPEND,     ACT_ACTION_LOOP_END);
1603         KX_MACRO_addTypesToDict(d, KX_ACTIONACT_PROPERTY,    ACT_ACTION_FROM_PROP);
1604         
1605         /* 7. GL_BlendFunc */
1606         KX_MACRO_addTypesToDict(d, BL_ZERO, GL_ZERO);
1607         KX_MACRO_addTypesToDict(d, BL_ONE, GL_ONE);
1608         KX_MACRO_addTypesToDict(d, BL_SRC_COLOR, GL_SRC_COLOR);
1609         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR);
1610         KX_MACRO_addTypesToDict(d, BL_DST_COLOR, GL_DST_COLOR);
1611         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR);
1612         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA, GL_SRC_ALPHA);
1613         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1614         KX_MACRO_addTypesToDict(d, BL_DST_ALPHA, GL_DST_ALPHA);
1615         KX_MACRO_addTypesToDict(d, BL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
1616         KX_MACRO_addTypesToDict(d, BL_SRC_ALPHA_SATURATE, GL_SRC_ALPHA_SATURATE);
1617
1618
1619         /* 8. UniformTypes */
1620         KX_MACRO_addTypesToDict(d, SHD_TANGENT, BL_Shader::SHD_TANGENT);
1621         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX, BL_Shader::MODELVIEWMATRIX);
1622         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_TRANSPOSE, BL_Shader::MODELVIEWMATRIX_TRANSPOSE);
1623         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSE, BL_Shader::MODELVIEWMATRIX_INVERSE);
1624         KX_MACRO_addTypesToDict(d, MODELVIEWMATRIX_INVERSETRANSPOSE, BL_Shader::MODELVIEWMATRIX_INVERSETRANSPOSE);
1625         KX_MACRO_addTypesToDict(d, MODELMATRIX, BL_Shader::MODELMATRIX);
1626         KX_MACRO_addTypesToDict(d, MODELMATRIX_TRANSPOSE, BL_Shader::MODELMATRIX_TRANSPOSE);
1627         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSE, BL_Shader::MODELMATRIX_INVERSE);
1628         KX_MACRO_addTypesToDict(d, MODELMATRIX_INVERSETRANSPOSE, BL_Shader::MODELMATRIX_INVERSETRANSPOSE);
1629         KX_MACRO_addTypesToDict(d, VIEWMATRIX, BL_Shader::VIEWMATRIX);
1630         KX_MACRO_addTypesToDict(d, VIEWMATRIX_TRANSPOSE, BL_Shader::VIEWMATRIX_TRANSPOSE);
1631         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSE, BL_Shader::VIEWMATRIX_INVERSE);
1632         KX_MACRO_addTypesToDict(d, VIEWMATRIX_INVERSETRANSPOSE, BL_Shader::VIEWMATRIX_INVERSETRANSPOSE);
1633         KX_MACRO_addTypesToDict(d, CAM_POS, BL_Shader::CAM_POS);
1634         KX_MACRO_addTypesToDict(d, CONSTANT_TIMER, BL_Shader::CONSTANT_TIMER);
1635
1636         /* 9. state actuator */
1637         KX_MACRO_addTypesToDict(d, KX_STATE1, (1<<0));
1638         KX_MACRO_addTypesToDict(d, KX_STATE2, (1<<1));
1639         KX_MACRO_addTypesToDict(d, KX_STATE3, (1<<2));
1640         KX_MACRO_addTypesToDict(d, KX_STATE4, (1<<3));
1641         KX_MACRO_addTypesToDict(d, KX_STATE5, (1<<4));
1642         KX_MACRO_addTypesToDict(d, KX_STATE6, (1<<5));
1643         KX_MACRO_addTypesToDict(d, KX_STATE7, (1<<6));
1644         KX_MACRO_addTypesToDict(d, KX_STATE8, (1<<7));
1645         KX_MACRO_addTypesToDict(d, KX_STATE9, (1<<8));
1646         KX_MACRO_addTypesToDict(d, KX_STATE10, (1<<9));
1647         KX_MACRO_addTypesToDict(d, KX_STATE11, (1<<10));
1648         KX_MACRO_addTypesToDict(d, KX_STATE12, (1<<11));
1649         KX_MACRO_addTypesToDict(d, KX_STATE13, (1<<12));
1650         KX_MACRO_addTypesToDict(d, KX_STATE14, (1<<13));
1651         KX_MACRO_addTypesToDict(d, KX_STATE15, (1<<14));
1652         KX_MACRO_addTypesToDict(d, KX_STATE16, (1<<15));
1653         KX_MACRO_addTypesToDict(d, KX_STATE17, (1<<16));
1654         KX_MACRO_addTypesToDict(d, KX_STATE18, (1<<17));
1655         KX_MACRO_addTypesToDict(d, KX_STATE19, (1<<18));
1656         KX_MACRO_addTypesToDict(d, KX_STATE20, (1<<19));
1657         KX_MACRO_addTypesToDict(d, KX_STATE21, (1<<20));
1658         KX_MACRO_addTypesToDict(d, KX_STATE22, (1<<21));
1659         KX_MACRO_addTypesToDict(d, KX_STATE23, (1<<22));
1660         KX_MACRO_addTypesToDict(d, KX_STATE24, (1<<23));
1661         KX_MACRO_addTypesToDict(d, KX_STATE25, (1<<24));
1662         KX_MACRO_addTypesToDict(d, KX_STATE26, (1<<25));
1663         KX_MACRO_addTypesToDict(d, KX_STATE27, (1<<26));
1664         KX_MACRO_addTypesToDict(d, KX_STATE28, (1<<27));
1665         KX_MACRO_addTypesToDict(d, KX_STATE29, (1<<28));
1666         KX_MACRO_addTypesToDict(d, KX_STATE30, (1<<29));
1667         
1668         /* All Sensors */
1669         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_ACTIVATED, SCA_ISensor::KX_SENSOR_JUST_ACTIVATED);
1670         KX_MACRO_addTypesToDict(d, KX_SENSOR_ACTIVE, SCA_ISensor::KX_SENSOR_ACTIVE);
1671         KX_MACRO_addTypesToDict(d, KX_SENSOR_JUST_DEACTIVATED, SCA_ISensor::KX_SENSOR_JUST_DEACTIVATED);
1672         KX_MACRO_addTypesToDict(d, KX_SENSOR_INACTIVE, SCA_ISensor::KX_SENSOR_INACTIVE);
1673         
1674         /* Radar Sensor */
1675         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_X, KX_RadarSensor::KX_RADAR_AXIS_POS_X);
1676         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Y, KX_RadarSensor::KX_RADAR_AXIS_POS_Y);
1677         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_POS_Z, KX_RadarSensor::KX_RADAR_AXIS_POS_Z);
1678         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_X, KX_RadarSensor::KX_RADAR_AXIS_NEG_X);
1679         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Y, KX_RadarSensor::KX_RADAR_AXIS_NEG_Y);
1680         KX_MACRO_addTypesToDict(d, KX_RADAR_AXIS_NEG_Z, KX_RadarSensor::KX_RADAR_AXIS_NEG_Z);
1681
1682         /* Ray Sensor */
1683         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_X, KX_RaySensor::KX_RAY_AXIS_POS_X);
1684         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Y, KX_RaySensor::KX_RAY_AXIS_POS_Y);
1685         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_POS_Z, KX_RaySensor::KX_RAY_AXIS_POS_Z);
1686         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_X, KX_RaySensor::KX_RAY_AXIS_NEG_X);
1687         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Y, KX_RaySensor::KX_RAY_AXIS_NEG_Y);
1688         KX_MACRO_addTypesToDict(d, KX_RAY_AXIS_NEG_Z, KX_RaySensor::KX_RAY_AXIS_NEG_Z);
1689
1690         /* Dynamic actuator */
1691         KX_MACRO_addTypesToDict(d, KX_DYN_RESTORE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_RESTORE_DYNAMICS);
1692         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_DYNAMICS, KX_SCA_DynamicActuator::KX_DYN_DISABLE_DYNAMICS);
1693         KX_MACRO_addTypesToDict(d, KX_DYN_ENABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_ENABLE_RIGID_BODY);
1694         KX_MACRO_addTypesToDict(d, KX_DYN_DISABLE_RIGID_BODY, KX_SCA_DynamicActuator::KX_DYN_DISABLE_RIGID_BODY);
1695         KX_MACRO_addTypesToDict(d, KX_DYN_SET_MASS, KX_SCA_DynamicActuator::KX_DYN_SET_MASS);
1696
1697         /* Input & Mouse Sensor */
1698         KX_MACRO_addTypesToDict(d, KX_INPUT_NONE, SCA_InputEvent::KX_NO_INPUTSTATUS);
1699         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_ACTIVATED, SCA_InputEvent::KX_JUSTACTIVATED);
1700         KX_MACRO_addTypesToDict(d, KX_INPUT_ACTIVE, SCA_InputEvent::KX_ACTIVE);
1701         KX_MACRO_addTypesToDict(d, KX_INPUT_JUST_RELEASED, SCA_InputEvent::KX_JUSTRELEASED);
1702         
1703         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_LEFT, SCA_IInputDevice::KX_LEFTMOUSE);
1704         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_MIDDLE, SCA_IInputDevice::KX_MIDDLEMOUSE);
1705         KX_MACRO_addTypesToDict(d, KX_MOUSE_BUT_RIGHT, SCA_IInputDevice::KX_RIGHTMOUSE);
1706
1707         /* 2D Filter Actuator */
1708         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_ENABLED, RAS_2DFilterManager::RAS_2DFILTER_ENABLED);
1709         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DISABLED, RAS_2DFilterManager::RAS_2DFILTER_DISABLED);
1710         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_NOFILTER, RAS_2DFilterManager::RAS_2DFILTER_NOFILTER);
1711         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_MOTIONBLUR, RAS_2DFilterManager::RAS_2DFILTER_MOTIONBLUR);
1712         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_BLUR, RAS_2DFilterManager::RAS_2DFILTER_BLUR);
1713         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SHARPEN, RAS_2DFilterManager::RAS_2DFILTER_SHARPEN);
1714         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_DILATION, RAS_2DFilterManager::RAS_2DFILTER_DILATION);
1715         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_EROSION, RAS_2DFilterManager::RAS_2DFILTER_EROSION);
1716         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_LAPLACIAN, RAS_2DFilterManager::RAS_2DFILTER_LAPLACIAN);
1717         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SOBEL, RAS_2DFilterManager::RAS_2DFILTER_SOBEL);
1718         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_PREWITT, RAS_2DFilterManager::RAS_2DFILTER_PREWITT);
1719         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_GRAYSCALE, RAS_2DFilterManager::RAS_2DFILTER_GRAYSCALE);
1720         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_SEPIA, RAS_2DFilterManager::RAS_2DFILTER_SEPIA);
1721         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_INVERT, RAS_2DFilterManager::RAS_2DFILTER_INVERT);
1722         KX_MACRO_addTypesToDict(d, RAS_2DFILTER_CUSTOMFILTER, RAS_2DFilterManager::RAS_2DFILTER_CUSTOMFILTER);
1723
1724         /* Sound Actuator */
1725         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYSTOP, KX_SoundActuator::KX_SOUNDACT_PLAYSTOP);
1726         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_PLAYEND, KX_SoundActuator::KX_SOUNDACT_PLAYEND);
1727         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPSTOP, KX_SoundActuator::KX_SOUNDACT_LOOPSTOP);
1728         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPEND, KX_SoundActuator:: KX_SOUNDACT_LOOPEND);
1729         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL);
1730         KX_MACRO_addTypesToDict(d, KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP, KX_SoundActuator::KX_SOUNDACT_LOOPBIDIRECTIONAL_STOP);
1731
1732         /* State Actuator */
1733         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CPY, KX_StateActuator::OP_CPY);
1734         KX_MACRO_addTypesToDict(d, KX_STATE_OP_SET, KX_StateActuator::OP_SET);
1735         KX_MACRO_addTypesToDict(d, KX_STATE_OP_CLR, KX_StateActuator::OP_CLR);
1736         KX_MACRO_addTypesToDict(d, KX_STATE_OP_NEG, KX_StateActuator::OP_NEG);
1737
1738         /* Game Actuator Modes */
1739         KX_MACRO_addTypesToDict(d, KX_GAME_LOAD, KX_GameActuator::KX_GAME_LOAD);
1740         KX_MACRO_addTypesToDict(d, KX_GAME_START, KX_GameActuator::KX_GAME_START);
1741         KX_MACRO_addTypesToDict(d, KX_GAME_RESTART, KX_GameActuator::KX_GAME_RESTART);
1742         KX_MACRO_addTypesToDict(d, KX_GAME_QUIT, KX_GameActuator::KX_GAME_QUIT);
1743         KX_MACRO_addTypesToDict(d, KX_GAME_SAVECFG, KX_GameActuator::KX_GAME_SAVECFG);
1744         KX_MACRO_addTypesToDict(d, KX_GAME_LOADCFG, KX_GameActuator::KX_GAME_LOADCFG);
1745
1746         /* Scene Actuator Modes */
1747         KX_MACRO_addTypesToDict(d, KX_SCENE_RESTART, KX_SceneActuator::KX_SCENE_RESTART);
1748         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_SCENE, KX_SceneActuator::KX_SCENE_SET_SCENE);
1749         KX_MACRO_addTypesToDict(d, KX_SCENE_SET_CAMERA, KX_SceneActuator::KX_SCENE_SET_CAMERA);
1750         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_FRONT_SCENE, KX_SceneActuator::KX_SCENE_ADD_FRONT_SCENE);
1751         KX_MACRO_addTypesToDict(d, KX_SCENE_ADD_BACK_SCENE, KX_SceneActuator::KX_SCENE_ADD_BACK_SCENE);
1752         KX_MACRO_addTypesToDict(d, KX_SCENE_REMOVE_SCENE, KX_SceneActuator::KX_SCENE_REMOVE_SCENE);
1753         KX_MACRO_addTypesToDict(d, KX_SCENE_SUSPEND, KX_SceneActuator::KX_SCENE_SUSPEND);
1754         KX_MACRO_addTypesToDict(d, KX_SCENE_RESUME, KX_SceneActuator::KX_SCENE_RESUME);
1755
1756         /* Parent Actuator Modes */
1757         KX_MACRO_addTypesToDict(d, KX_PARENT_SET, KX_ParentActuator::KX_PARENT_SET);
1758         KX_MACRO_addTypesToDict(d, KX_PARENT_REMOVE, KX_ParentActuator::KX_PARENT_REMOVE);
1759
1760         /* BL_ArmatureConstraint type */
1761         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_TRACKTO);
1762         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_KINEMATIC);
1763         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_ROTLIKE, CONSTRAINT_TYPE_ROTLIKE);
1764         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCLIKE, CONSTRAINT_TYPE_LOCLIKE);
1765         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_MINMAX, CONSTRAINT_TYPE_MINMAX);
1766         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_SIZELIKE, CONSTRAINT_TYPE_SIZELIKE);
1767         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_LOCKTRACK);
1768         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_STRETCHTO, CONSTRAINT_TYPE_STRETCHTO);
1769         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_CLAMPTO);
1770         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_TRANSFORM, CONSTRAINT_TYPE_TRANSFORM);
1771         KX_MACRO_addTypesToDict(d, CONSTRAINT_TYPE_DISTLIMIT, CONSTRAINT_TYPE_DISTLIMIT);
1772         /* BL_ArmatureConstraint ik_type */
1773         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_COPYPOSE, CONSTRAINT_IK_COPYPOSE);
1774         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_DISTANCE, CONSTRAINT_IK_DISTANCE);
1775         /* BL_ArmatureConstraint ik_mode */
1776         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_INSIDE, LIMITDIST_INSIDE);
1777         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_OUTSIDE, LIMITDIST_OUTSIDE);
1778         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_MODE_ONSURFACE, LIMITDIST_ONSURFACE);
1779         /* BL_ArmatureConstraint ik_flag */
1780         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_TIP, CONSTRAINT_IK_TIP);
1781         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_ROT, CONSTRAINT_IK_ROT);
1782         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_STRETCH, CONSTRAINT_IK_STRETCH);
1783         KX_MACRO_addTypesToDict(d, CONSTRAINT_IK_FLAG_POS, CONSTRAINT_IK_POS);
1784         /* KX_ArmatureSensor type */
1785         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_STATE_CHANGED, SENS_ARM_STATE_CHANGED);
1786         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_BELOW, SENS_ARM_LIN_ERROR_BELOW);
1787         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_LIN_ERROR_ABOVE, SENS_ARM_LIN_ERROR_ABOVE);
1788         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_BELOW, SENS_ARM_ROT_ERROR_BELOW);
1789         KX_MACRO_addTypesToDict(d, KX_ARMSENSOR_ROT_ERROR_ABOVE, SENS_ARM_ROT_ERROR_ABOVE);
1790
1791         /* BL_ArmatureActuator type */
1792         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_RUN, ACT_ARM_RUN);
1793         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_ENABLE, ACT_ARM_ENABLE);
1794         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_DISABLE, ACT_ARM_DISABLE);
1795         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETTARGET, ACT_ARM_SETTARGET);
1796         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETWEIGHT, ACT_ARM_SETWEIGHT);
1797         KX_MACRO_addTypesToDict(d, KX_ACT_ARMATURE_SETINFLUENCE, ACT_ARM_SETINFLUENCE);
1798
1799         /* BL_Armature Channel rotation_mode */
1800         KX_MACRO_addTypesToDict(d, ROT_MODE_QUAT, ROT_MODE_QUAT);
1801         KX_MACRO_addTypesToDict(d, ROT_MODE_XYZ, ROT_MODE_XYZ);
1802         KX_MACRO_addTypesToDict(d, ROT_MODE_XZY, ROT_MODE_XZY);
1803         KX_MACRO_addTypesToDict(d, ROT_MODE_YXZ, ROT_MODE_YXZ);
1804         KX_MACRO_addTypesToDict(d, ROT_MODE_YZX, ROT_MODE_YZX);
1805         KX_MACRO_addTypesToDict(d, ROT_MODE_ZXY, ROT_MODE_ZXY);
1806         KX_MACRO_addTypesToDict(d, ROT_MODE_ZYX, ROT_MODE_ZYX);
1807
1808         /* Steering actuator */
1809         KX_MACRO_addTypesToDict(d, KX_STEERING_SEEK, KX_SteeringActuator::KX_STEERING_SEEK);
1810         KX_MACRO_addTypesToDict(d, KX_STEERING_FLEE, KX_SteeringActuator::KX_STEERING_FLEE);
1811         KX_MACRO_addTypesToDict(d, KX_STEERING_PATHFOLLOWING, KX_SteeringActuator::KX_STEERING_PATHFOLLOWING);
1812
1813         /* KX_NavMeshObject render mode */
1814         KX_MACRO_addTypesToDict(d, RM_WALLS, KX_NavMeshObject::RM_WALLS);
1815         KX_MACRO_addTypesToDict(d, RM_POLYS, KX_NavMeshObject::RM_POLYS);
1816         KX_MACRO_addTypesToDict(d, RM_TRIS, KX_NavMeshObject::RM_TRIS);
1817
1818         /* BL_Action play modes */
1819         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PLAY, BL_Action::ACT_MODE_PLAY);
1820         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_LOOP, BL_Action::ACT_MODE_LOOP);
1821         KX_MACRO_addTypesToDict(d, KX_ACTION_MODE_PING_PONG, BL_Action::ACT_MODE_PING_PONG);
1822
1823         /* BL_Action blend modes */
1824         KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_BLEND, BL_Action::ACT_BLEND_BLEND);
1825         KX_MACRO_addTypesToDict(d, KX_ACTION_BLEND_ADD, BL_Action::ACT_BLEND_ADD);
1826
1827         // Check for errors
1828         if (PyErr_Occurred())
1829         {
1830                 Py_FatalError("can't initialize module bge.logic");
1831         }
1832
1833         return m;
1834 }
1835
1836 /* Explanation of 
1837  * 
1838  * - backupPySysObjects()               : stores sys.path in gp_OrigPythonSysPath
1839  * - initPySysObjects(main)     : initializes the blendfile and library paths
1840  * - restorePySysObjects()              : restores sys.path from gp_OrigPythonSysPath
1841  * 
1842  * These exist so the current blend dir "//" can always be used to import modules from.
1843  * the reason we need a few functions for this is that python is not only used by the game engine
1844  * so we cant just add to sys.path all the time, it would leave pythons state in a mess.
1845  * It would also be incorrect since loading blend files for new levels etc would always add to sys.path
1846  * 
1847  * To play nice with blenders python, the sys.path is backed up and the current blendfile along
1848  * with all its lib paths are added to the sys path.
1849  * When loading a new blendfile, the original sys.path is restored and the new paths are added over the top.
1850  */
1851
1852 /**
1853  * So we can have external modules mixed with our blend files.
1854  */
1855 static void backupPySysObjects(void)
1856 {
1857         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1858         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1859         
1860         /* paths */
1861         Py_XDECREF(gp_OrigPythonSysPath); /* just in case its set */
1862         gp_OrigPythonSysPath = PyList_GetSlice(sys_path, 0, INT_MAX); /* copy the list */
1863         
1864         /* modules */
1865         Py_XDECREF(gp_OrigPythonSysModules); /* just in case its set */
1866         gp_OrigPythonSysModules = PyDict_Copy(sys_mods); /* copy the list */
1867         
1868 }
1869
1870 /* for initPySysObjects only,
1871  * takes a blend path and adds a scripts dir from it
1872  *
1873  * "/home/me/foo.blend" -> "/home/me/scripts"
1874  */
1875 static void initPySysObjects__append(PyObject *sys_path, const char *filename)
1876 {
1877         PyObject *item;
1878         char expanded[FILE_MAX];
1879         
1880         BLI_split_dir_part(filename, expanded, sizeof(expanded)); /* get the dir part of filename only */
1881         BLI_path_abs(expanded, gp_GamePythonPath); /* filename from lib->filename is (always?) absolute, so this may not be needed but it wont hurt */
1882         BLI_cleanup_file(gp_GamePythonPath, expanded); /* Don't use BLI_cleanup_dir because it adds a slash - BREAKS WIN32 ONLY */
1883         item= PyUnicode_DecodeFSDefault(expanded);
1884         
1885 //      printf("SysPath - '%s', '%s', '%s'\n", expanded, filename, gp_GamePythonPath);
1886         
1887         if (PySequence_Index(sys_path, item) == -1) {
1888                 PyErr_Clear(); /* PySequence_Index sets a ValueError */
1889                 PyList_Insert(sys_path, 0, item);
1890         }
1891         
1892         Py_DECREF(item);
1893 }
1894 static void initPySysObjects(Main *maggie)
1895 {
1896         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1897         
1898         if (gp_OrigPythonSysPath==NULL) {
1899                 /* backup */
1900                 backupPySysObjects();
1901         }
1902         else {
1903                 /* get the original sys path when the BGE started */
1904                 PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1905         }
1906         
1907         Library *lib= (Library *)maggie->library.first;
1908         
1909         while (lib) {
1910                 /* lib->name wont work in some cases (on win32),
1911                  * even when expanding with gp_GamePythonPath, using lib->filename is less trouble */
1912                 initPySysObjects__append(sys_path, lib->filepath);
1913                 lib= (Library *)lib->id.next;
1914         }
1915         
1916         initPySysObjects__append(sys_path, gp_GamePythonPath);
1917         
1918 //      fprintf(stderr, "\nNew Path: %d ", PyList_GET_SIZE(sys_path));
1919 //      PyObject_Print(sys_path, stderr, 0);
1920 }
1921
1922 static void restorePySysObjects(void)
1923 {
1924         if (gp_OrigPythonSysPath==NULL)
1925                 return;
1926         
1927         PyObject *sys_path= PySys_GetObject("path"); /* should never fail */
1928         PyObject *sys_mods= PySys_GetObject("modules"); /* should never fail */
1929
1930         /* paths */
1931         PyList_SetSlice(sys_path, 0, INT_MAX, gp_OrigPythonSysPath);
1932         Py_DECREF(gp_OrigPythonSysPath);
1933         gp_OrigPythonSysPath= NULL;
1934         
1935         /* modules */
1936         PyDict_Clear(sys_mods);
1937         PyDict_Update(sys_mods, gp_OrigPythonSysModules);
1938         Py_DECREF(gp_OrigPythonSysModules);
1939         gp_OrigPythonSysModules= NULL;
1940         
1941         
1942 //      fprintf(stderr, "\nRestore Path: %d ", PyList_GET_SIZE(sys_path));
1943 //      PyObject_Print(sys_path, stderr, 0);
1944 }
1945
1946 void addImportMain(struct Main *maggie)
1947 {
1948         bpy_import_main_extra_add(maggie);
1949 }
1950
1951 void removeImportMain(struct Main *maggie)
1952 {
1953         bpy_import_main_extra_remove(maggie);
1954 }
1955
1956 // Copied from bpy_interface.c
1957 static struct _inittab bge_internal_modules[] = {
1958         {(char *)"mathutils", PyInit_mathutils},
1959         {(char *)"bgl", BPyInit_bgl},
1960         {(char *)"blf", BPyInit_blf},
1961         {(char *)"aud", AUD_initPython},
1962         {NULL, NULL}
1963 };
1964
1965 /**
1966  * Python is not initialized.
1967  * see bpy_interface.c's BPY_python_start() which shares the same functionality in blender.
1968  */
1969 PyObject *initGamePlayerPythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie, int argc, char** argv)
1970 {
1971         /* Yet another gotcha in the py api
1972          * Cant run PySys_SetArgv more than once because this adds the
1973          * binary dir to the sys.path each time.
1974          * Id have thought python being totally restarted would make this ok but
1975          * somehow it remembers the sys.path - Campbell
1976          */
1977         static bool first_time = true;
1978         const char * const py_path_bundle   = BLI_get_folder(BLENDER_SYSTEM_PYTHON, NULL);
1979
1980 #if 0 // TODO - py3
1981         STR_String pname = progname;
1982         Py_SetProgramName(pname.Ptr());
1983 #endif
1984
1985         if (py_path_bundle != NULL) {
1986                 Py_NoSiteFlag = 1;
1987         }
1988
1989         Py_FrozenFlag = 1;
1990
1991         /* must run before python initializes */
1992         PyImport_ExtendInittab(bge_internal_modules);
1993
1994         /* find local python installation */
1995         PyC_SetHomePath(py_path_bundle);
1996
1997         Py_Initialize();
1998         
1999         if (argv && first_time) { /* browser plugins don't currently set this */
2000                 // Until python support ascii again, we use our own.
2001                 // PySys_SetArgv(argc, argv);
2002                 int i;
2003                 PyObject *py_argv= PyList_New(argc);
2004
2005                 for (i=0; i<argc; i++)
2006                         PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
2007
2008                 PySys_SetObject("argv", py_argv);
2009                 Py_DECREF(py_argv);
2010         }
2011         
2012         /* Initialize thread support (also acquires lock) */
2013         PyEval_InitThreads();
2014
2015         bpy_import_init(PyEval_GetBuiltins());
2016
2017         /* mathutils types are used by the BGE even if we don't import them */
2018         {
2019                 PyObject *mod = PyImport_ImportModuleLevel("mathutils", NULL, NULL, NULL, 0);
2020                 Py_DECREF(mod);
2021         }
2022
2023 #ifdef WITH_AUDASPACE
2024         /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
2025         {
2026                 PyObject *mod = PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
2027                 Py_DECREF(mod);
2028         }
2029 #endif
2030
2031         initPyTypes();
2032         
2033         bpy_import_main_set(maggie);
2034         
2035         initPySysObjects(maggie);
2036         
2037         first_time = false;
2038         
2039         PyObjectPlus::ClearDeprecationWarning();
2040
2041         return PyC_DefaultNameSpace(NULL);
2042 }
2043
2044 void exitGamePlayerPythonScripting()
2045 {
2046         /* Clean up the Python mouse and keyboard */
2047         delete gp_PythonKeyboard;
2048         gp_PythonKeyboard = NULL;
2049
2050         delete gp_PythonMouse;
2051         gp_PythonMouse = NULL;
2052
2053         for (int i=0; i<JOYINDEX_MAX; ++i) {
2054                 if (gp_PythonJoysticks[i]) {
2055                         delete gp_PythonJoysticks[i];
2056                         gp_PythonJoysticks[i] = NULL;
2057                 }
2058         }
2059
2060         /* since python restarts we cant let the python backup of the sys.path hang around in a global pointer */
2061         restorePySysObjects(); /* get back the original sys.path and clear the backup */
2062         
2063         Py_Finalize();
2064         bpy_import_main_set(NULL);
2065         PyObjectPlus::ClearDeprecationWarning();
2066 }
2067
2068
2069
2070 /**
2071  * Python is already initialized.
2072  */
2073 PyObject *initGamePythonScripting(const STR_String& progname, TPythonSecurityLevel level, Main *maggie)
2074 {
2075 #if 0 // XXX TODO Py3
2076         STR_String pname = progname;
2077         Py_SetProgramName(pname.Ptr());
2078 #endif
2079
2080 #ifdef WITH_AUDASPACE
2081         /* accessing a SoundActuator's sound results in a crash if aud is not initialized... */
2082         {
2083                 PyObject *mod= PyImport_ImportModuleLevel("aud", NULL, NULL, NULL, 0);
2084                 Py_DECREF(mod);
2085         }
2086 #endif
2087
2088         initPyTypes();
2089         
2090         bpy_import_main_set(maggie);
2091         
2092         initPySysObjects(maggie);
2093
2094         PyObjectPlus::NullDeprecationWarning();
2095
2096         return PyC_DefaultNameSpace(NULL);
2097 }
2098
2099 void exitGamePythonScripting()
2100 {
2101         /* Clean up the Python mouse and keyboard */
2102         delete gp_PythonKeyboard;
2103         gp_PythonKeyboard = NULL;
2104
2105         delete gp_PythonMouse;
2106         gp_PythonMouse = NULL;
2107
2108         for (int i=0; i<JOYINDEX_MAX; ++i) {
2109                 if (gp_PythonJoysticks[i]) {
2110                         delete gp_PythonJoysticks[i];
2111                         gp_PythonJoysticks[i] = NULL;
2112                 }
2113         }
2114
2115         restorePySysObjects(); /* get back the original sys.path and clear the backup */
2116         bpy_import_main_set(NULL);
2117         PyObjectPlus::ClearDeprecationWarning();
2118 }
2119
2120 /* similar to the above functions except it sets up the namespace
2121  * and other more general things */
2122 void setupGamePython(KX_KetsjiEngine* ketsjiengine, KX_Scene *startscene, Main *blenderdata,
2123                      PyObject *pyGlobalDict, PyObject **gameLogic, PyObject **gameLogic_keys, int argc, char** argv)
2124 {
2125         PyObject *dictionaryobject;
2126
2127         if (argv) /* player only */
2128                 dictionaryobject= initGamePlayerPythonScripting("Ketsji", psl_Lowest, blenderdata, argc, argv);
2129         else
2130                 dictionaryobject= initGamePythonScripting("Ketsji", psl_Lowest, blenderdata);
2131
2132         ketsjiengine->SetPyNamespace(dictionaryobject);
2133         initRasterizer(ketsjiengine->GetRasterizer(), ketsjiengine->GetCanvas());
2134         *gameLogic = initGameLogic(ketsjiengine, startscene);
2135
2136         /* is set in initGameLogic so only set here if we want it to persist between scenes */
2137         if (pyGlobalDict)
2138                 PyDict_SetItemString(PyModule_GetDict(*gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2139
2140         *gameLogic_keys = PyDict_Keys(PyModule_GetDict(*gameLogic));
2141
2142         initGameKeys();
2143         initPythonConstraintBinding();
2144         initVideoTexture();
2145
2146         /* could be done a lot more nicely, but for now a quick way to get bge.* working */
2147         PyRun_SimpleString("sys = __import__('sys');"
2148                            "bge = type(sys)('bge');"
2149                            "bge.__dict__.update({'logic':__import__('GameLogic'), "
2150                                                 "'render':__import__('Rasterizer'), "
2151                                                 "'events':__import__('GameKeys'), "
2152                                                 "'constraints':__import__('PhysicsConstraints'), "
2153                                                 "'physics':__import__('PhysicsConstraints'),"
2154                                                 "'types':__import__('GameTypes'), "
2155                                                 "'texture':__import__('VideoTexture')});"
2156                            /* so we can do 'import bge.foo as bar' */
2157                            "sys.modules.update({'bge': bge, "
2158                                                "'bge.logic':bge.logic, "
2159                                                "'bge.render':bge.render, "
2160                                                "'bge.events':bge.events, "
2161                                                "'bge.constraints':bge.constraints, "
2162                                                "'bge.physics':bge.physics,"
2163                                                "'bge.types':bge.types, "
2164                                                "'bge.texture':bge.texture})"
2165                            );
2166 }
2167
2168 static struct PyModuleDef Rasterizer_module_def = {
2169         {}, /* m_base */
2170         "Rasterizer",  /* m_name */
2171         Rasterizer_module_documentation,  /* m_doc */
2172         0,  /* m_size */
2173         rasterizer_methods,  /* m_methods */
2174         0,  /* m_reload */
2175         0,  /* m_traverse */
2176         0,  /* m_clear */
2177         0,  /* m_free */
2178 };
2179
2180 PyObject *initRasterizer(RAS_IRasterizer* rasty,RAS_ICanvas* canvas)
2181 {
2182         gp_Canvas = canvas;
2183         gp_Rasterizer = rasty;
2184
2185
2186         PyObject *m;
2187         PyObject *d;
2188         PyObject *item;
2189
2190         /* Use existing module where possible
2191          * be careful not to init any runtime vars after this */
2192         m = PyImport_ImportModule( "Rasterizer" );
2193         if (m) {
2194                 Py_DECREF(m);
2195                 return m;
2196         }
2197         else {
2198                 PyErr_Clear();
2199
2200                 // Create the module and add the functions
2201                 m = PyModule_Create(&Rasterizer_module_def);
2202                 PyDict_SetItemString(PySys_GetObject("modules"), Rasterizer_module_def.m_name, m);
2203         }
2204
2205         // Add some symbolic constants to the module
2206         d = PyModule_GetDict(m);
2207         ErrorObject = PyUnicode_FromString("Rasterizer.error");
2208         PyDict_SetItemString(d, "error", ErrorObject);
2209         Py_DECREF(ErrorObject);
2210
2211         /* needed for get/setMaterialType */
2212         KX_MACRO_addTypesToDict(d, KX_TEXFACE_MATERIAL, KX_TEXFACE_MATERIAL);
2213         KX_MACRO_addTypesToDict(d, KX_BLENDER_MULTITEX_MATERIAL, KX_BLENDER_MULTITEX_MATERIAL);
2214         KX_MACRO_addTypesToDict(d, KX_BLENDER_GLSL_MATERIAL, KX_BLENDER_GLSL_MATERIAL);
2215
2216         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NONE, RAS_IRasterizer::RAS_MIPMAP_NONE);
2217         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_NEAREST, RAS_IRasterizer::RAS_MIPMAP_NEAREST);
2218         KX_MACRO_addTypesToDict(d, RAS_MIPMAP_LINEAR, RAS_IRasterizer::RAS_MIPMAP_LINEAR);
2219
2220         /* for get/setVsync */
2221         KX_MACRO_addTypesToDict(d, VSYNC_OFF, VSYNC_OFF);
2222         KX_MACRO_addTypesToDict(d, VSYNC_ON, VSYNC_ON);
2223         KX_MACRO_addTypesToDict(d, VSYNC_ADAPTIVE, VSYNC_ADAPTIVE);
2224
2225         // XXXX Add constants here
2226
2227         // Check for errors
2228         if (PyErr_Occurred())
2229         {
2230                 Py_FatalError("can't initialize module Rasterizer");
2231         }
2232
2233         return d;
2234 }
2235
2236
2237
2238 /* ------------------------------------------------------------------------- */
2239 /* GameKeys: symbolic constants for key mapping                              */
2240 /* ------------------------------------------------------------------------- */
2241
2242 static char GameKeys_module_documentation[] =
2243 "This modules provides defines for key-codes"
2244 ;
2245
2246 static char gPyEventToString_doc[] =
2247 "EventToString(event) - Take a valid event from the GameKeys module or Keyboard Sensor and return a name"
2248 ;
2249
2250 static PyObject *gPyEventToString(PyObject *, PyObject *value)
2251 {
2252         PyObject *mod, *dict, *key, *val, *ret = NULL;
2253         Py_ssize_t pos = 0;
2254         
2255         mod = PyImport_ImportModule( "GameKeys" );
2256         if (!mod)
2257                 return NULL;
2258         
2259         dict = PyModule_GetDict(mod);
2260         
2261         while (PyDict_Next(dict, &pos, &key, &val)) {
2262                 if (PyObject_RichCompareBool(value, val, Py_EQ)) {
2263                         ret = key;
2264                         break;
2265                 }
2266         }
2267         
2268         PyErr_Clear(); // in case there was an error clearing
2269         Py_DECREF(mod);
2270         if (!ret)       PyErr_SetString(PyExc_ValueError, "GameKeys.EventToString(int): expected a valid int keyboard event");
2271         else            Py_INCREF(ret);
2272         
2273         return ret;
2274 }
2275
2276 static char gPyEventToCharacter_doc[] =
2277 "EventToCharacter(event, is_shift) - Take a valid event from the GameKeys module or Keyboard Sensor and return a character"
2278 ;
2279
2280 static PyObject *gPyEventToCharacter(PyObject *, PyObject *args)
2281 {
2282         int event, shift;
2283         if (!PyArg_ParseTuple(args,"ii:EventToCharacter", &event, &shift))
2284                 return NULL;
2285         
2286         if (IsPrintable(event)) {
2287                 char ch[2] = {'\0', '\0'};
2288                 ch[0] = ToCharacter(event, (bool)shift);
2289                 return PyUnicode_FromString(ch);
2290         }
2291         else {
2292                 return PyUnicode_FromString("");
2293         }
2294 }
2295
2296
2297 static struct PyMethodDef gamekeys_methods[] = {
2298         {"EventToCharacter", (PyCFunction)gPyEventToCharacter, METH_VARARGS, (const char *)gPyEventToCharacter_doc},
2299         {"EventToString", (PyCFunction)gPyEventToString, METH_O, (const char *)gPyEventToString_doc},
2300         { NULL, (PyCFunction) NULL, 0, NULL }
2301 };
2302
2303 static struct PyModuleDef GameKeys_module_def = {
2304         {}, /* m_base */
2305         "GameKeys",  /* m_name */
2306         GameKeys_module_documentation,  /* m_doc */
2307         0,  /* m_size */
2308         gamekeys_methods,  /* m_methods */
2309         0,  /* m_reload */
2310         0,  /* m_traverse */
2311         0,  /* m_clear */
2312         0,  /* m_free */
2313 };
2314
2315 PyObject *initGameKeys()
2316 {
2317         PyObject *m;
2318         PyObject *d;
2319         PyObject *item;
2320         
2321         /* Use existing module where possible */
2322         m = PyImport_ImportModule( "GameKeys" );
2323         if (m) {
2324                 Py_DECREF(m);
2325                 return m;
2326         }
2327         else {
2328                 PyErr_Clear();
2329         
2330                 // Create the module and add the functions
2331                 m = PyModule_Create(&GameKeys_module_def);
2332                 PyDict_SetItemString(PySys_GetObject("modules"), GameKeys_module_def.m_name, m);
2333         }
2334
2335         // Add some symbolic constants to the module
2336         d = PyModule_GetDict(m);
2337
2338         // XXXX Add constants here
2339
2340         KX_MACRO_addTypesToDict(d, AKEY, SCA_IInputDevice::KX_AKEY);
2341         KX_MACRO_addTypesToDict(d, BKEY, SCA_IInputDevice::KX_BKEY);
2342         KX_MACRO_addTypesToDict(d, CKEY, SCA_IInputDevice::KX_CKEY);
2343         KX_MACRO_addTypesToDict(d, DKEY, SCA_IInputDevice::KX_DKEY);
2344         KX_MACRO_addTypesToDict(d, EKEY, SCA_IInputDevice::KX_EKEY);
2345         KX_MACRO_addTypesToDict(d, FKEY, SCA_IInputDevice::KX_FKEY);
2346         KX_MACRO_addTypesToDict(d, GKEY, SCA_IInputDevice::KX_GKEY);
2347         KX_MACRO_addTypesToDict(d, HKEY, SCA_IInputDevice::KX_HKEY);
2348         KX_MACRO_addTypesToDict(d, IKEY, SCA_IInputDevice::KX_IKEY);
2349         KX_MACRO_addTypesToDict(d, JKEY, SCA_IInputDevice::KX_JKEY);
2350         KX_MACRO_addTypesToDict(d, KKEY, SCA_IInputDevice::KX_KKEY);
2351         KX_MACRO_addTypesToDict(d, LKEY, SCA_IInputDevice::KX_LKEY);
2352         KX_MACRO_addTypesToDict(d, MKEY, SCA_IInputDevice::KX_MKEY);
2353         KX_MACRO_addTypesToDict(d, NKEY, SCA_IInputDevice::KX_NKEY);
2354         KX_MACRO_addTypesToDict(d, OKEY, SCA_IInputDevice::KX_OKEY);
2355         KX_MACRO_addTypesToDict(d, PKEY, SCA_IInputDevice::KX_PKEY);
2356         KX_MACRO_addTypesToDict(d, QKEY, SCA_IInputDevice::KX_QKEY);
2357         KX_MACRO_addTypesToDict(d, RKEY, SCA_IInputDevice::KX_RKEY);
2358         KX_MACRO_addTypesToDict(d, SKEY, SCA_IInputDevice::KX_SKEY);
2359         KX_MACRO_addTypesToDict(d, TKEY, SCA_IInputDevice::KX_TKEY);
2360         KX_MACRO_addTypesToDict(d, UKEY, SCA_IInputDevice::KX_UKEY);
2361         KX_MACRO_addTypesToDict(d, VKEY, SCA_IInputDevice::KX_VKEY);
2362         KX_MACRO_addTypesToDict(d, WKEY, SCA_IInputDevice::KX_WKEY);
2363         KX_MACRO_addTypesToDict(d, XKEY, SCA_IInputDevice::KX_XKEY);
2364         KX_MACRO_addTypesToDict(d, YKEY, SCA_IInputDevice::KX_YKEY);
2365         KX_MACRO_addTypesToDict(d, ZKEY, SCA_IInputDevice::KX_ZKEY);
2366         
2367         KX_MACRO_addTypesToDict(d, ZEROKEY, SCA_IInputDevice::KX_ZEROKEY);
2368         KX_MACRO_addTypesToDict(d, ONEKEY, SCA_IInputDevice::KX_ONEKEY);
2369         KX_MACRO_addTypesToDict(d, TWOKEY, SCA_IInputDevice::KX_TWOKEY);
2370         KX_MACRO_addTypesToDict(d, THREEKEY, SCA_IInputDevice::KX_THREEKEY);
2371         KX_MACRO_addTypesToDict(d, FOURKEY, SCA_IInputDevice::KX_FOURKEY);
2372         KX_MACRO_addTypesToDict(d, FIVEKEY, SCA_IInputDevice::KX_FIVEKEY);
2373         KX_MACRO_addTypesToDict(d, SIXKEY, SCA_IInputDevice::KX_SIXKEY);
2374         KX_MACRO_addTypesToDict(d, SEVENKEY, SCA_IInputDevice::KX_SEVENKEY);
2375         KX_MACRO_addTypesToDict(d, EIGHTKEY, SCA_IInputDevice::KX_EIGHTKEY);
2376         KX_MACRO_addTypesToDict(d, NINEKEY, SCA_IInputDevice::KX_NINEKEY);
2377                 
2378         KX_MACRO_addTypesToDict(d, CAPSLOCKKEY, SCA_IInputDevice::KX_CAPSLOCKKEY);
2379                 
2380         KX_MACRO_addTypesToDict(d, LEFTCTRLKEY, SCA_IInputDevice::KX_LEFTCTRLKEY);
2381         KX_MACRO_addTypesToDict(d, LEFTALTKEY, SCA_IInputDevice::KX_LEFTALTKEY);
2382         KX_MACRO_addTypesToDict(d, RIGHTALTKEY, SCA_IInputDevice::KX_RIGHTALTKEY);
2383         KX_MACRO_addTypesToDict(d, RIGHTCTRLKEY, SCA_IInputDevice::KX_RIGHTCTRLKEY);
2384         KX_MACRO_addTypesToDict(d, RIGHTSHIFTKEY, SCA_IInputDevice::KX_RIGHTSHIFTKEY);
2385         KX_MACRO_addTypesToDict(d, LEFTSHIFTKEY, SCA_IInputDevice::KX_LEFTSHIFTKEY);
2386                 
2387         KX_MACRO_addTypesToDict(d, ESCKEY, SCA_IInputDevice::KX_ESCKEY);
2388         KX_MACRO_addTypesToDict(d, TABKEY, SCA_IInputDevice::KX_TABKEY);
2389         KX_MACRO_addTypesToDict(d, RETKEY, SCA_IInputDevice::KX_RETKEY);
2390         KX_MACRO_addTypesToDict(d, ENTERKEY, SCA_IInputDevice::KX_RETKEY);
2391         KX_MACRO_addTypesToDict(d, SPACEKEY, SCA_IInputDevice::KX_SPACEKEY);
2392         KX_MACRO_addTypesToDict(d, LINEFEEDKEY, SCA_IInputDevice::KX_LINEFEEDKEY);
2393         KX_MACRO_addTypesToDict(d, BACKSPACEKEY, SCA_IInputDevice::KX_BACKSPACEKEY);
2394         KX_MACRO_addTypesToDict(d, DELKEY, SCA_IInputDevice::KX_DELKEY);
2395         KX_MACRO_addTypesToDict(d, SEMICOLONKEY, SCA_IInputDevice::KX_SEMICOLONKEY);
2396         KX_MACRO_addTypesToDict(d, PERIODKEY, SCA_IInputDevice::KX_PERIODKEY);
2397         KX_MACRO_addTypesToDict(d, COMMAKEY, SCA_IInputDevice::KX_COMMAKEY);
2398         KX_MACRO_addTypesToDict(d, QUOTEKEY, SCA_IInputDevice::KX_QUOTEKEY);
2399         KX_MACRO_addTypesToDict(d, ACCENTGRAVEKEY, SCA_IInputDevice::KX_ACCENTGRAVEKEY);
2400         KX_MACRO_addTypesToDict(d, MINUSKEY, SCA_IInputDevice::KX_MINUSKEY);
2401         KX_MACRO_addTypesToDict(d, SLASHKEY, SCA_IInputDevice::KX_SLASHKEY);
2402         KX_MACRO_addTypesToDict(d, BACKSLASHKEY, SCA_IInputDevice::KX_BACKSLASHKEY);
2403         KX_MACRO_addTypesToDict(d, EQUALKEY, SCA_IInputDevice::KX_EQUALKEY);
2404         KX_MACRO_addTypesToDict(d, LEFTBRACKETKEY, SCA_IInputDevice::KX_LEFTBRACKETKEY);
2405         KX_MACRO_addTypesToDict(d, RIGHTBRACKETKEY, SCA_IInputDevice::KX_RIGHTBRACKETKEY);
2406                 
2407         KX_MACRO_addTypesToDict(d, LEFTARROWKEY, SCA_IInputDevice::KX_LEFTARROWKEY);
2408         KX_MACRO_addTypesToDict(d, DOWNARROWKEY, SCA_IInputDevice::KX_DOWNARROWKEY);
2409         KX_MACRO_addTypesToDict(d, RIGHTARROWKEY, SCA_IInputDevice::KX_RIGHTARROWKEY);
2410         KX_MACRO_addTypesToDict(d, UPARROWKEY, SCA_IInputDevice::KX_UPARROWKEY);
2411         
2412         KX_MACRO_addTypesToDict(d, PAD2 , SCA_IInputDevice::KX_PAD2);
2413         KX_MACRO_addTypesToDict(d, PAD4 , SCA_IInputDevice::KX_PAD4);
2414         KX_MACRO_addTypesToDict(d, PAD6 , SCA_IInputDevice::KX_PAD6);
2415         KX_MACRO_addTypesToDict(d, PAD8 , SCA_IInputDevice::KX_PAD8);
2416                 
2417         KX_MACRO_addTypesToDict(d, PAD1 , SCA_IInputDevice::KX_PAD1);
2418         KX_MACRO_addTypesToDict(d, PAD3 , SCA_IInputDevice::KX_PAD3);
2419         KX_MACRO_addTypesToDict(d, PAD5 , SCA_IInputDevice::KX_PAD5);
2420         KX_MACRO_addTypesToDict(d, PAD7 , SCA_IInputDevice::KX_PAD7);
2421         KX_MACRO_addTypesToDict(d, PAD9 , SCA_IInputDevice::KX_PAD9);
2422                 
2423         KX_MACRO_addTypesToDict(d, PADPERIOD, SCA_IInputDevice::KX_PADPERIOD);
2424         KX_MACRO_addTypesToDict(d, PADSLASHKEY, SCA_IInputDevice::KX_PADSLASHKEY);
2425         KX_MACRO_addTypesToDict(d, PADASTERKEY, SCA_IInputDevice::KX_PADASTERKEY);
2426                 
2427                 
2428         KX_MACRO_addTypesToDict(d, PAD0, SCA_IInputDevice::KX_PAD0);
2429         KX_MACRO_addTypesToDict(d, PADMINUS, SCA_IInputDevice::KX_PADMINUS);
2430         KX_MACRO_addTypesToDict(d, PADENTER, SCA_IInputDevice::KX_PADENTER);
2431         KX_MACRO_addTypesToDict(d, PADPLUSKEY, SCA_IInputDevice::KX_PADPLUSKEY);
2432                 
2433                 
2434         KX_MACRO_addTypesToDict(d, F1KEY,  SCA_IInputDevice::KX_F1KEY);
2435         KX_MACRO_addTypesToDict(d, F2KEY,  SCA_IInputDevice::KX_F2KEY);
2436         KX_MACRO_addTypesToDict(d, F3KEY,  SCA_IInputDevice::KX_F3KEY);
2437         KX_MACRO_addTypesToDict(d, F4KEY,  SCA_IInputDevice::KX_F4KEY);
2438         KX_MACRO_addTypesToDict(d, F5KEY,  SCA_IInputDevice::KX_F5KEY);
2439         KX_MACRO_addTypesToDict(d, F6KEY,  SCA_IInputDevice::KX_F6KEY);
2440         KX_MACRO_addTypesToDict(d, F7KEY,  SCA_IInputDevice::KX_F7KEY);
2441         KX_MACRO_addTypesToDict(d, F8KEY,  SCA_IInputDevice::KX_F8KEY);
2442         KX_MACRO_addTypesToDict(d, F9KEY,  SCA_IInputDevice::KX_F9KEY);
2443         KX_MACRO_addTypesToDict(d, F10KEY, SCA_IInputDevice::KX_F10KEY);
2444         KX_MACRO_addTypesToDict(d, F11KEY, SCA_IInputDevice::KX_F11KEY);
2445         KX_MACRO_addTypesToDict(d, F12KEY, SCA_IInputDevice::KX_F12KEY);
2446         KX_MACRO_addTypesToDict(d, F13KEY, SCA_IInputDevice::KX_F13KEY);
2447         KX_MACRO_addTypesToDict(d, F14KEY, SCA_IInputDevice::KX_F14KEY);
2448         KX_MACRO_addTypesToDict(d, F15KEY, SCA_IInputDevice::KX_F15KEY);
2449         KX_MACRO_addTypesToDict(d, F16KEY, SCA_IInputDevice::KX_F16KEY);
2450         KX_MACRO_addTypesToDict(d, F17KEY, SCA_IInputDevice::KX_F17KEY);
2451         KX_MACRO_addTypesToDict(d, F18KEY, SCA_IInputDevice::KX_F18KEY);
2452         KX_MACRO_addTypesToDict(d, F19KEY, SCA_IInputDevice::KX_F19KEY);
2453
2454         KX_MACRO_addTypesToDict(d, OSKEY, SCA_IInputDevice::KX_OSKEY);
2455                 
2456         KX_MACRO_addTypesToDict(d, PAUSEKEY,  SCA_IInputDevice::KX_PAUSEKEY);
2457         KX_MACRO_addTypesToDict(d, INSERTKEY, SCA_IInputDevice::KX_INSERTKEY);
2458         KX_MACRO_addTypesToDict(d, HOMEKEY,   SCA_IInputDevice::KX_HOMEKEY);
2459         KX_MACRO_addTypesToDict(d, PAGEUPKEY, SCA_IInputDevice::KX_PAGEUPKEY);
2460         KX_MACRO_addTypesToDict(d, PAGEDOWNKEY, SCA_IInputDevice::KX_PAGEDOWNKEY);
2461         KX_MACRO_addTypesToDict(d, ENDKEY, SCA_IInputDevice::KX_ENDKEY);
2462
2463         // MOUSE
2464         KX_MACRO_addTypesToDict(d, LEFTMOUSE, SCA_IInputDevice::KX_LEFTMOUSE);
2465         KX_MACRO_addTypesToDict(d, MIDDLEMOUSE, SCA_IInputDevice::KX_MIDDLEMOUSE);
2466         KX_MACRO_addTypesToDict(d, RIGHTMOUSE, SCA_IInputDevice::KX_RIGHTMOUSE);
2467         KX_MACRO_addTypesToDict(d, WHEELUPMOUSE, SCA_IInputDevice::KX_WHEELUPMOUSE);
2468         KX_MACRO_addTypesToDict(d, WHEELDOWNMOUSE, SCA_IInputDevice::KX_WHEELDOWNMOUSE);
2469         KX_MACRO_addTypesToDict(d, MOUSEX, SCA_IInputDevice::KX_MOUSEX);
2470         KX_MACRO_addTypesToDict(d, MOUSEY, SCA_IInputDevice::KX_MOUSEY);
2471
2472         // Check for errors
2473         if (PyErr_Occurred())
2474         {
2475                 Py_FatalError("can't initialize module GameKeys");
2476         }
2477
2478         return d;
2479 }
2480
2481 // utility function for loading and saving the globalDict
2482 int saveGamePythonConfig( char **marshal_buffer)
2483 {
2484         int marshal_length = 0;
2485         PyObject *gameLogic = PyImport_ImportModule("GameLogic");
2486         if (gameLogic) {
2487                 PyObject *pyGlobalDict = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module
2488                 if (pyGlobalDict) {
2489 #ifdef Py_MARSHAL_VERSION
2490                         PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict, 2); // Py_MARSHAL_VERSION == 2 as of Py2.5
2491 #else
2492                         PyObject *pyGlobalDictMarshal = PyMarshal_WriteObjectToString(  pyGlobalDict );
2493 #endif
2494                         if (pyGlobalDictMarshal) {
2495                                 // for testing only
2496                                 // PyObject_Print(pyGlobalDictMarshal, stderr, 0);
2497                                 char *marshal_cstring;
2498                                 
2499                                 marshal_cstring = PyBytes_AsString(pyGlobalDictMarshal); // py3 uses byte arrays
2500                                 marshal_length= PyBytes_Size(pyGlobalDictMarshal);
2501                                 *marshal_buffer = new char[marshal_length + 1];
2502                                 memcpy(*marshal_buffer, marshal_cstring, marshal_length);
2503                                 Py_DECREF(pyGlobalDictMarshal);
2504                         } else {
2505                                 printf("Error, bge.logic.globalDict could not be marshal'd\n");
2506                         }
2507                 } else {
2508                         printf("Error, bge.logic.globalDict was removed\n");
2509                 }
2510                 Py_DECREF(gameLogic);
2511         } else {
2512                 PyErr_Clear();
2513                 printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2514         }
2515         return marshal_length;
2516 }
2517
2518 int loadGamePythonConfig(char *marshal_buffer, int marshal_length)
2519 {
2520         /* Restore the dict */
2521         if (marshal_buffer) {
2522                 PyObject *gameLogic = PyImport_ImportModule("GameLogic");
2523
2524                 if (gameLogic) {
2525                         PyObject *pyGlobalDict = PyMarshal_ReadObjectFromString(marshal_buffer, marshal_length);
2526                         if (pyGlobalDict) {
2527                                 PyObject *pyGlobalDict_orig = PyDict_GetItemString(PyModule_GetDict(gameLogic), "globalDict"); // Same as importing the module.
2528                                 if (pyGlobalDict_orig) {
2529                                         PyDict_Clear(pyGlobalDict_orig);
2530                                         PyDict_Update(pyGlobalDict_orig, pyGlobalDict);
2531                                 } else {
2532                                         /* this should not happen, but cant find the original globalDict, just assign it then */
2533                                         PyDict_SetItemString(PyModule_GetDict(gameLogic), "globalDict", pyGlobalDict); // Same as importing the module.
2534                                 }
2535                                 Py_DECREF(gameLogic);
2536                                 Py_DECREF(pyGlobalDict);
2537                                 return 1;
2538                         } else {
2539                                 Py_DECREF(gameLogic);
2540                                 PyErr_Clear();
2541                                 printf("Error could not marshall string\n");
2542                         }
2543                 }
2544                 else {
2545                         PyErr_Clear();
2546                         printf("Error, bge.logic failed to import bge.logic.globalDict will be lost\n");
2547                 }
2548         }
2549         return 0;
2550 }
2551
2552 void pathGamePythonConfig(char *path)
2553 {
2554         int len = strlen(gp_GamePythonPathOrig); // Always use the first loaded blend filename
2555         
2556         BLI_strncpy(path, gp_GamePythonPathOrig, sizeof(gp_GamePythonPathOrig));
2557
2558         /* replace extension */
2559         if (BLI_testextensie(path, ".blend")) {
2560                 strcpy(path+(len-6), ".bgeconf");
2561         } else {
2562                 strcpy(path+len, ".bgeconf");
2563         }
2564 }
2565
2566 void setGamePythonPath(const char *path)
2567 {
2568         BLI_strncpy(gp_GamePythonPath, path, sizeof(gp_GamePythonPath));
2569         BLI_cleanup_file(NULL, gp_GamePythonPath); /* not absolutely needed but makes resolving path problems less confusing later */
2570         
2571         if (gp_GamePythonPathOrig[0] == '\0')
2572                 BLI_strncpy(gp_GamePythonPathOrig, path, sizeof(gp_GamePythonPathOrig));
2573 }
2574
2575 // we need this so while blender is open (not blenderplayer)
2576 // loading new blendfiles will reset this on starting the
2577 // engine but loading blend files within the BGE wont overwrite gp_GamePythonPathOrig
2578 void resetGamePythonPath()
2579 {
2580         gp_GamePythonPathOrig[0] = '\0';
2581 }
2582
2583 #endif // WITH_PYTHON