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