Recreating my GSoC branch.
[blender-staging.git] / source / gameengine / GamePlayer / ghost / GPG_ghost.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 * Start up of the Blender Player on GHOST.
29 */
30
31 #include <iostream>
32 #include <math.h>
33
34 #ifdef __linux__
35 #ifdef __alpha__
36 #include <signal.h>
37 #endif /* __alpha__ */
38 #endif /* __linux__ */
39
40 #ifdef __APPLE__
41 // Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
42 //#include <Carbon/Carbon.h>
43 //#include <CFBundle.h>
44 #endif // __APPLE__
45 #include "GEN_messaging.h"
46 #include "KX_KetsjiEngine.h"
47 #include "KX_PythonInit.h"
48
49 /**********************************
50 * Begin Blender include block
51 **********************************/
52 #ifdef __cplusplus
53 extern "C"
54 {
55 #endif  // __cplusplus
56 #include "MEM_guardedalloc.h"
57 #include "BKE_blender.h"        
58 #include "BKE_global.h" 
59 #include "BKE_icons.h"  
60 #include "BKE_node.h"   
61 #include "BKE_report.h" 
62 #include "BLI_blenlib.h"
63 #include "DNA_scene_types.h"
64 #include "DNA_userdef_types.h"
65 #include "BLO_readfile.h"
66 #include "BLO_readblenfile.h"
67 #include "IMB_imbuf.h"
68 #include "BKE_text.h"
69         
70         int GHOST_HACK_getFirstFile(char buf[]);
71         
72 extern char bprogname[];        /* holds a copy of argv[0], from creator.c */
73 extern char btempdir[];         /* use this to store a valid temp directory */
74
75 #ifdef __cplusplus
76 }
77 #endif // __cplusplus
78
79 #include "GPU_draw.h"
80
81 /**********************************
82 * End Blender include block
83 **********************************/
84
85 #include "SYS_System.h"
86 #include "GPG_Application.h"
87
88 #include "GHOST_ISystem.h"
89 #include "RAS_IRasterizer.h"
90
91 #include "BKE_main.h"
92 #include "BKE_utildefines.h"
93
94 #include "RNA_define.h"
95
96 #ifdef WIN32
97 #include <windows.h>
98 #ifdef NDEBUG
99 #include <wincon.h>
100 #endif // NDEBUG
101 #endif // WIN32
102
103 const int kMinWindowWidth = 100;
104 const int kMinWindowHeight = 100;
105
106 char bprogname[FILE_MAXDIR+FILE_MAXFILE];
107
108 #ifdef WIN32
109 typedef enum 
110 {
111   SCREEN_SAVER_MODE_NONE = 0,
112   SCREEN_SAVER_MODE_PREVIEW,
113   SCREEN_SAVER_MODE_SAVER,
114   SCREEN_SAVER_MODE_CONFIGURATION,
115   SCREEN_SAVER_MODE_PASSWORD,
116 } ScreenSaverMode;
117
118 static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
119 static HWND scr_saver_hwnd = NULL;
120
121 static BOOL scr_saver_init(int argc, char **argv) 
122 {
123         scr_saver_mode = SCREEN_SAVER_MODE_NONE;
124         scr_saver_hwnd = NULL;
125         BOOL ret = FALSE;
126
127         int len = ::strlen(argv[0]);
128         if (len > 4 && !::stricmp(".scr", argv[0] + len - 4))
129         {
130                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
131                 ret = TRUE;
132                 if (argc >= 2)
133                 {
134                         if (argc >= 3)
135                         {
136                                 scr_saver_hwnd = (HWND) ::atoi(argv[2]);
137                         }
138                         if (!::stricmp("/c", argv[1]))
139                         {
140                                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
141                                 if (scr_saver_hwnd == NULL)
142                                         scr_saver_hwnd = ::GetForegroundWindow();
143                         }
144                         else if (!::stricmp("/s", argv[1]))
145                         {
146                                 scr_saver_mode = SCREEN_SAVER_MODE_SAVER;
147                         }
148                         else if (!::stricmp("/a", argv[1]))
149                         {
150                                 scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD;
151                         }
152                         else if (!::stricmp("/p", argv[1])
153                                  || !::stricmp("/l", argv[1]))
154                         {
155                                 scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW;
156                         }
157                 }
158         }
159         return ret;
160 }
161
162 #endif /* WIN32 */
163
164 void usage(const char* program)
165 {
166         const char * consoleoption;
167 #ifdef _WIN32
168         consoleoption = "-c ";
169 #else
170         consoleoption = "";
171 #endif
172         
173         printf("usage:   %s [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] "
174                 "[-s stereomode] filename.blend\n", program, consoleoption);
175         printf("  -h: Prints this command summary\n\n");
176         printf("  -w: display in a window\n");
177         printf("       --Optional parameters--\n"); 
178         printf("       w = window width\n");
179         printf("       h = window height\n\n");
180         printf("       l = window left coordinate\n");
181         printf("       t = window top coordinate\n");
182         printf("       Note: If w or h is defined, both must be defined.\n");
183         printf("          Also, if l or t is defined, all options must be used.\n\n");
184         printf("  -f: start game in full screen mode\n");
185         printf("       --Optional parameters--\n");
186         printf("       fw = full screen mode pixel width\n");
187         printf("       fh = full screen mode pixel height\n\n");
188         printf("       fb = full screen mode bits per pixel\n");
189         printf("       ff = full screen mode frequency\n");
190         printf("       Note: If fw or fh is defined, both must be defined.\n");
191         printf("          Also, if fb is used, fw and fh must be used. ff requires all options.\n\n");
192         printf("  -s: start player in stereo\n");
193         printf("       stereomode: hwpageflip       (Quad buffered shutter glasses)\n");
194         printf("                   syncdoubling     (Above Below)\n");
195         printf("                   sidebyside       (Left Right)\n");
196         printf("                   anaglyph         (Red-Blue glasses)\n");
197         printf("                   vinterlace       (Vertical interlace for autostereo display)\n");
198         printf("                             depending on the type of stereo you want\n\n");
199         printf("  -D: start player in dome mode\n");
200         printf("       --Optional parameters--\n");
201         printf("       angle    = field of view in degrees\n");
202         printf("       tilt     = tilt angle in degrees\n");
203         printf("       warpdata = a file to use for warping the image (absolute path)\n");      
204         printf("       mode: fisheye                (Fisheye)\n");
205         printf("             truncatedfront         (Front-Truncated)\n");
206         printf("             truncatedrear          (Rear-Truncated)\n");
207         printf("             cubemap                (Cube Map)\n");
208         printf("             sphericalpanoramic     (Spherical Panoramic)\n");
209         printf("                             depending on the type of dome you are using\n\n");
210 #ifndef _WIN32
211         printf("  -i: parent windows ID \n\n");
212 #endif
213 #ifdef _WIN32
214         printf("  -c: keep console window open\n\n");
215 #endif
216         printf("  -d: turn debugging on\n\n");
217         printf("  -g: game engine options:\n\n");
218         printf("       Name                       Default      Description\n");
219         printf("       ------------------------------------------------------------------------\n");
220         printf("       fixedtime                      0         \"Enable all frames\"\n");
221         printf("       nomipmap                       0         Disable mipmaps\n");
222         printf("       show_framerate                 0         Show the frame rate\n");
223         printf("       show_properties                0         Show debug properties\n");
224         printf("       show_profile                   0         Show profiling information\n");
225         printf("       blender_material               0         Enable material settings\n");
226         printf("       ignore_deprecation_warnings    1         Ignore deprecation warnings\n");
227         printf("\n");
228         printf("  - : all arguments after this are ignored, allowing python to access them from sys.argv\n");
229         printf("\n");
230         printf("example: %s -w 320 200 10 10 -g noaudio c:\\loadtest.blend\n", program);
231         printf("example: %s -g show_framerate = 0 c:\\loadtest.blend\n", program);
232 }
233
234 static void get_filename(int argc, char **argv, char *filename)
235 {
236 #ifdef __APPLE__
237 /* On Mac we park the game file (called game.blend) in the application bundle.
238 * The executable is located in the bundle as well.
239 * Therefore, we can locate the game relative to the executable.
240         */
241         int srclen = ::strlen(argv[0]);
242         int len = 0;
243         char *gamefile = NULL;
244         
245         filename[0] = '\0';
246
247         if (argc > 1) {
248                 if (BLI_exists(argv[argc-1])) {
249                         BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
250                 }
251                 if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
252                         static char firstfilebuf[512];
253                         if (GHOST_HACK_getFirstFile(firstfilebuf)) {
254                                 BLI_strncpy(filename, firstfilebuf, FILE_MAXDIR + FILE_MAXFILE);
255                         }
256                 }                        
257         }
258         
259         srclen -= ::strlen("MacOS/blenderplayer");
260         if (srclen > 0) {
261                 len = srclen + ::strlen("Resources/game.blend"); 
262                 gamefile = new char [len + 1];
263                 ::strcpy(gamefile, argv[0]);
264                 ::strcpy(gamefile + srclen, "Resources/game.blend");
265                 //::printf("looking for file: %s\n", filename);
266                 
267                 if (BLI_exists(gamefile))
268                         BLI_strncpy(filename, gamefile, FILE_MAXDIR + FILE_MAXFILE);
269
270                 delete [] gamefile;
271         }
272         
273 #else
274         filename[0] = '\0';
275
276         if(argc > 1)
277                 BLI_strncpy(filename, argv[argc-1], FILE_MAXDIR + FILE_MAXFILE);
278 #endif // !_APPLE
279 }
280
281 static BlendFileData *load_game_data(char *progname, char *filename = NULL, char *relativename = NULL)
282 {
283         ReportList reports;
284         BlendFileData *bfd = NULL;
285
286         BKE_reports_init(&reports, RPT_STORE);
287         
288         /* try to load ourself, will only work if we are a runtime */
289         if (blo_is_a_runtime(progname)) {
290                 bfd= blo_read_runtime(progname, &reports);
291                 if (bfd) {
292                         bfd->type= BLENFILETYPE_RUNTIME;
293                         strcpy(bfd->main->name, progname);
294                 }
295         } else {
296                 bfd= BLO_read_from_file(progname, &reports);
297         }
298         
299         if (!bfd && filename) {
300                 bfd = load_game_data(filename);
301                 if (!bfd) {
302                         printf("Loading %s failed: ", filename);
303                         BKE_reports_print(&reports, RPT_ERROR);
304                 }
305         }
306
307         BKE_reports_clear(&reports);
308         
309         return bfd;
310 }
311
312 int main(int argc, char** argv)
313 {
314         int i;
315         int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
316         bool error = false;
317         SYS_SystemHandle syshandle = SYS_GetSystem();
318         bool fullScreen = false;
319         bool fullScreenParFound = false;
320         bool windowParFound = false;
321         bool closeConsole = true;
322         RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
323         bool stereoWindow = false;
324         bool stereoParFound = false;
325         int stereoFlag = STEREO_NOSTEREO;
326         int domeFov = -1;
327         int domeTilt = -200;
328         int domeMode = 0;
329         char* domeWarp = NULL;
330         Text *domeText  = NULL;
331         int windowLeft = 100;
332         int windowTop = 100;
333         int windowWidth = 640;
334         int windowHeight = 480;
335         GHOST_TUns32 fullScreenWidth = 0;
336         GHOST_TUns32 fullScreenHeight= 0;
337         int fullScreenBpp = 32;
338         int fullScreenFrequency = 60;
339         GHOST_TEmbedderWindowID parentWindow = 0;
340
341
342         
343 #ifdef __linux__
344 #ifdef __alpha__
345         signal (SIGFPE, SIG_IGN);
346 #endif /* __alpha__ */
347 #endif /* __linux__ */
348         BLI_where_am_i(bprogname, argv[0]);
349 #ifdef __APPLE__
350     // Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
351     /*
352     IBNibRef            nibRef;
353     WindowRef           window;
354     OSStatus            err;
355         
356           // Create a Nib reference passing the name of the nib file (without the .nib extension)
357           // CreateNibReference only searches into the application bundle.
358           err = ::CreateNibReference(CFSTR("main"), &nibRef);
359           if (err) return -1;
360           
361                 // Once the nib reference is created, set the menu bar. "MainMenu" is the name of the menu bar
362                 // object. This name is set in InterfaceBuilder when the nib is created.
363                 err = ::SetMenuBarFromNib(nibRef, CFSTR("MenuBar"));
364                 if (err) return -1;
365                 
366                   // We don't need the nib reference anymore.
367                   ::DisposeNibReference(nibRef);
368     */
369 #endif // __APPLE__
370
371         RNA_init();
372
373         init_nodesystem();
374         
375         initglobals();
376
377         GEN_init_messaging_system();
378
379         IMB_init();
380  
381         // Parse command line options
382 #ifndef NDEBUG
383         printf("argv[0] = '%s'\n", argv[0]);
384 #endif
385
386 #ifdef WIN32
387         if (scr_saver_init(argc, argv))
388         {
389                 switch (scr_saver_mode)
390                 {
391                 case SCREEN_SAVER_MODE_CONFIGURATION:
392                         MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
393                         break;
394                 case SCREEN_SAVER_MODE_PASSWORD:
395                         /* This is W95 only, which we currently do not support.
396                            Fall-back to normal screen saver behaviour in that case... */
397                 case SCREEN_SAVER_MODE_SAVER:
398                         fullScreen = true;
399                         fullScreenParFound = true;
400                         break;
401
402                 case SCREEN_SAVER_MODE_PREVIEW:
403                         /* This will actually be handled somewhere below... */
404                         break;
405                 }
406         }
407 #endif
408         // XXX add the ability to change this values to the command line parsing.
409         U.mixbufsize = 2048;
410         U.audiodevice = 2;
411         U.audiorate = 44100;
412         U.audioformat = 0x24;
413         U.audiochannels = 2;
414
415         for (i = 1; (i < argc) && !error 
416 #ifdef WIN32
417                 && scr_saver_mode == SCREEN_SAVER_MODE_NONE
418 #endif
419                 ;)
420
421         {
422 #ifndef NDEBUG
423                 printf("argv[%d] = '%s'   , %i\n", i, argv[i],argc);
424 #endif
425                 if (argv[i][0] == '-')
426                 {
427                         /* ignore all args after " - ", allow python to have own args */
428                         if (argv[i][1]=='\0') {
429                                 argc_py_clamped= i;
430                                 break;
431                         }
432                         
433                         switch (argv[i][1])
434                         {
435                         case 'g':
436                                 // Parse game options
437                                 {
438                                         i++;
439                                         if (i < argc)
440                                         {
441                                                 char* paramname = argv[i];
442                                                 // Check for single value versus assignment
443                                                 if (i+1 < argc && (*(argv[i+1]) == '='))
444                                                 {
445                                                         i++;
446                                                         if (i + 1 < argc)
447                                                         {
448                                                                 i++;
449                                                                 // Assignment
450                                                                 SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
451                                                                 SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
452                                                                 SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
453 #ifndef NDEBUG
454                                                                 printf("%s = '%s'\n", paramname, argv[i]);
455 #endif
456                                                                 i++;
457                                                         }
458                                                         else
459                                                         {
460                                                                 error = true;
461                                                                 printf("error: argument assignment %s without value.\n", paramname);
462                                                         }
463                                                 }
464                                                 else
465                                                 {
466 //                                                      SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
467                                                 }
468                                         }
469                                 }
470                                 break;
471
472                         case 'd':
473                                 i++;
474                                 G.f |= G_DEBUG;     /* std output printf's */
475                                 MEM_set_memory_debug();
476                                 break;
477
478                         case 'f':
479                                 i++;
480                                 fullScreen = true;
481                                 fullScreenParFound = true;
482                                 if ((i + 2) <= argc && argv[i][0] != '-' && argv[i+1][0] != '-')
483                                 {
484                                         fullScreenWidth = atoi(argv[i++]);
485                                         fullScreenHeight = atoi(argv[i++]);
486                                         if ((i + 1) <= argc && argv[i][0] != '-')
487                                         {
488                                                 fullScreenBpp = atoi(argv[i++]);
489                                                 if ((i + 1) <= argc && argv[i][0] != '-')
490                                                         fullScreenFrequency = atoi(argv[i++]);
491                                         }
492                                 }
493                                 break;
494                         case 'w':
495                                 // Parse window position and size options
496                                 i++;
497                                 fullScreen = false;
498                                 windowParFound = true;
499
500                                 if ((i + 2) <= argc && argv[i][0] != '-' && argv[i+1][0] != '-')
501                                 {
502                                         windowWidth = atoi(argv[i++]);
503                                         windowHeight = atoi(argv[i++]);
504                                         if ((i +2) <= argc && argv[i][0] != '-' && argv[i+1][0] != '-')
505                                         {
506                                                 windowLeft = atoi(argv[i++]);
507                                                 windowTop = atoi(argv[i++]);
508                                         }
509                                 }
510                                 break;
511                                         
512                         case 'h':
513                                 usage(argv[0]);
514                                 return 0;
515                                 break;
516 #ifndef _WIN32
517                         case 'i':
518                                 i++;
519                                 if ( (i + 1) < argc )
520                                         parentWindow = atoi(argv[i++]);                                         
521 #ifndef NDEBUG
522                                 printf("XWindows ID = %d\n", parentWindow);
523 #endif //NDEBUG
524
525 #endif  // _WIN32                       
526                         case 'c':
527                                 i++;
528                                 closeConsole = false;
529                                 break;
530                         case 's':  // stereo
531                                 i++;
532                                 if ((i + 1) < argc)
533                                 {
534                                         stereomode = (RAS_IRasterizer::StereoMode) atoi(argv[i]);
535                                         if (stereomode < RAS_IRasterizer::RAS_STEREO_NOSTEREO || stereomode >= RAS_IRasterizer::RAS_STEREO_MAXSTEREO)
536                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
537                                         
538                                         if(!strcmp(argv[i], "nostereo"))  // ok, redundant but clear
539                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
540                                         
541                                         // only the hardware pageflip method needs a stereo window
542                                         else if(!strcmp(argv[i], "hwpageflip")) {
543                                                 stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
544                                                 stereoWindow = true;
545                                         }
546                                         else if(!strcmp(argv[i], "syncdoubling"))
547                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
548                                         
549                                         else if(!strcmp(argv[i], "anaglyph"))
550                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
551                                         
552                                         else if(!strcmp(argv[i], "sidebyside"))
553                                                 stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
554                                         
555                                         else if(!strcmp(argv[i], "vinterlace"))
556                                                 stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
557                                         
558 #if 0
559                                         // future stuff
560                                         else if(!strcmp(argv[i], "stencil")
561                                                 stereomode = RAS_STEREO_STENCIL;
562 #endif
563                                         
564                                         i++;
565                                         stereoParFound = true;
566                                         stereoFlag = STEREO_ENABLED;
567                                 }
568                                 else
569                                 {
570                                         error = true;
571                                         printf("error: too few options for stereo argument.\n");
572                                 }
573                                 break;
574                         case 'D':
575                                 stereoFlag = STEREO_DOME;
576                                 stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
577                                 i++;
578                                 if ((i + 1) < argc)
579                                 {
580                                         if(!strcmp(argv[i], "angle")){
581                                                 i++;
582                                                 domeFov = atoi(argv[i++]);
583                                         }
584                                         if(!strcmp(argv[i], "tilt")){
585                                                 i++;
586                                                 domeTilt = atoi(argv[i++]);
587                                         }
588                                         if(!strcmp(argv[i], "warpdata")){
589                                                 i++;
590                                                 domeWarp = argv[i++];
591                                         }
592                                         if(!strcmp(argv[i], "mode")){
593                                                 i++;
594                                                 if(!strcmp(argv[i], "fisheye"))
595                                                         domeMode = DOME_FISHEYE;
596                                                         
597                                                 else if(!strcmp(argv[i], "truncatedfront"))
598                                                         domeMode = DOME_TRUNCATED_FRONT;
599                                                         
600                                                 else if(!strcmp(argv[i], "truncatedrear"))
601                                                         domeMode = DOME_TRUNCATED_REAR;
602                                                         
603                                                 else if(!strcmp(argv[i], "cubemap"))
604                                                         domeMode = DOME_ENVMAP;
605                                                         
606                                                 else if(!strcmp(argv[i], "sphericalpanoramic"))
607                                                         domeMode = DOME_PANORAM_SPH;
608
609                                                 else
610                                                         printf("error: %s is not a valid dome mode.\n", argv[i]);
611                                         }
612                                         i++;
613                                 }
614                                 break;
615                         default:
616                                 printf("Unknown argument: %s\n", argv[i++]);
617                                 break;
618                         }
619                 }
620                 else
621                 {
622                         i++;
623                 }
624         }
625         
626         if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
627         {
628                 error = true;
629                 printf("error: window size too small.\n");
630         }
631         
632         if (error )
633         {
634                 usage(argv[0]);
635                 return 0;
636         }
637
638 #ifdef WIN32
639         if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
640 #endif
641         {
642 #ifdef __APPLE__
643                 //SYS_WriteCommandLineInt(syshandle, "show_framerate", 1);
644                 //SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
645                 //fullScreen = false;           // Can't use full screen
646 #endif
647
648                 if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0))
649                 {
650                         GPU_set_mipmap(0);
651                 }
652                 
653                 // Create the system
654                 if (GHOST_ISystem::createSystem() == GHOST_kSuccess)
655                 {
656                         GHOST_ISystem* system = GHOST_ISystem::getSystem();
657                         assertd(system);
658                         
659                         if (!fullScreenWidth || !fullScreenHeight)
660                                 system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
661                         // process first batch of events. If the user
662                         // drops a file on top off the blenderplayer icon, we 
663                         // recieve an event with the filename
664                         
665                         system->processEvents(0);
666                         
667                         // this bracket is needed for app (see below) to get out
668                         // of scope before GHOST_ISystem::disposeSystem() is called.
669                         {
670                                 int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
671                                 STR_String exitstring = "";
672                                 GPG_Application app(system);
673                                 bool firstTimeRunning = true;
674                                 char filename[FILE_MAXDIR + FILE_MAXFILE];
675                                 char pathname[FILE_MAXDIR + FILE_MAXFILE];
676                                 char *titlename;
677
678                                 get_filename(argc_py_clamped, argv, filename);
679                                 if(filename[0])
680                                         BLI_path_cwd(filename);
681                                 
682                                 do
683                                 {
684                                         // Read the Blender file
685                                         BlendFileData *bfd;
686                                         
687                                         // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
688                                         if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
689                                         {
690                                                 char basedpath[240];
691                                                 
692                                                 // base the actuator filename relative to the last file
693                                                 strcpy(basedpath, exitstring.Ptr());
694                                                 BLI_path_abs(basedpath, pathname);
695                                                 
696                                                 bfd = load_game_data(basedpath);
697
698                                                 if (!bfd)
699                                                 {
700                                                         // just add "//" in front of it
701                                                         char temppath[242];
702                                                         strcpy(temppath, "//");
703                                                         strcat(temppath, basedpath);
704                                 
705                                                         BLI_path_abs(temppath, pathname);
706                                                         bfd = load_game_data(temppath);
707                                                 }
708                                         }
709                                         else
710                                         {
711                                                 bfd = load_game_data(bprogname, filename[0]? filename: NULL);
712                                         }
713                                         
714                                         //::printf("game data loaded from %s\n", filename);
715                                         
716                                         if (!bfd) {
717                                                 usage(argv[0]);
718                                                 error = true;
719                                                 exitcode = KX_EXIT_REQUEST_QUIT_GAME;
720                                         } 
721                                         else 
722                                         {
723 #ifdef WIN32
724 #ifdef NDEBUG
725                                                 if (closeConsole)
726                                                 {
727                                                         //::FreeConsole();    // Close a console window
728                                                 }
729 #endif // NDEBUG
730 #endif // WIN32
731                                                 Main *maggie = bfd->main;
732                                                 Scene *scene = bfd->curscene;
733                                                 G.main = maggie;
734
735                                                 if (firstTimeRunning)
736                                                         G.fileflags  = bfd->fileflags;
737
738                                                 //Seg Fault; icon.c gIcons == 0
739                                                 BKE_icons_init(1);
740                                                 
741                                                 titlename = maggie->name;
742                                                 
743                                                 // Check whether the game should be displayed full-screen
744                                                 if ((!fullScreenParFound) && (!windowParFound))
745                                                 {
746                                                         // Only use file settings when command line did not override
747                                                         if (scene->gm.fullscreen) {
748                                                                 //printf("fullscreen option found in Blender file\n");
749                                                                 fullScreen = true;
750                                                                 fullScreenWidth= scene->gm.xplay;
751                                                                 fullScreenHeight= scene->gm.yplay;
752                                                                 fullScreenFrequency= scene->gm.freqplay;
753                                                                 fullScreenBpp = scene->gm.depth;
754                                                         }
755                                                         else
756                                                         {
757                                                                 fullScreen = false;
758                                                                 windowWidth = scene->gm.xplay;
759                                                                 windowHeight = scene->gm.yplay;
760                                                         }
761                                                 }
762                                                 
763                                                 
764                                                 // Check whether the game should be displayed in stereo
765                                                 if (!stereoParFound)
766                                                 {
767                                                         if(scene->gm.stereoflag == STEREO_ENABLED){
768                                                                 stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
769                                                                 if (stereomode != RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
770                                                                         stereoWindow = true;
771                                                         }
772                                                 }
773                                                 else
774                                                         scene->gm.stereoflag = STEREO_ENABLED;
775
776                                                 if (stereoFlag == STEREO_DOME){
777                                                         stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
778                                                         scene->gm.stereoflag = STEREO_DOME;
779                                                         if (domeFov > 89)
780                                                                 scene->gm.dome.angle = domeFov;
781                                                         if (domeTilt > -180)
782                                                                 scene->gm.dome.tilt = domeTilt;
783                                                         if (domeMode > 0)
784                                                                 scene->gm.dome.mode = domeMode;
785                                                         if (domeWarp)
786                                                         {
787                                                                 //XXX to do: convert relative to absolute path
788                                                                 domeText= add_text(domeWarp, "");
789                                                                 if(!domeText)
790                                                                         printf("error: invalid warpdata text file - %s\n", domeWarp);
791                                                                 else
792                                                                         scene->gm.dome.warptext = domeText;
793                                                         }
794                                                 }
795                                                 
796                                                 //                                      GPG_Application app (system, maggie, startscenename);
797                                                 app.SetGameEngineData(maggie, scene, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
798                                                 
799                                                 BLI_strncpy(pathname, maggie->name, sizeof(pathname));
800                                                 BLI_strncpy(G.sce, maggie->name, sizeof(G.sce));
801                                                 setGamePythonPath(G.sce);
802
803                                                 if (firstTimeRunning)
804                                                 {
805                                                         firstTimeRunning = false;
806
807                                                         if (fullScreen)
808                                                         {
809 #ifdef WIN32
810                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
811                                                                 {
812                                                                         app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
813                                                                                 stereoWindow, stereomode);
814                                                                 }
815                                                                 else
816 #endif
817                                                                 {
818                                                                         app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
819                                                                                 stereoWindow, stereomode);
820                                                                 }
821                                                         }
822                                                         else
823                                                         {
824 #ifdef __APPLE__
825                                                                 // on Mac's we'll show the executable name instead of the 'game.blend' name
826                                                                 char tempname[1024], *appstring;
827                                                                 ::strcpy(tempname, titlename);
828                                                                 
829                                                                 appstring = strstr(tempname, ".app/");
830                                                                 if (appstring) {
831                                                                         appstring[2] = 0;
832                                                                         titlename = &tempname[0];
833                                                                 }
834 #endif
835                                                                 // Strip the path so that we have the name of the game file
836                                                                 STR_String path = titlename;
837 #ifndef WIN32
838                                                                 vector<STR_String> parts = path.Explode('/');
839 #else  // WIN32
840                                                                 vector<STR_String> parts = path.Explode('\\');
841 #endif // WIN32                        
842                                                                 STR_String title;
843                                                                 if (parts.size())
844                                                                 {
845                                                                         title = parts[parts.size()-1];
846                                                                         parts = title.Explode('.');
847                                                                         if (parts.size() > 1)
848                                                                         {
849                                                                                 title = parts[0];
850                                                                         }
851                                                                 }
852                                                                 else
853                                                                 {
854                                                                         title = "blenderplayer";
855                                                                 }
856 #ifdef WIN32
857                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
858                                                                 {
859                                                                         app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode);
860                                                                 }
861                                                                 else
862 #endif
863                                                                 {
864                                                                                                                                                                                                                 if (parentWindow != 0)
865                                                                                 app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode);
866                                                                         else
867                                                                                 app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
868                                                                                 stereoWindow, stereomode);
869                                                                 }
870                                                         }
871                                                 }
872                                                 else
873                                                 {
874                                                         app.StartGameEngine(stereomode);
875                                                         exitcode = KX_EXIT_REQUEST_NO_REQUEST;
876                                                 }
877                                                 
878                                                 // Add the application as event consumer
879                                                 system->addEventConsumer(&app);
880                                                 
881                                                 // Enter main loop
882                                                 bool run = true;
883                                                 while (run)
884                                                 {
885                                                         system->processEvents(false);
886                                                         system->dispatchEvents();
887                                                         if ((exitcode = app.getExitRequested()))
888                                                         {
889                                                                 run = false;
890                                                                 exitstring = app.getExitString();
891                                                         }
892                                                 }
893                                                 app.StopGameEngine();
894
895                                                 BLO_blendfiledata_free(bfd);
896                                         }
897                                 } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
898                         }
899
900                         // Seg Fault; icon.c gIcons == 0
901                         BKE_icons_free();
902
903                         // Dispose the system
904                         GHOST_ISystem::disposeSystem();
905                 } else {
906                         error = true;
907                         printf("error: couldn't create a system.\n");
908                 }
909         }
910
911         free_nodesystem();
912
913         return error ? -1 : 0;
914 }
915
916