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