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