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