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