BGE: Cleaning up the vsync code a little.
[blender-staging.git] / source / gameengine / BlenderRoutines / BL_KetsjiEmbedStart.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  * Blender's Ketsji startpoint
27  */
28
29 /** \file gameengine/BlenderRoutines/BL_KetsjiEmbedStart.cpp
30  *  \ingroup blroutines
31  */
32
33
34 #include <signal.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37
38 #ifdef _MSC_VER
39    /* don't show stl-warnings */
40 #  pragma warning (disable:4786)
41 #endif
42
43 #include "GL/glew.h"
44
45 #include "KX_BlenderGL.h"
46 #include "KX_BlenderCanvas.h"
47 #include "KX_BlenderKeyboardDevice.h"
48 #include "KX_BlenderMouseDevice.h"
49 #include "KX_BlenderRenderTools.h"
50 #include "KX_BlenderSystem.h"
51 #include "BL_Material.h"
52
53 #include "KX_KetsjiEngine.h"
54 #include "KX_BlenderSceneConverter.h"
55 #include "KX_PythonInit.h"
56 #include "KX_PyConstraintBinding.h"
57 #include "KX_PythonMain.h"
58
59 #include "RAS_GLExtensionManager.h"
60 #include "RAS_OpenGLRasterizer.h"
61 #include "RAS_ListRasterizer.h"
62
63 #include "NG_LoopBackNetworkDeviceInterface.h"
64
65 #include "BL_System.h"
66
67 #include "GPU_extensions.h"
68 #include "Value.h"
69
70
71 extern "C" {
72         #include "DNA_view3d_types.h"
73         #include "DNA_screen_types.h"
74         #include "DNA_userdef_types.h"
75         #include "DNA_scene_types.h"
76         #include "DNA_windowmanager_types.h"
77
78         #include "BKE_global.h"
79         #include "BKE_report.h"
80         #include "BKE_ipo.h"
81         #include "BKE_main.h"
82         #include "BKE_context.h"
83
84         /* avoid c++ conflict with 'new' */
85         #define new _new
86         #include "BKE_screen.h"
87         #undef new
88
89         #include "MEM_guardedalloc.h"
90
91         #include "BLI_blenlib.h"
92         #include "BLO_readfile.h"
93
94         #include "../../blender/windowmanager/WM_types.h"
95         #include "../../blender/windowmanager/wm_window.h"
96         #include "../../blender/windowmanager/wm_event_system.h"
97 }
98
99 #ifdef WITH_AUDASPACE
100 #  include "AUD_C-API.h"
101 #  include "AUD_I3DDevice.h"
102 #  include "AUD_IDevice.h"
103 #endif
104
105 static BlendFileData *load_game_data(char *filename)
106 {
107         ReportList reports;
108         BlendFileData *bfd;
109         
110         BKE_reports_init(&reports, RPT_STORE);
111         bfd= BLO_read_from_file(filename, &reports);
112
113         if (!bfd) {
114                 printf("Loading %s failed: ", filename);
115                 BKE_reports_print(&reports, RPT_ERROR);
116         }
117
118         BKE_reports_clear(&reports);
119
120         return bfd;
121 }
122
123 static int BL_KetsjiNextFrame(KX_KetsjiEngine *ketsjiengine, bContext *C, wmWindow *win, Scene *scene, ARegion *ar,
124                               KX_BlenderKeyboardDevice* keyboarddevice, KX_BlenderMouseDevice* mousedevice, int draw_letterbox)
125 {
126         int exitrequested;
127
128         // first check if we want to exit
129         exitrequested = ketsjiengine->GetExitCode();
130
131         // kick the engine
132         bool render = ketsjiengine->NextFrame();
133
134         if (render) {
135                 if (draw_letterbox) {
136                         // Clear screen to border color
137                         // We do this here since we set the canvas to be within the frames. This means the engine
138                         // itself is unaware of the extra space, so we clear the whole region for it.
139                         glClearColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 1.0f);
140                         glViewport(ar->winrct.xmin, ar->winrct.ymin,
141                                    BLI_rcti_size_x(&ar->winrct), BLI_rcti_size_y(&ar->winrct));
142                         glClear(GL_COLOR_BUFFER_BIT);
143                 }
144
145                 // render the frame
146                 ketsjiengine->Render();
147         }
148
149         wm_window_process_events_nosleep();
150
151         // test for the ESC key
152         //XXX while (qtest())
153         while (wmEvent *event= (wmEvent *)win->queue.first) {
154                 short val = 0;
155                 //unsigned short event = 0; //XXX extern_qread(&val);
156
157                 if (keyboarddevice->ConvertBlenderEvent(event->type,event->val))
158                         exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
159
160                 /* Coordinate conversion... where
161                  * should this really be?
162                  */
163                 if (event->type == MOUSEMOVE) {
164                         /* Note, not nice! XXX 2.5 event hack */
165                         val = event->x - ar->winrct.xmin;
166                         mousedevice->ConvertBlenderEvent(MOUSEX, val);
167
168                         val = ar->winy - (event->y - ar->winrct.ymin) - 1;
169                         mousedevice->ConvertBlenderEvent(MOUSEY, val);
170                 }
171                 else {
172                         mousedevice->ConvertBlenderEvent(event->type,event->val);
173                 }
174
175                 BLI_remlink(&win->queue, event);
176                 wm_event_free(event);
177         }
178
179         if (win != CTX_wm_window(C)) {
180                 exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */
181         }
182         return exitrequested;
183 }
184
185 static struct BL_KetsjiNextFrameState {
186         class KX_KetsjiEngine* ketsjiengine;
187         struct bContext *C;
188         struct wmWindow* win;
189         struct Scene* scene;
190         struct ARegion *ar;
191         KX_BlenderKeyboardDevice* keyboarddevice;
192         KX_BlenderMouseDevice* mousedevice;
193         int draw_letterbox;
194 } ketsjinextframestate;
195
196 static int BL_KetsjiPyNextFrame(void *state0)
197 {
198         BL_KetsjiNextFrameState *state = (BL_KetsjiNextFrameState *) state0;
199         return BL_KetsjiNextFrame(
200                 state->ketsjiengine, 
201                 state->C, 
202                 state->win, 
203                 state->scene, 
204                 state->ar,
205                 state->keyboarddevice, 
206                 state->mousedevice, 
207                 state->draw_letterbox);
208 }
209
210 extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *cam_frame, int always_use_expand_framing)
211 {
212         /* context values */
213         struct wmWindowManager *wm= CTX_wm_manager(C);
214         struct wmWindow *win= CTX_wm_window(C);
215         struct Scene *startscene= CTX_data_scene(C);
216         struct Main* maggie1= CTX_data_main(C);
217
218
219         RAS_Rect area_rect;
220         area_rect.SetLeft(cam_frame->xmin);
221         area_rect.SetBottom(cam_frame->ymin);
222         area_rect.SetRight(cam_frame->xmax);
223         area_rect.SetTop(cam_frame->ymax);
224
225         int exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
226         Main* blenderdata = maggie1;
227
228         char* startscenename = startscene->id.name+2;
229         char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
230         STR_String exitstring = "";
231         BlendFileData *bfd= NULL;
232
233         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
234         BLI_strncpy(oldsce, G.main->name, sizeof(oldsce));
235 #ifdef WITH_PYTHON
236         resetGamePythonPath(); // need this so running a second time wont use an old blendfiles path
237         setGamePythonPath(G.main->name);
238
239         // Acquire Python's GIL (global interpreter lock)
240         // so we can safely run Python code and API calls
241         PyGILState_STATE gilstate = PyGILState_Ensure();
242         
243         PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */
244 #endif
245         
246         bgl::InitExtensions(true);
247
248         // VBO code for derived mesh is not compatible with BGE (couldn't find why), so disable
249         int disableVBO = (U.gameflags & USER_DISABLE_VBO);
250         U.gameflags |= USER_DISABLE_VBO;
251
252         // Globals to be carried on over blender files
253         GlobalSettings gs;
254         gs.matmode= startscene->gm.matmode;
255         gs.glslflag= startscene->gm.flag;
256
257         do
258         {
259                 View3D *v3d= CTX_wm_view3d(C);
260                 RegionView3D *rv3d= CTX_wm_region_view3d(C);
261
262                 // get some preferences
263                 SYS_SystemHandle syshandle = SYS_GetSystem();
264                 bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
265                 bool usefixed = (SYS_GetCommandLineInt(syshandle, "fixedtime", 0) != 0);
266                 bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
267                 bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
268                 bool animation_record = (SYS_GetCommandLineInt(syshandle, "animation_record", 0) != 0);
269                 bool displaylists = (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0);
270 #ifdef WITH_PYTHON
271                 bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
272 #endif
273                 // bool novertexarrays = (SYS_GetCommandLineInt(syshandle, "novertexarrays", 0) != 0);
274                 bool mouse_state = startscene->gm.flag & GAME_SHOW_MOUSE;
275                 bool restrictAnimFPS = startscene->gm.flag & GAME_RESTRICT_ANIM_UPDATES;
276
277                 if (animation_record) usefixed= false; /* override since you don't want to run full-speed for sim recording */
278
279                 // create the canvas, rasterizer and rendertools
280                 RAS_ICanvas* canvas = new KX_BlenderCanvas(wm, win, area_rect, ar);
281                 
282                 // default mouse state set on render panel
283                 if (mouse_state)
284                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
285                 else
286                         canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
287
288                 // Setup vsync
289                 int previous_vsync = canvas->GetSwapInterval();
290                 if (startscene->gm.vsync == VSYNC_ADAPTIVE)
291                         canvas->SetSwapInterval(-1);
292                 else
293                         canvas->SetSwapInterval((startscene->gm.vsync == VSYNC_ON) ? 1 : 0);
294
295                 RAS_IRenderTools* rendertools = new KX_BlenderRenderTools();
296                 RAS_IRasterizer* rasterizer = NULL;
297                 //Don't use displaylists with VBOs
298                 //If auto starts using VBOs, make sure to check for that here
299                 if (displaylists && startscene->gm.raster_storage != RAS_STORE_VBO)
300                         rasterizer = new RAS_ListRasterizer(canvas, true, startscene->gm.raster_storage);
301                 else
302                         rasterizer = new RAS_OpenGLRasterizer(canvas, startscene->gm.raster_storage);
303
304                 RAS_IRasterizer::MipmapOption mipmapval = rasterizer->GetMipmapping();
305
306                 
307                 // create the inputdevices
308                 KX_BlenderKeyboardDevice* keyboarddevice = new KX_BlenderKeyboardDevice();
309                 KX_BlenderMouseDevice* mousedevice = new KX_BlenderMouseDevice();
310                 
311                 // create a networkdevice
312                 NG_NetworkDeviceInterface* networkdevice = new
313                         NG_LoopBackNetworkDeviceInterface();
314
315                 //
316                 // create a ketsji/blendersystem (only needed for timing and stuff)
317                 KX_BlenderSystem* kxsystem = new KX_BlenderSystem();
318                 
319                 // create the ketsjiengine
320                 KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
321                 
322                 // set the devices
323                 ketsjiengine->SetKeyboardDevice(keyboarddevice);
324                 ketsjiengine->SetMouseDevice(mousedevice);
325                 ketsjiengine->SetNetworkDevice(networkdevice);
326                 ketsjiengine->SetCanvas(canvas);
327                 ketsjiengine->SetRenderTools(rendertools);
328                 ketsjiengine->SetRasterizer(rasterizer);
329                 ketsjiengine->SetUseFixedTime(usefixed);
330                 ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
331                 ketsjiengine->SetRestrictAnimationFPS(restrictAnimFPS);
332                 KX_KetsjiEngine::SetExitKey(ConvertKeyCode(startscene->gm.exitkey));
333
334                 //set the global settings (carried over if restart/load new files)
335                 ketsjiengine->SetGlobalSettings(&gs);
336
337 #ifdef WITH_PYTHON
338                 CValue::SetDeprecationWarnings(nodepwarnings);
339 #endif
340
341                 //lock frame and camera enabled - storing global values
342                 int tmp_lay= startscene->lay;
343                 Object *tmp_camera = startscene->camera;
344
345                 if (v3d->scenelock==0) {
346                         startscene->lay= v3d->lay;
347                         startscene->camera= v3d->camera;
348                 }
349
350                 // some blender stuff
351                 float camzoom;
352                 int draw_letterbox = 0;
353                 
354                 if (rv3d->persp==RV3D_CAMOB) {
355                         if (startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
356                                 camzoom = 1.0f;
357                                 draw_letterbox = 1;
358                         }
359                         else {
360                                 camzoom = 1.0f / BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
361                         }
362                 }
363                 else {
364                         camzoom = 2.0;
365                 }
366
367
368                 ketsjiengine->SetDrawType(v3d->drawtype);
369                 ketsjiengine->SetCameraZoom(camzoom);
370                 
371                 // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
372                 if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
373                 {
374                         exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
375                         if (bfd) BLO_blendfiledata_free(bfd);
376                         
377                         char basedpath[FILE_MAX];
378                         // base the actuator filename with respect
379                         // to the original file working directory
380
381                         if (exitstring != "")
382                                 BLI_strncpy(basedpath, exitstring.ReadPtr(), sizeof(basedpath));
383
384                         // load relative to the last loaded file, this used to be relative
385                         // to the first file but that makes no sense, relative paths in
386                         // blend files should be relative to that file, not some other file
387                         // that happened to be loaded first
388                         BLI_path_abs(basedpath, pathname);
389                         bfd = load_game_data(basedpath);
390                         
391                         // if it wasn't loaded, try it forced relative
392                         if (!bfd)
393                         {
394                                 // just add "//" in front of it
395                                 char temppath[FILE_MAX] = "//";
396                                 BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2);
397                                 
398                                 BLI_path_abs(temppath, pathname);
399                                 bfd = load_game_data(temppath);
400                         }
401                         
402                         // if we got a loaded blendfile, proceed
403                         if (bfd)
404                         {
405                                 blenderdata = bfd->main;
406                                 startscenename = bfd->curscene->id.name + 2;
407
408                                 if (blenderdata) {
409                                         BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
410                                         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
411 #ifdef WITH_PYTHON
412                                         setGamePythonPath(G.main->name);
413 #endif
414                                 }
415                         }
416                         // else forget it, we can't find it
417                         else
418                         {
419                                 exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
420                         }
421                 }
422
423                 Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
424
425                 if (scene)
426                 {
427                         int startFrame = scene->r.cfra;
428                         ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
429                         
430                         // Quad buffered needs a special window.
431                         if (scene->gm.stereoflag == STEREO_ENABLED) {
432                                 if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
433                                         rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
434
435                                 rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
436                         }
437
438                         rasterizer->SetBackColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 0.0f);
439                 }
440                 
441                 if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
442                 {
443                         if (rv3d->persp != RV3D_CAMOB)
444                         {
445                                 ketsjiengine->EnableCameraOverride(startscenename);
446                                 ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
447                                 ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat));
448                                 ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat));
449                                 if (rv3d->persp == RV3D_ORTHO)
450                                 {
451                                         ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
452                                 }
453                                 else
454                                 {
455                                         ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
456                                 }
457                                 ketsjiengine->SetCameraOverrideLens(v3d->lens);
458                         }
459                         
460                         // create a scene converter, create and convert the startingscene
461                         KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
462                         ketsjiengine->SetSceneConverter(sceneconverter);
463                         sceneconverter->addInitFromFrame=false;
464                         if (always_use_expand_framing)
465                                 sceneconverter->SetAlwaysUseExpandFraming(true);
466
467                         bool usemat = false, useglslmat = false;
468
469                         if (GLEW_ARB_multitexture && GLEW_VERSION_1_1)
470                                 usemat = true;
471
472                         if (GPU_glsl_support())
473                                 useglslmat = true;
474                         else if (gs.matmode == GAME_MAT_GLSL)
475                                 usemat = false;
476
477                         if (usemat && (gs.matmode != GAME_MAT_TEXFACE))
478                                 sceneconverter->SetMaterials(true);
479                         if (useglslmat && (gs.matmode == GAME_MAT_GLSL))
480                                 sceneconverter->SetGLSLMaterials(true);
481                         if (scene->gm.flag & GAME_NO_MATERIAL_CACHING)
482                                 sceneconverter->SetCacheMaterials(false);
483                                         
484                         KX_Scene* startscene = new KX_Scene(keyboarddevice,
485                                 mousedevice,
486                                 networkdevice,
487                                 startscenename,
488                                 scene,
489                                 canvas);
490
491 #ifdef WITH_PYTHON
492                         // some python things
493                         PyObject *gameLogic, *gameLogic_keys;
494                         setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
495 #endif // WITH_PYTHON
496
497                         //initialize Dome Settings
498                         if (scene->gm.stereoflag == STEREO_DOME)
499                                 ketsjiengine->InitDome(scene->gm.dome.res, scene->gm.dome.mode, scene->gm.dome.angle, scene->gm.dome.resbuf, scene->gm.dome.tilt, scene->gm.dome.warptext);
500
501                         // initialize 3D Audio Settings
502                         AUD_I3DDevice* dev = AUD_get3DDevice();
503                         if (dev)
504                         {
505                                 dev->setSpeedOfSound(scene->audio.speed_of_sound);
506                                 dev->setDopplerFactor(scene->audio.doppler_factor);
507                                 dev->setDistanceModel(AUD_DistanceModel(scene->audio.distance_model));
508                         }
509
510                         // from see blender.c:
511                         // FIXME: this version patching should really be part of the file-reading code,
512                         // but we still get too many unrelated data-corruption crashes otherwise...
513                         if (blenderdata->versionfile < 250)
514                                 do_versions_ipos_to_animato(blenderdata);
515
516                         if (sceneconverter)
517                         {
518                                 // convert and add scene
519                                 sceneconverter->ConvertScene(
520                                         startscene,
521                                         rendertools,
522                                         canvas);
523                                 ketsjiengine->AddScene(startscene);
524                                 
525                                 // init the rasterizer
526                                 rasterizer->Init();
527                                 
528                                 // start the engine
529                                 ketsjiengine->StartEngine(true);
530                                 
531
532                                 // Set the animation playback rate for ipo's and actions
533                                 // the framerate below should patch with FPS macro defined in blendef.h
534                                 // Could be in StartEngine set the framerate, we need the scene to do this
535                                 ketsjiengine->SetAnimFrameRate(FPS);
536                                 
537 #ifdef WITH_PYTHON
538                                 char *python_main = NULL;
539                                 pynextframestate.state = NULL;
540                                 pynextframestate.func = NULL;
541                                 python_main = KX_GetPythonMain(scene);
542
543                                 // the mainloop
544                                 printf("\nBlender Game Engine Started\n");
545                                 if (python_main) {
546                                         char *python_code = KX_GetPythonCode(blenderdata, python_main);
547                                         if (python_code) {
548                                                 ketsjinextframestate.ketsjiengine = ketsjiengine;
549                                                 ketsjinextframestate.C = C;
550                                                 ketsjinextframestate.win = win;
551                                                 ketsjinextframestate.scene = scene;
552                                                 ketsjinextframestate.ar = ar;
553                                                 ketsjinextframestate.keyboarddevice = keyboarddevice;
554                                                 ketsjinextframestate.mousedevice = mousedevice;
555                                                 ketsjinextframestate.draw_letterbox = draw_letterbox;
556                         
557                                                 pynextframestate.state = &ketsjinextframestate;
558                                                 pynextframestate.func = &BL_KetsjiPyNextFrame;
559                                                 printf("Yielding control to Python script '%s'...\n", python_main);
560                                                 PyRun_SimpleString(python_code);
561                                                 printf("Exit Python script '%s'\n", python_main);
562                                                 MEM_freeN(python_code);
563                                         }
564                                 }
565                                 else
566 #endif  /* WITH_PYTHON */
567                                 {
568                                         while (!exitrequested)
569                                         {
570                                                 exitrequested = BL_KetsjiNextFrame(ketsjiengine, C, win, scene, ar, keyboarddevice, mousedevice, draw_letterbox);
571                                         }
572                                 }
573                                 printf("Blender Game Engine Finished\n");
574                                 exitstring = ketsjiengine->GetExitString();
575 #ifdef WITH_PYTHON
576                                 if (python_main) MEM_freeN(python_main);
577 #endif  /* WITH_PYTHON */
578
579                                 gs = *(ketsjiengine->GetGlobalSettings());
580
581                                 // when exiting the mainloop
582 #ifdef WITH_PYTHON
583                                 // Clears the dictionary by hand:
584                                 // This prevents, extra references to global variables
585                                 // inside the GameLogic dictionary when the python interpreter is finalized.
586                                 // which allows the scene to safely delete them :)
587                                 // see: (space.c)->start_game
588                                 
589                                 //PyDict_Clear(PyModule_GetDict(gameLogic));
590                                 
591                                 // Keep original items, means python plugins will autocomplete members
592                                 PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
593                                 const Py_ssize_t numitems= PyList_GET_SIZE(gameLogic_keys_new);
594                                 Py_ssize_t listIndex;
595                                 for (listIndex=0; listIndex < numitems; listIndex++) {
596                                         PyObject *item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
597                                         if (!PySequence_Contains(gameLogic_keys, item)) {
598                                                 PyDict_DelItem( PyModule_GetDict(gameLogic), item);
599                                         }
600                                 }
601                                 Py_DECREF(gameLogic_keys_new);
602                                 gameLogic_keys_new = NULL;
603 #endif
604                                 ketsjiengine->StopEngine();
605 #ifdef WITH_PYTHON
606                                 exitGamePythonScripting();
607 #endif
608                                 networkdevice->Disconnect();
609                         }
610                         if (sceneconverter)
611                         {
612                                 delete sceneconverter;
613                                 sceneconverter = NULL;
614                         }
615
616 #ifdef WITH_PYTHON
617                         Py_DECREF(gameLogic_keys);
618                         gameLogic_keys = NULL;
619 #endif
620                 }
621                 //lock frame and camera enabled - restoring global values
622                 if (v3d->scenelock==0) {
623                         startscene->lay= tmp_lay;
624                         startscene->camera= tmp_camera;
625                 }
626
627                 if (exitrequested != KX_EXIT_REQUEST_OUTSIDE)
628                 {
629                         // set the cursor back to normal
630                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
631
632                         // set mipmap setting back to its original value
633                         rasterizer->SetMipmapping(mipmapval);
634                 }
635                 
636                 // clean up some stuff
637                 if (ketsjiengine)
638                 {
639                         delete ketsjiengine;
640                         ketsjiengine = NULL;
641                 }
642                 if (kxsystem)
643                 {
644                         delete kxsystem;
645                         kxsystem = NULL;
646                 }
647                 if (networkdevice)
648                 {
649                         delete networkdevice;
650                         networkdevice = NULL;
651                 }
652                 if (keyboarddevice)
653                 {
654                         delete keyboarddevice;
655                         keyboarddevice = NULL;
656                 }
657                 if (mousedevice)
658                 {
659                         delete mousedevice;
660                         mousedevice = NULL;
661                 }
662                 if (rasterizer)
663                 {
664                         delete rasterizer;
665                         rasterizer = NULL;
666                 }
667                 if (rendertools)
668                 {
669                         delete rendertools;
670                         rendertools = NULL;
671                 }
672                 if (canvas)
673                 {
674                         canvas->SetSwapInterval(previous_vsync); // Set the swap interval back
675                         delete canvas;
676                         canvas = NULL;
677                 }
678
679                 // stop all remaining playing sounds
680                 AUD_getDevice()->stopAll();
681         
682         } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
683         
684         if (!disableVBO)
685                 U.gameflags &= ~USER_DISABLE_VBO;
686
687         if (bfd) BLO_blendfiledata_free(bfd);
688
689         BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
690
691 #ifdef WITH_PYTHON
692         Py_DECREF(pyGlobalDict);
693
694         // Release Python's GIL
695         PyGILState_Release(gilstate);
696 #endif
697
698 }