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