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