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