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