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