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