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