rename and negate DISABLE_PYTHON --> WITH_PYTHON
[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                 MT_CmMatrix4x4 projmat;
239                 MT_CmMatrix4x4 viewmat;
240                 float camzoom;
241                 int i;
242
243                 for (i = 0; i < 16; i++)
244                 {
245                         float *viewmat_linear= (float*) rv3d->viewmat;
246                         viewmat.setElem(i, viewmat_linear[i]);
247                 }
248                 for (i = 0; i < 16; i++)
249                 {
250                         float *projmat_linear= (float*) rv3d->winmat;
251                         projmat.setElem(i, projmat_linear[i]);
252                 }
253                 
254                 if(rv3d->persp==RV3D_CAMOB) {
255                         if(startscene->gm.framing.type == SCE_GAMEFRAMING_BARS) { /* Letterbox */
256                                 camzoom = 1.0f;
257                         }
258                         else {
259                                 camzoom = (1.41421 + (rv3d->camzoom / 50.0));
260                                 camzoom *= camzoom;
261                                 camzoom = 4.0 / camzoom;
262                         }
263                 }
264                 else {
265                         camzoom = 2.0;
266                 }
267
268                 
269
270                 ketsjiengine->SetDrawType(v3d->drawtype);
271                 ketsjiengine->SetCameraZoom(camzoom);
272                 
273                 // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
274                 if (exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME || exitrequested == KX_EXIT_REQUEST_RESTART_GAME)
275                 {
276                         exitrequested = KX_EXIT_REQUEST_NO_REQUEST;
277                         if (bfd) BLO_blendfiledata_free(bfd);
278                         
279                         char basedpath[240];
280                         // base the actuator filename with respect
281                         // to the original file working directory
282
283                         if (exitstring != "")
284                                 strcpy(basedpath, exitstring.Ptr());
285
286                         // load relative to the last loaded file, this used to be relative
287                         // to the first file but that makes no sense, relative paths in
288                         // blend files should be relative to that file, not some other file
289                         // that happened to be loaded first
290                         BLI_path_abs(basedpath, pathname);
291                         bfd = load_game_data(basedpath);
292                         
293                         // if it wasn't loaded, try it forced relative
294                         if (!bfd)
295                         {
296                                 // just add "//" in front of it
297                                 char temppath[242];
298                                 strcpy(temppath, "//");
299                                 strcat(temppath, basedpath);
300                                 
301                                 BLI_path_abs(temppath, pathname);
302                                 bfd = load_game_data(temppath);
303                         }
304                         
305                         // if we got a loaded blendfile, proceed
306                         if (bfd)
307                         {
308                                 blenderdata = bfd->main;
309                                 startscenename = bfd->curscene->id.name + 2;
310
311                                 if(blenderdata) {
312                                         BLI_strncpy(G.main->name, blenderdata->name, sizeof(G.main->name));
313                                         BLI_strncpy(pathname, blenderdata->name, sizeof(pathname));
314 #ifdef WITH_PYTHON
315                                         setGamePythonPath(G.main->name);
316 #endif
317                                 }
318                         }
319                         // else forget it, we can't find it
320                         else
321                         {
322                                 exitrequested = KX_EXIT_REQUEST_QUIT_GAME;
323                         }
324                 }
325
326                 Scene *scene= bfd ? bfd->curscene : (Scene *)BLI_findstring(&blenderdata->scene, startscenename, offsetof(ID, name) + 2);
327
328                 if (scene)
329                 {
330                         int startFrame = scene->r.cfra;
331                         ketsjiengine->SetAnimRecordMode(animation_record, startFrame);
332                         
333                         // Quad buffered needs a special window.
334                         if(scene->gm.stereoflag == STEREO_ENABLED){
335                                 if (scene->gm.stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
336                                         rasterizer->SetStereoMode((RAS_IRasterizer::StereoMode) scene->gm.stereomode);
337
338                                 rasterizer->SetEyeSeparation(scene->gm.eyeseparation);
339                         }
340
341                         rasterizer->SetBackColor(scene->gm.framing.col[0], scene->gm.framing.col[1], scene->gm.framing.col[2], 0.0f);
342                 }
343                 
344                 if (exitrequested != KX_EXIT_REQUEST_QUIT_GAME)
345                 {
346                         if (rv3d->persp != RV3D_CAMOB)
347                         {
348                                 ketsjiengine->EnableCameraOverride(startscenename);
349                                 ketsjiengine->SetCameraOverrideUseOrtho((rv3d->persp == RV3D_ORTHO));
350                                 ketsjiengine->SetCameraOverrideProjectionMatrix(projmat);
351                                 ketsjiengine->SetCameraOverrideViewMatrix(viewmat);
352                                 ketsjiengine->SetCameraOverrideClipping(v3d->near, v3d->far);
353                                 ketsjiengine->SetCameraOverrideLens(v3d->lens);
354                         }
355                         
356                         // create a scene converter, create and convert the startingscene
357                         KX_ISceneConverter* sceneconverter = new KX_BlenderSceneConverter(blenderdata, ketsjiengine);
358                         ketsjiengine->SetSceneConverter(sceneconverter);
359                         sceneconverter->addInitFromFrame=false;
360                         if (always_use_expand_framing)
361                                 sceneconverter->SetAlwaysUseExpandFraming(true);
362
363                         bool usemat = false, useglslmat = false;
364
365                         if(GLEW_ARB_multitexture && GLEW_VERSION_1_1)
366                                 usemat = true;
367
368                         if(GPU_glsl_support())
369                                 useglslmat = true;
370                         else if(scene->gm.matmode == GAME_MAT_GLSL)
371                                 usemat = false;
372
373                         if(usemat && (scene->gm.matmode != GAME_MAT_TEXFACE))
374                                 sceneconverter->SetMaterials(true);
375                         if(useglslmat && (scene->gm.matmode == GAME_MAT_GLSL))
376                                 sceneconverter->SetGLSLMaterials(true);
377                                         
378                         KX_Scene* startscene = new KX_Scene(keyboarddevice,
379                                 mousedevice,
380                                 networkdevice,
381                                 startscenename,
382                                 scene,
383                                 canvas);
384
385 #ifdef WITH_PYTHON
386                         // some python things
387                         PyObject *gameLogic, *gameLogic_keys;
388                         setupGamePython(ketsjiengine, startscene, blenderdata, pyGlobalDict, &gameLogic, &gameLogic_keys, 0, NULL);
389 #endif // WITH_PYTHON
390
391                         //initialize Dome Settings
392                         if(scene->gm.stereoflag == STEREO_DOME)
393                                 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);
394
395                         // initialize 3D Audio Settings
396                         AUD_setSpeedOfSound(scene->audio.speed_of_sound);
397                         AUD_setDopplerFactor(scene->audio.doppler_factor);
398                         AUD_setDistanceModel(AUD_DistanceModel(scene->audio.distance_model));
399
400                         // from see blender.c:
401                         // FIXME: this version patching should really be part of the file-reading code,
402                         // but we still get too many unrelated data-corruption crashes otherwise...
403                         if (blenderdata->versionfile < 250)
404                                 do_versions_ipos_to_animato(blenderdata);
405
406                         if (sceneconverter)
407                         {
408                                 // convert and add scene
409                                 sceneconverter->ConvertScene(
410                                         startscene,
411                                         rendertools,
412                                         canvas);
413                                 ketsjiengine->AddScene(startscene);
414                                 
415                                 // init the rasterizer
416                                 rasterizer->Init();
417                                 
418                                 // start the engine
419                                 ketsjiengine->StartEngine(true);
420                                 
421
422                                 // Set the animation playback rate for ipo's and actions
423                                 // the framerate below should patch with FPS macro defined in blendef.h
424                                 // Could be in StartEngine set the framerate, we need the scene to do this
425                                 ketsjiengine->SetAnimFrameRate(FPS);
426                                 
427                                 // the mainloop
428                                 printf("\nBlender Game Engine Started\n");
429                                 while (!exitrequested)
430                                 {
431                                         // first check if we want to exit
432                                         exitrequested = ketsjiengine->GetExitCode();
433                                         
434                                         // kick the engine
435                                         bool render = ketsjiengine->NextFrame(); // XXX 2.5 Bug, This is never true! FIXME-  Campbell
436                                         
437                                         if (render)
438                                         {
439                                                 // render the frame
440                                                 ketsjiengine->Render();
441                                         }
442                                         
443                                         wm_window_process_events_nosleep();
444                                         
445                                         // test for the ESC key
446                                         //XXX while (qtest())
447                                         while(wmEvent *event= (wmEvent *)win->queue.first)
448                                         {
449                                                 short val = 0;
450                                                 //unsigned short event = 0; //XXX extern_qread(&val);
451                                                 
452                                                 if (keyboarddevice->ConvertBlenderEvent(event->type,event->val))
453                                                         exitrequested = KX_EXIT_REQUEST_BLENDER_ESC;
454                                                 
455                                                         /* Coordinate conversion... where
456                                                         * should this really be?
457                                                 */
458                                                 if (event->type==MOUSEMOVE) {
459                                                         /* Note, not nice! XXX 2.5 event hack */
460                                                         val = event->x - ar->winrct.xmin;
461                                                         mousedevice->ConvertBlenderEvent(MOUSEX, val);
462                                                         
463                                                         val = ar->winy - (event->y - ar->winrct.ymin) - 1;
464                                                         mousedevice->ConvertBlenderEvent(MOUSEY, val);
465                                                 }
466                                                 else {
467                                                         mousedevice->ConvertBlenderEvent(event->type,event->val);
468                                                 }
469                                                 
470                                                 BLI_remlink(&win->queue, event);
471                                                 wm_event_free(event);
472                                         }
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                 // set the cursor back to normal
525                 canvas->SetMouseState(RAS_ICanvas::MOUSE_NORMAL);
526                 
527                 // clean up some stuff
528                 if (ketsjiengine)
529                 {
530                         delete ketsjiengine;
531                         ketsjiengine = NULL;
532                 }
533                 if (kxsystem)
534                 {
535                         delete kxsystem;
536                         kxsystem = NULL;
537                 }
538                 if (networkdevice)
539                 {
540                         delete networkdevice;
541                         networkdevice = NULL;
542                 }
543                 if (keyboarddevice)
544                 {
545                         delete keyboarddevice;
546                         keyboarddevice = NULL;
547                 }
548                 if (mousedevice)
549                 {
550                         delete mousedevice;
551                         mousedevice = NULL;
552                 }
553                 if (rasterizer)
554                 {
555                         delete rasterizer;
556                         rasterizer = NULL;
557                 }
558                 if (rendertools)
559                 {
560                         delete rendertools;
561                         rendertools = NULL;
562                 }
563                 if (canvas)
564                 {
565                         delete canvas;
566                         canvas = NULL;
567                 }
568         
569         } while (exitrequested == KX_EXIT_REQUEST_RESTART_GAME || exitrequested == KX_EXIT_REQUEST_START_OTHER_GAME);
570         
571         if (!disableVBO)
572                 U.gameflags &= ~USER_DISABLE_VBO;
573
574         if (bfd) BLO_blendfiledata_free(bfd);
575
576         BLI_strncpy(G.main->name, oldsce, sizeof(G.main->name));
577
578 #ifdef WITH_PYTHON
579         Py_DECREF(pyGlobalDict);
580
581         // Release Python's GIL
582         PyGILState_Release(gilstate);
583 #endif
584
585 }