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