bugfix [#23423] Multi-window : closing game windows cause blender crash
[blender.git] / source / gameengine / BlenderRoutines / BL_KetsjiEmbedStart.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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  * Blender's Ketsji startpoint
29  */
30
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34
35 #if defined(WIN32) && !defined(FREE_WINDOWS)
36 // don't show stl-warnings
37 #pragma warning (disable:4786)
38 #endif
39
40 #include "GL/glew.h"
41
42 #include "KX_BlenderGL.h"
43 #include "KX_BlenderCanvas.h"
44 #include "KX_BlenderKeyboardDevice.h"
45 #include "KX_BlenderMouseDevice.h"
46 #include "KX_BlenderRenderTools.h"
47 #include "KX_BlenderSystem.h"
48 #include "BL_Material.h"
49
50 #include "KX_KetsjiEngine.h"
51 #include "KX_BlenderSceneConverter.h"
52 #include "KX_PythonInit.h"
53 #include "KX_PyConstraintBinding.h"
54
55 #include "RAS_GLExtensionManager.h"
56 #include "RAS_OpenGLRasterizer.h"
57 #include "RAS_VAOpenGLRasterizer.h"
58 #include "RAS_ListRasterizer.h"
59
60 #include "NG_LoopBackNetworkDeviceInterface.h"
61
62 #include "SYS_System.h"
63
64 #include "GPU_extensions.h"
65 #include "Value.h"
66
67
68
69 #ifdef __cplusplus
70 extern "C" {
71 #endif
72         /***/
73 #include "DNA_view3d_types.h"
74 #include "DNA_screen_types.h"
75 #include "DNA_userdef_types.h"
76 #include "DNA_windowmanager_types.h"
77 #include "BKE_global.h"
78 #include "BKE_report.h"
79
80 #include "BKE_utildefines.h"
81 //XXX #include "BIF_screen.h"
82 //XXX #include "BIF_scrarea.h"
83
84 #include "BKE_main.h"
85 #include "BLI_blenlib.h"
86 #include "BLO_readfile.h"
87 #include "DNA_scene_types.h"
88 #include "BKE_ipo.h"
89         /***/
90
91 #include "AUD_C-API.h"
92
93 //XXX #include "BSE_headerbuttons.h"
94 #include "BKE_context.h"
95 #include "../../blender/windowmanager/WM_types.h"
96 #include "../../blender/windowmanager/wm_window.h"
97 #include "../../blender/windowmanager/wm_event_system.h"
98 #ifdef __cplusplus
99 }
100 #endif
101
102
103 static BlendFileData *load_game_data(char *filename)
104 {
105         ReportList reports;
106         BlendFileData *bfd;
107         
108         BKE_reports_init(&reports, RPT_STORE);
109         bfd= BLO_read_from_file(filename, &reports);
110
111         if (!bfd) {
112                 printf("Loading %s failed: ", filename);
113                 BKE_reports_print(&reports, RPT_ERROR);
114         }
115
116         BKE_reports_clear(&reports);
117
118         return bfd;
119 }
120
121 extern "C" void StartKetsjiShell(struct bContext *C, struct ARegion *ar, rcti *cam_frame, int always_use_expand_framing)
122 {
123         /* context values */
124         struct wmWindow *win= CTX_wm_window(C);
125         struct Scene *startscene= CTX_data_scene(C);
126         struct Main* maggie1= CTX_data_main(C);
127
128
129         RAS_Rect area_rect;
130         area_rect.SetLeft(cam_frame->xmin);
131         area_rect.SetBottom(cam_frame->ymin);
132         area_rect.SetRight(cam_frame->xmax);
133         area_rect.SetTop(cam_frame->ymax);
134
135         int exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
136         Main* blenderdata = maggie1;
137
138         char* startscenename = startscene->id.name+2;
139         char pathname[FILE_MAXDIR+FILE_MAXFILE], oldsce[FILE_MAXDIR+FILE_MAXFILE];
140         STR_String exitstring = "";
141         BlendFileData *bfd= NULL;
142
143         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
144         BLI_strncpy(oldsce, G.main->name, sizeof(oldsce));
145 #ifdef WITH_PYTHON
146         resetGamePythonPath(); // need this so running a second time wont use an old blendfiles path
147         setGamePythonPath(G.main->name);
148
149         // Acquire Python's GIL (global interpreter lock)
150         // so we can safely run Python code and API calls
151         PyGILState_STATE gilstate = PyGILState_Ensure();
152         
153         PyObject *pyGlobalDict = PyDict_New(); /* python utility storage, spans blend file loading */
154 #endif
155         
156         bgl::InitExtensions(true);
157
158         // VBO code for derived mesh is not compatible with BGE (couldn't find why), so disable
159         int disableVBO = (U.gameflags & USER_DISABLE_VBO);
160         U.gameflags |= USER_DISABLE_VBO;
161
162         do
163         {
164                 View3D *v3d= CTX_wm_view3d(C);
165                 RegionView3D *rv3d= CTX_wm_region_view3d(C);
166
167                 // get some preferences
168                 SYS_SystemHandle syshandle = SYS_GetSystem();
169                 bool properties = (SYS_GetCommandLineInt(syshandle, "show_properties", 0) != 0);
170                 bool usefixed = (SYS_GetCommandLineInt(syshandle, "fixedtime", 0) != 0);
171                 bool profile = (SYS_GetCommandLineInt(syshandle, "show_profile", 0) != 0);
172                 bool frameRate = (SYS_GetCommandLineInt(syshandle, "show_framerate", 0) != 0);
173                 bool animation_record = (SYS_GetCommandLineInt(syshandle, "animation_record", 0) != 0);
174                 bool displaylists = (SYS_GetCommandLineInt(syshandle, "displaylists", 0) != 0);
175 #ifdef WITH_PYTHON
176                 bool nodepwarnings = (SYS_GetCommandLineInt(syshandle, "ignore_deprecation_warnings", 0) != 0);
177 #endif
178                 bool novertexarrays = (SYS_GetCommandLineInt(syshandle, "novertexarrays", 0) != 0);
179                 if(animation_record) usefixed= true; /* override since you's always want fixed time for sim recording */
180
181                 // create the canvas, rasterizer and rendertools
182                 RAS_ICanvas* canvas = new KX_BlenderCanvas(win, area_rect, ar);
183                 canvas->SetMouseState(RAS_ICanvas::MOUSE_INVISIBLE);
184                 RAS_IRenderTools* rendertools = new KX_BlenderRenderTools();
185                 RAS_IRasterizer* rasterizer = NULL;
186                 
187                 if(displaylists) {
188                         if (GLEW_VERSION_1_1 && !novertexarrays)
189                                 rasterizer = new RAS_ListRasterizer(canvas, true, true);
190                         else
191                                 rasterizer = new RAS_ListRasterizer(canvas);
192                 }
193                 else if (GLEW_VERSION_1_1 && !novertexarrays)
194                         rasterizer = new RAS_VAOpenGLRasterizer(canvas, false);
195                 else
196                         rasterizer = new RAS_OpenGLRasterizer(canvas);
197                 
198                 // create the inputdevices
199                 KX_BlenderKeyboardDevice* keyboarddevice = new KX_BlenderKeyboardDevice();
200                 KX_BlenderMouseDevice* mousedevice = new KX_BlenderMouseDevice();
201                 
202                 // create a networkdevice
203                 NG_NetworkDeviceInterface* networkdevice = new
204                         NG_LoopBackNetworkDeviceInterface();
205
206                 //
207                 // create a ketsji/blendersystem (only needed for timing and stuff)
208                 KX_BlenderSystem* kxsystem = new KX_BlenderSystem();
209                 
210                 // create the ketsjiengine
211                 KX_KetsjiEngine* ketsjiengine = new KX_KetsjiEngine(kxsystem);
212                 
213                 // set the devices
214                 ketsjiengine->SetKeyboardDevice(keyboarddevice);
215                 ketsjiengine->SetMouseDevice(mousedevice);
216                 ketsjiengine->SetNetworkDevice(networkdevice);
217                 ketsjiengine->SetCanvas(canvas);
218                 ketsjiengine->SetRenderTools(rendertools);
219                 ketsjiengine->SetRasterizer(rasterizer);
220                 ketsjiengine->SetNetworkDevice(networkdevice);
221                 ketsjiengine->SetUseFixedTime(usefixed);
222                 ketsjiengine->SetTimingDisplay(frameRate, profile, properties);
223
224 #ifdef WITH_PYTHON
225                 CValue::SetDeprecationWarnings(nodepwarnings);
226 #endif
227
228                 //lock frame and camera enabled - storing global values
229                 int tmp_lay= startscene->lay;
230                 Object *tmp_camera = startscene->camera;
231
232                 if (v3d->scenelock==0){
233                         startscene->lay= v3d->lay;
234                         startscene->camera= v3d->camera;
235                 }
236
237                 // some blender stuff
238                 float camzoom;
239                 
240                 if(rv3d->persp==RV3D_CAMOB) {
241                         if(startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
242                                 camzoom = 1.0f;
243                         }
244                         else {
245                                 camzoom = (1.41421 + (rv3d->camzoom / 50.0));
246                                 camzoom *= camzoom;
247                                 camzoom = 4.0 / camzoom;
248                         }
249                 }
250                 else {
251                         camzoom = 2.0;
252                 }
253
254
255                 ketsjiengine->SetDrawType(v3d->drawtype);
256                 ketsjiengine->SetCameraZoom(camzoom);
257                 
258                 // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
259                 if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
260                 {
261                         exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
262                         if (bfd) BLO_blendfiledata_free(bfd);
263                         
264                         char basedpath[240];
265                         // base the actuator filename with respect
266                         // to the original file working directory
267
268                         if (exitstring != "")
269                                 strcpy(basedpath, exitstring.Ptr());
270
271                         // load relative to the last loaded file, this used to be relative
272                         // to the first file but that makes no sense, relative paths in
273                         // blend files should be relative to that file, not some other file
274                         // that happened to be loaded first
275                         BLI_path_abs(basedpath, pathname);
276                         bfd = load_game_data(basedpath);
277                         
278                         // if it wasn't loaded, try it forced relative
279                         if (!bfd)
280                         {
281                                 // just add "//" in front of it
282                                 char temppath[242];
283                                 strcpy(temppath, "//");
284                                 strcat(temppath, basedpath);
285                                 
286                                 BLI_path_abs(temppath, pathname);
287                                 bfd = load_game_data(temppath);
288                         }
289                         
290                         // if we got a loaded blendfile, proceed
291                         if (bfd)
292                         {
293                                 blenderdata = bfd->main;
294                                 startscenename = bfd->curscene->id.name + 2;
295
296                                 if(blenderdata) {
297                                         BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
298                                         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
299 #ifdef WITH_PYTHON
300                                         setGamePythonPath(G.main->name);
301 #endif
302                                 }
303                         }
304                         // else forget it, we can't find it
305                         else
306                         {
307                                 exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
308                         }
309                 }
310
311                 Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
312
313                 if (scene)
314                 {
315                         int startFrame = scene->r.cfra;
316                         ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
317                         
318                         // Quad buffered needs a special window.
319                         if(scene->gm.stereoflag == STEREO_ENABLED){
320                                 if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
321                                         rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
322
323                                 rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
324                         }
325
326                         rasterizer->SetBackColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 0.0f);
327                 }
328                 
329                 if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
330                 {
331                         if (rv3d->persp != RV3D_CAMOB)
332                         {
333                                 ketsjiengine->EnableCameraOverride(startscenename);
334                                 ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
335                                 ketsjiengine->SetCameraOverrideProjectionMatrix(MT_CmMatrix4x4(rv3d->winmat));
336                                 ketsjiengine->SetCameraOverrideViewMatrix(MT_CmMatrix4x4(rv3d->viewmat));
337                                 ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
338                                 ketsjiengine->SetCameraOverrideLens(v3d->lens);
339                         }
340                         
341                         // create a scene converter, create and convert the startingscene
342                         KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
343                         ketsjiengine->SetSceneConverter(sceneconverter);
344                         sceneconverter->addInitFromFrame=false;
345                         if (always_use_expand_framing)
346                                 sceneconverter->SetAlwaysUseExpandFraming(true);
347
348                         bool usemat = false, useglslmat = false;
349
350                         if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
351                                 usemat = true;
352
353                         if(GPU_glsl_support())
354                                 useglslmat = true;
355                         else if(scene->gm.matmode == GAME_MAT_GLSL)
356                                 usemat = false;
357
358                         if(usemat && (scene->gm.matmode != GAME_MAT_TEXFACE))
359                                 sceneconverter->SetMaterials(true);
360                         if(useglslmat && (scene->gm.matmode == GAME_MAT_GLSL))
361                                 sceneconverter->SetGLSLMaterials(true);
362                                         
363                         KX_Scene* startscene = new KX_Scene(keyboarddevice,
364                                 mousedevice,
365                                 networkdevice,
366                                 startscenename,
367                                 scene,
368                                 canvas);
369
370 #ifdef WITH_PYTHON
371                         // some python things
372                         PyObject *gameLogic, *gameLogic_keys;
373                         setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
374 #endif // WITH_PYTHON
375
376                         //initialize Dome Settings
377                         if(scene->gm.stereoflag == STEREO_DOME)
378                                 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);
379
380                         // initialize 3D Audio Settings
381                         AUD_setSpeedOfSound(scene->audio.speed_of_sound);
382                         AUD_setDopplerFactor(scene->audio.doppler_factor);
383                         AUD_setDistanceModel(AUD_DistanceModel(scene->audio.distance_model));
384
385                         // from see blender.c:
386                         // FIXME: this version patching should really be part of the file-reading code,
387                         // but we still get too many unrelated data-corruption crashes otherwise...
388                         if (blenderdata->versionfile < 250)
389                                 do_versions_ipos_to_animato(blenderdata);
390
391                         if (sceneconverter)
392                         {
393                                 // convert and add scene
394                                 sceneconverter->ConvertScene(
395                                         startscene,
396                                         rendertools,
397                                         canvas);
398                                 ketsjiengine->AddScene(startscene);
399                                 
400                                 // init the rasterizer
401                                 rasterizer->Init();
402                                 
403                                 // start the engine
404                                 ketsjiengine->StartEngine(true);
405                                 
406
407                                 // Set the animation playback rate for ipo's and actions
408                                 // the framerate below should patch with FPS macro defined in blendef.h
409                                 // Could be in StartEngine set the framerate, we need the scene to do this
410                                 ketsjiengine->SetAnimFrameRate(FPS);
411                                 
412                                 // the mainloop
413                                 printf("\nBlender Game Engine Started\n");
414                                 while (!exitrequested)
415                                 {
416                                         // first check if we want to exit
417                                         exitrequested = ketsjiengine->GetExitCode();
418                                         
419                                         // kick the engine
420                                         bool render = ketsjiengine->NextFrame();
421                                         
422                                         if (render)
423                                         {
424                                                 // render the frame
425                                                 ketsjiengine->Render();
426                                         }
427                                         
428                                         wm_window_process_events_nosleep();
429                                         
430                                         // test for the ESC key
431                                         //XXX while (qtest())
432                                         while(wmEvent *event= (wmEvent *)win->queue.first)
433                                         {
434                                                 short val = 0;
435                                                 //unsigned short event = 0; //XXX extern_qread(&val);
436                                                 
437                                                 if (keyboarddevice->ConvertBlenderEvent(event->type,event->val))
438                                                         exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
439                                                 
440                                                         /* Coordinate conversion... where
441                                                         * should this really be?
442                                                 */
443                                                 if (event->type==MOUSEMOVE) {
444                                                         /* Note, not nice! XXX 2.5 event hack */
445                                                         val = event->x - ar->winrct.xmin;
446                                                         mousedevice->ConvertBlenderEvent(MOUSEX, val);
447                                                         
448                                                         val = ar->winy - (event->y - ar->winrct.ymin) - 1;
449                                                         mousedevice->ConvertBlenderEvent(MOUSEY, val);
450                                                 }
451                                                 else {
452                                                         mousedevice->ConvertBlenderEvent(event->type,event->val);
453                                                 }
454                                                 
455                                                 BLI_remlink(&win->queue, event);
456                                                 wm_event_free(event);
457                                         }
458                                         
459                                         if(win != CTX_wm_window(C)) {
460                                                 exitrequested= KX_EXIT_REQUEST_OUTSIDE; /* window closed while bge runs */
461                                         }
462                                 }
463                                 printf("Blender Game Engine Finished\n");
464                                 exitstring = ketsjiengine->GetExitString();
465
466
467                                 // when exiting the mainloop
468 #ifdef WITH_PYTHON
469                                 // Clears the dictionary by hand:
470                                 // This prevents, extra references to global variables
471                                 // inside the GameLogic dictionary when the python interpreter is finalized.
472                                 // which allows the scene to safely delete them :)
473                                 // see: (space.c)->start_game
474                                 
475                                 //PyDict_Clear(PyModule_GetDict(gameLogic));
476                                 
477                                 // Keep original items, means python plugins will autocomplete members
478                                 int listIndex;
479                                 PyObject *gameLogic_keys_new = PyDict_Keys(PyModule_GetDict(gameLogic));
480                                 for (listIndex=0; listIndex < PyList_Size(gameLogic_keys_new); listIndex++)  {
481                                         PyObject* item = PyList_GET_ITEM(gameLogic_keys_new, listIndex);
482                                         if (!PySequence_Contains(gameLogic_keys, item)) {
483                                                 PyDict_DelItem( PyModule_GetDict(gameLogic), item);
484                                         }
485                                 }
486                                 Py_DECREF(gameLogic_keys_new);
487                                 gameLogic_keys_new = NULL;
488 #endif
489                                 ketsjiengine->StopEngine();
490 #ifdef WITH_PYTHON
491                                 exitGamePythonScripting();
492 #endif
493                                 networkdevice->Disconnect();
494                         }
495                         if (sceneconverter)
496                         {
497                                 delete sceneconverter;
498                                 sceneconverter = NULL;
499                         }
500
501 #ifdef WITH_PYTHON
502                         Py_DECREF(gameLogic_keys);
503                         gameLogic_keys = NULL;
504 #endif
505                 }
506                 //lock frame and camera enabled - restoring global values
507                 if (v3d->scenelock==0){
508                         startscene->lay= tmp_lay;
509                         startscene->camera= tmp_camera;
510                 }
511
512                 if(exitrequested != KX_EXIT_REQUEST_OUTSIDE)
513                 {
514                         // set the cursor back to normal
515                         canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
516                 }
517                 
518                 // clean up some stuff
519                 if (ketsjiengine)
520                 {
521                         delete ketsjiengine;
522                         ketsjiengine = NULL;
523                 }
524                 if (kxsystem)
525                 {
526                         delete kxsystem;
527                         kxsystem = NULL;
528                 }
529                 if (networkdevice)
530                 {
531                         delete networkdevice;
532                         networkdevice = NULL;
533                 }
534                 if (keyboarddevice)
535                 {
536                         delete keyboarddevice;
537                         keyboarddevice = NULL;
538                 }
539                 if (mousedevice)
540                 {
541                         delete mousedevice;
542                         mousedevice = NULL;
543                 }
544                 if (rasterizer)
545                 {
546                         delete rasterizer;
547                         rasterizer = NULL;
548                 }
549                 if (rendertools)
550                 {
551                         delete rendertools;
552                         rendertools = NULL;
553                 }
554                 if (canvas)
555                 {
556                         delete canvas;
557                         canvas = NULL;
558                 }
559         
560         } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
561         
562         if (!disableVBO)
563                 U.gameflags &= ~USER_DISABLE_VBO;
564
565         if (bfd) BLO_blendfiledata_free(bfd);
566
567         BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
568
569 #ifdef WITH_PYTHON
570         Py_DECREF(pyGlobalDict);
571
572         // Release Python's GIL
573         PyGILState_Release(gilstate);
574 #endif
575
576 }