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