style cleanup: comment format
[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 #include "KX_PythonMain.h"
51
52 /**********************************
53 * Begin Blender include block
54 **********************************/
55 #ifdef __cplusplus
56 extern "C"
57 {
58 #endif  // __cplusplus
59 #include "MEM_guardedalloc.h"
60 #include "BKE_blender.h"
61 #include "BKE_global.h"
62 #include "BKE_icons.h"
63 #include "BKE_image.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 // For BLF
80 #include "BLF_api.h"
81 #include "BLF_translation.h"
82 extern int datatoc_bfont_ttf_size;
83 extern char datatoc_bfont_ttf[];
84
85 #ifdef __cplusplus
86 }
87 #endif // __cplusplus
88
89 #include "GPU_draw.h"
90
91 /**********************************
92 * End Blender include block
93 **********************************/
94
95 #include "BL_System.h"
96 #include "GPG_Application.h"
97
98 #include "GHOST_ISystem.h"
99 #include "RAS_IRasterizer.h"
100
101 #include "BKE_main.h"
102
103 #include "RNA_define.h"
104
105 #ifdef WIN32
106 #include <windows.h>
107 #if !defined(DEBUG)
108 #include <wincon.h>
109 #endif // !defined(DEBUG)
110 #endif // WIN32
111
112 const int kMinWindowWidth = 100;
113 const int kMinWindowHeight = 100;
114
115 static void mem_error_cb(const char *errorStr)
116 {
117         fprintf(stderr, "%s", errorStr);
118         fflush(stderr);
119 }
120
121 #ifdef WIN32
122 typedef enum {
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 static void usage(const char* program, bool isBlenderPlayer)
177 {
178         const char * consoleoption;
179         const char * example_filename = "";
180         const char * example_pathname = "";
181
182 #ifdef _WIN32
183         consoleoption = "-c ";
184 #else
185         consoleoption = "";
186 #endif
187
188         if (isBlenderPlayer) {
189                 example_filename = "filename.blend";
190 #ifdef _WIN32
191                 example_pathname = "c:\\";
192 #else
193                 example_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, example_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, example_pathname, example_filename);
254         printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename);
255         printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_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_MAX);
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_MAX);
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_MAX);
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_MAX);
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 static bool GPG_NextFrame(GHOST_ISystem* system, GPG_Application *app, int &exitcode, STR_String &exitstring, GlobalSettings *gs)
337 {
338         bool run = true;
339         system->processEvents(false);
340         system->dispatchEvents();
341         app->EngineNextFrame();
342         if ((exitcode = app->getExitRequested())) {
343                 run = false;
344                 exitstring = app->getExitString();
345                 *gs = *app->getGlobalSettings();
346         }
347         return run;
348 }
349
350 struct GPG_NextFrameState {
351         GHOST_ISystem* system;
352         GPG_Application *app;
353         GlobalSettings *gs;
354 } gpg_nextframestate;
355
356 static int GPG_PyNextFrame(void *state0)
357 {
358         GPG_NextFrameState *state = (GPG_NextFrameState *) state0;
359         int exitcode;
360         STR_String exitstring;
361         bool run = GPG_NextFrame(state->system, state->app, exitcode, exitstring, state->gs);
362         if (run) return 0;  
363         else {
364                 if (exitcode) 
365                         fprintf(stderr, "Exit code %d: %s\n", exitcode, exitstring.ReadPtr());
366                 return 1;
367         }
368 }
369
370 int main(int argc, char** argv)
371 {
372         int i;
373         int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
374         bool error = false;
375         SYS_SystemHandle syshandle = SYS_GetSystem();
376         bool fullScreen = false;
377         bool fullScreenParFound = false;
378         bool windowParFound = false;
379 #ifdef WIN32
380         bool closeConsole = true;
381 #endif
382         RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
383         bool stereoWindow = false;
384         bool stereoParFound = false;
385         int stereoFlag = STEREO_NOSTEREO;
386         int domeFov = -1;
387         int domeTilt = -200;
388         int domeMode = 0;
389         char* domeWarp = NULL;
390         Text *domeText  = NULL;
391         int windowLeft = 100;
392         int windowTop = 100;
393         int windowWidth = 640;
394         int windowHeight = 480;
395         GHOST_TUns32 fullScreenWidth = 0;
396         GHOST_TUns32 fullScreenHeight= 0;
397         int fullScreenBpp = 32;
398         int fullScreenFrequency = 60;
399         GHOST_TEmbedderWindowID parentWindow = 0;
400         bool isBlenderPlayer = false;
401         int validArguments=0;
402         bool samplesParFound = false;
403         GHOST_TUns16 aasamples = 0;
404         
405 #ifdef __linux__
406 #ifdef __alpha__
407         signal (SIGFPE, SIG_IGN);
408 #endif /* __alpha__ */
409 #endif /* __linux__ */
410         BLI_init_program_path(argv[0]);
411         BLI_init_temporary_dir(NULL);
412 #ifdef __APPLE__
413         // Can't use Carbon right now because of double defined type ID (In Carbon.h and DNA_ID.h, sigh)
414         /*
415         IBNibRef                nibRef;
416         WindowRef               window;
417         OSStatus                err;
418
419           // Create a Nib reference passing the name of the nib file (without the .nib extension)
420           // CreateNibReference only searches into the application bundle.
421           err = ::CreateNibReference(CFSTR("main"), &nibRef);
422           if (err) return -1;
423           
424                 // Once the nib reference is created, set the menu bar. "MainMenu" is the name of the menu bar
425                 // object. This name is set in InterfaceBuilder when the nib is created.
426                 err = ::SetMenuBarFromNib(nibRef, CFSTR("MenuBar"));
427                 if (err) return -1;
428                 
429                   // We don't need the nib reference anymore.
430                   ::DisposeNibReference(nibRef);
431         */
432 #endif // __APPLE__
433         
434         // We don't use threads directly in the BGE, but we need to call this so things like
435         // freeing up GPU_Textures works correctly.
436         BLI_threadapi_init();
437
438         RNA_init();
439
440         init_nodesystem();
441         
442         initglobals();
443
444         U.gameflags |= USER_DISABLE_VBO;
445         // We load our own G.main, so free the one that initglobals() gives us
446         free_main(G.main);
447         G.main = NULL;
448
449         IMB_init();
450         BKE_images_init();
451
452         // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c)
453         BLF_init(11, U.dpi);
454         BLF_lang_init();
455         BLF_lang_set("");
456
457         BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
458
459         // Parse command line options
460 #if defined(DEBUG)
461         printf("argv[0] = '%s'\n", argv[0]);
462 #endif
463
464 #ifdef WIN32
465         if (scr_saver_init(argc, argv))
466         {
467                 switch (scr_saver_mode)
468                 {
469                 case SCREEN_SAVER_MODE_CONFIGURATION:
470                         MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
471                         break;
472                 case SCREEN_SAVER_MODE_PASSWORD:
473                         /* This is W95 only, which we currently do not support.
474                          * Fall-back to normal screen saver behavior in that case... */
475                 case SCREEN_SAVER_MODE_SAVER:
476                         fullScreen = true;
477                         fullScreenParFound = true;
478                         break;
479
480                 case SCREEN_SAVER_MODE_PREVIEW:
481                         /* This will actually be handled somewhere below... */
482                         break;
483                 }
484         }
485 #endif
486         // XXX add the ability to change this values to the command line parsing.
487         U.mixbufsize = 2048;
488         U.audiodevice = 2;
489         U.audiorate = 44100;
490         U.audioformat = 0x24;
491         U.audiochannels = 2;
492
493         // XXX this one too
494         U.anisotropic_filter = 2;
495         // enable fast mipmap generation
496         U.use_gpu_mipmap = 1;
497
498         sound_init_once();
499
500         /* if running blenderplayer the last argument can't be parsed since it has to be the filename. */
501         isBlenderPlayer = !BLO_is_a_runtime(argv[0]);
502         if (isBlenderPlayer)
503                 validArguments = argc - 1;
504         else
505                 validArguments = argc;
506
507         for (i = 1; (i < validArguments) && !error 
508 #ifdef WIN32
509                 && scr_saver_mode == SCREEN_SAVER_MODE_NONE
510 #endif
511                 ;)
512
513         {
514 #if defined(DEBUG)
515                 printf("argv[%d] = '%s', %i\n", i, argv[i],argc);
516 #endif
517                 if (argv[i][0] == '-')
518                 {
519                         /* ignore all args after " - ", allow python to have own args */
520                         if (argv[i][1]=='\0') {
521                                 argc_py_clamped= i;
522                                 break;
523                         }
524                         
525                         switch (argv[i][1])
526                         {
527                         case 'g':
528                                 // Parse game options
529                                 {
530                                         i++;
531                                         if (i <= validArguments)
532                                         {
533                                                 char* paramname = argv[i];
534                                                 // Check for single value versus assignment
535                                                 if (i+1 <= validArguments && (*(argv[i+1]) == '='))
536                                                 {
537                                                         i++;
538                                                         if (i + 1 <= validArguments)
539                                                         {
540                                                                 i++;
541                                                                 // Assignment
542                                                                 SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
543                                                                 SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
544                                                                 SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
545 #if defined(DEBUG)
546                                                                 printf("%s = '%s'\n", paramname, argv[i]);
547 #endif
548                                                                 i++;
549                                                         }
550                                                         else
551                                                         {
552                                                                 error = true;
553                                                                 printf("error: argument assignment %s without value.\n", paramname);
554                                                         }
555                                                 }
556                                                 else
557                                                 {
558 //                                                      SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
559                                                 }
560                                         }
561                                 }
562                                 break;
563
564                         case 'd':
565                                 i++;
566                                 G.debug |= G_DEBUG;     /* std output printf's */
567                                 MEM_set_memory_debug();
568                                 break;
569
570                         case 'f':
571                                 i++;
572                                 fullScreen = true;
573                                 fullScreenParFound = true;
574                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
575                                 {
576                                         fullScreenWidth = atoi(argv[i++]);
577                                         fullScreenHeight = atoi(argv[i++]);
578                                         if ((i + 1) <= validArguments && argv[i][0] != '-')
579                                         {
580                                                 fullScreenBpp = atoi(argv[i++]);
581                                                 if ((i + 1) <= validArguments && argv[i][0] != '-')
582                                                         fullScreenFrequency = atoi(argv[i++]);
583                                         }
584                                 }
585                                 break;
586                         case 'w':
587                                 // Parse window position and size options
588                                 i++;
589                                 fullScreen = false;
590                                 windowParFound = true;
591
592                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
593                                 {
594                                         windowWidth = atoi(argv[i++]);
595                                         windowHeight = atoi(argv[i++]);
596                                         if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
597                                         {
598                                                 windowLeft = atoi(argv[i++]);
599                                                 windowTop = atoi(argv[i++]);
600                                         }
601                                 }
602                                 break;
603                                         
604                         case 'h':
605                                 usage(argv[0], isBlenderPlayer);
606                                 return 0;
607                                 break;
608                         case 'i':
609                                 i++;
610                                 if ( (i + 1) <= validArguments )
611                                         parentWindow = atoi(argv[i++]); 
612                                 else {
613                                         error = true;
614                                         printf("error: too few options for parent window argument.\n");
615                                 }
616 #if defined(DEBUG)
617                                 printf("XWindows ID = %d\n", parentWindow);
618 #endif // defined(DEBUG)
619                                 break;
620                         case 'm':
621                                 i++;
622                                 samplesParFound = true;
623                                 if ((i+1) <= validArguments )
624                                         aasamples = atoi(argv[i++]);
625                                 else
626                                 {
627                                         error = true;
628                                         printf("error: No argument supplied for -m");
629                                 }
630                                 break;
631                         case 'c':
632                                 i++;
633 #ifdef WIN32
634                                 closeConsole = false;
635 #endif
636                                 break;
637                         case 's':  // stereo
638                                 i++;
639                                 if ((i + 1) <= validArguments)
640                                 {
641                                         stereomode = (RAS_IRasterizer::StereoMode) atoi(argv[i]);
642                                         if (stereomode < RAS_IRasterizer::RAS_STEREO_NOSTEREO || stereomode >= RAS_IRasterizer::RAS_STEREO_MAXSTEREO)
643                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
644                                         
645                                         if (!strcmp(argv[i], "nostereo"))  // ok, redundant but clear
646                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
647                                         
648                                         // only the hardware pageflip method needs a stereo window
649                                         else if (!strcmp(argv[i], "hwpageflip")) {
650                                                 stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
651                                                 stereoWindow = true;
652                                         }
653                                         else if (!strcmp(argv[i], "syncdoubling"))
654                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
655                                         
656                                         else if (!strcmp(argv[i], "anaglyph"))
657                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
658                                         
659                                         else if (!strcmp(argv[i], "sidebyside"))
660                                                 stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
661                                         
662                                         else if (!strcmp(argv[i], "vinterlace"))
663                                                 stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
664                                         
665 #if 0
666                                         // future stuff
667                                         else if (!strcmp(argv[i], "stencil")
668                                                 stereomode = RAS_STEREO_STENCIL;
669 #endif
670                                         
671                                         i++;
672                                         stereoParFound = true;
673                                         stereoFlag = STEREO_ENABLED;
674                                 }
675                                 else
676                                 {
677                                         error = true;
678                                         printf("error: too few options for stereo argument.\n");
679                                 }
680                                 break;
681                         case 'D':
682                                 stereoFlag = STEREO_DOME;
683                                 stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
684                                 i++;
685                                 if ((i + 1) <= validArguments)
686                                 {
687                                         if (!strcmp(argv[i], "angle")) {
688                                                 i++;
689                                                 domeFov = atoi(argv[i++]);
690                                         }
691                                         if (!strcmp(argv[i], "tilt")) {
692                                                 i++;
693                                                 domeTilt = atoi(argv[i++]);
694                                         }
695                                         if (!strcmp(argv[i], "warpdata")) {
696                                                 i++;
697                                                 domeWarp = argv[i++];
698                                         }
699                                         if (!strcmp(argv[i], "mode")) {
700                                                 i++;
701                                                 if (!strcmp(argv[i], "fisheye"))
702                                                         domeMode = DOME_FISHEYE;
703                                                         
704                                                 else if (!strcmp(argv[i], "truncatedfront"))
705                                                         domeMode = DOME_TRUNCATED_FRONT;
706                                                         
707                                                 else if (!strcmp(argv[i], "truncatedrear"))
708                                                         domeMode = DOME_TRUNCATED_REAR;
709                                                         
710                                                 else if (!strcmp(argv[i], "cubemap"))
711                                                         domeMode = DOME_ENVMAP;
712                                                         
713                                                 else if (!strcmp(argv[i], "sphericalpanoramic"))
714                                                         domeMode = DOME_PANORAM_SPH;
715
716                                                 else
717                                                         printf("error: %s is not a valid dome mode.\n", argv[i]);
718                                         }
719                                         i++;
720                                 }
721                                 break;
722                         default:
723                                 printf("Unknown argument: %s\n", argv[i++]);
724                                 break;
725                         }
726                 }
727                 else
728                 {
729                         i++;
730                 }
731         }
732         
733         if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
734         {
735                 error = true;
736                 printf("error: window size too small.\n");
737         }
738         
739         if (error )
740         {
741                 usage(argv[0], isBlenderPlayer);
742                 return 0;
743         }
744
745 #ifdef WIN32
746         if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
747 #endif
748         {
749 #ifdef __APPLE__
750                 //SYS_WriteCommandLineInt(syshandle, "show_framerate", 1);
751                 //SYS_WriteCommandLineInt(syshandle, "nomipmap", 1);
752                 //fullScreen = false;           // Can't use full screen
753 #endif
754
755                 if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0))
756                 {
757                         GPU_set_mipmap(0);
758                 }
759
760                 GPU_set_anisotropic(U.anisotropic_filter);
761                 GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
762                 
763                 // Create the system
764                 if (GHOST_ISystem::createSystem() == GHOST_kSuccess)
765                 {
766                         GHOST_ISystem* system = GHOST_ISystem::getSystem();
767                         assertd(system);
768                         
769                         if (!fullScreenWidth || !fullScreenHeight)
770                                 system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
771                         // process first batch of events. If the user
772                         // drops a file on top off the blenderplayer icon, we 
773                         // receive an event with the filename
774                         
775                         system->processEvents(0);
776                         
777                         // this bracket is needed for app (see below) to get out
778                         // of scope before GHOST_ISystem::disposeSystem() is called.
779                         {
780                                 int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
781                                 STR_String exitstring = "";
782                                 GPG_Application app(system);
783                                 bool firstTimeRunning = true;
784                                 char filename[FILE_MAX];
785                                 char pathname[FILE_MAX];
786                                 char *titlename;
787
788                                 get_filename(argc_py_clamped, argv, filename);
789                                 if (filename[0])
790                                         BLI_path_cwd(filename);
791                                 
792
793                                 // fill the GlobalSettings with the first scene files
794                                 // those may change during the game and persist after using Game Actuator
795                                 GlobalSettings gs;
796
797                                 do
798                                 {
799                                         // Read the Blender file
800                                         BlendFileData *bfd;
801                                         
802                                         // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
803                                         if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
804                                         {
805                                                 char basedpath[FILE_MAX];
806                                                 
807                                                 // base the actuator filename relative to the last file
808                                                 BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath));
809                                                 BLI_path_abs(basedpath, pathname);
810                                                 
811                                                 bfd = load_game_data(basedpath);
812
813                                                 if (!bfd)
814                                                 {
815                                                         // just add "//" in front of it
816                                                         char temppath[242];
817                                                         strcpy(temppath, "//");
818                                                         strcat(temppath, basedpath);
819                                 
820                                                         BLI_path_abs(temppath, pathname);
821                                                         bfd = load_game_data(temppath);
822                                                 }
823                                         }
824                                         else
825                                         {
826                                                 bfd = load_game_data(BLI_program_path(), filename[0]? filename: NULL);
827                                         }
828                                         
829                                         //::printf("game data loaded from %s\n", filename);
830                                         
831                                         if (!bfd) {
832                                                 usage(argv[0], isBlenderPlayer);
833                                                 error = true;
834                                                 exitcode = KX_EXIT_REQUEST_QUIT_GAME;
835                                         } 
836                                         else 
837                                         {
838 #ifdef WIN32
839 #if !defined(DEBUG)
840                                                 if (closeConsole)
841                                                 {
842                                                         system->toggleConsole(0); // Close a console window
843                                                 }
844 #endif // !defined(DEBUG)
845 #endif // WIN32
846                                                 Main *maggie = bfd->main;
847                                                 Scene *scene = bfd->curscene;
848                                                 G.main = maggie;
849
850                                                 if (firstTimeRunning) {
851                                                         G.fileflags  = bfd->fileflags;
852
853                                                         gs.matmode= scene->gm.matmode;
854                                                         gs.glslflag= scene->gm.flag;
855                                                 }
856
857                                                 //Seg Fault; icon.c gIcons == 0
858                                                 BKE_icons_init(1);
859                                                 
860                                                 titlename = maggie->name;
861                                                 
862                                                 // Check whether the game should be displayed full-screen
863                                                 if ((!fullScreenParFound) && (!windowParFound))
864                                                 {
865                                                         // Only use file settings when command line did not override
866                                                         if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
867                                                                 //printf("fullscreen option found in Blender file\n");
868                                                                 fullScreen = true;
869                                                                 fullScreenWidth= scene->gm.xplay;
870                                                                 fullScreenHeight= scene->gm.yplay;
871                                                                 fullScreenFrequency= scene->gm.freqplay;
872                                                                 fullScreenBpp = scene->gm.depth;
873                                                         }
874                                                         else
875                                                         {
876                                                                 fullScreen = false;
877                                                                 windowWidth = scene->gm.xplay;
878                                                                 windowHeight = scene->gm.yplay;
879                                                         }
880                                                 }
881                                                 
882                                                 
883                                                 // Check whether the game should be displayed in stereo
884                                                 if (!stereoParFound)
885                                                 {
886                                                         if (scene->gm.stereoflag == STEREO_ENABLED) {
887                                                                 stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
888                                                                 if (stereomode == RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
889                                                                         stereoWindow = true;
890                                                         }
891                                                 }
892                                                 else
893                                                         scene->gm.stereoflag = STEREO_ENABLED;
894
895                                                 if (!samplesParFound)
896                                                         aasamples = scene->gm.aasamples;
897
898                                                 if (stereoFlag == STEREO_DOME) {
899                                                         stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
900                                                         scene->gm.stereoflag = STEREO_DOME;
901                                                         if (domeFov > 89)
902                                                                 scene->gm.dome.angle = domeFov;
903                                                         if (domeTilt > -180)
904                                                                 scene->gm.dome.tilt = domeTilt;
905                                                         if (domeMode > 0)
906                                                                 scene->gm.dome.mode = domeMode;
907                                                         if (domeWarp)
908                                                         {
909                                                                 //XXX to do: convert relative to absolute path
910                                                                 domeText= BKE_text_load(domeWarp, "");
911                                                                 if (!domeText)
912                                                                         printf("error: invalid warpdata text file - %s\n", domeWarp);
913                                                                 else
914                                                                         scene->gm.dome.warptext = domeText;
915                                                         }
916                                                 }
917                                                 
918                                                 //                                      GPG_Application app (system, maggie, startscenename);
919                                                 app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
920                                                 BLI_strncpy(pathname, maggie->name, sizeof(pathname));
921                                                 if (G.main != maggie) {
922                                                         BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name));
923                                                 }
924 #ifdef WITH_PYTHON
925                                                 setGamePythonPath(G.main->name);
926 #endif
927                                                 if (firstTimeRunning)
928                                                 {
929                                                         firstTimeRunning = false;
930
931                                                         if (fullScreen)
932                                                         {
933 #ifdef WIN32
934                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
935                                                                 {
936                                                                         app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
937                                                                                 stereoWindow, stereomode, aasamples);
938                                                                 }
939                                                                 else
940 #endif
941                                                                 {
942                                                                         app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
943                                                                                 stereoWindow, stereomode, aasamples, (scene->gm.playerflag & GAME_PLAYER_DESKTOP_RESOLUTION));
944                                                                 }
945                                                         }
946                                                         else
947                                                         {
948 #ifdef __APPLE__
949                                                                 // on Mac's we'll show the executable name instead of the 'game.blend' name
950                                                                 char tempname[1024], *appstring;
951                                                                 ::strcpy(tempname, titlename);
952                                                                 
953                                                                 appstring = strstr(tempname, ".app/");
954                                                                 if (appstring) {
955                                                                         appstring[2] = 0;
956                                                                         titlename = &tempname[0];
957                                                                 }
958 #endif
959                                                                 // Strip the path so that we have the name of the game file
960                                                                 STR_String path = titlename;
961 #ifndef WIN32
962                                                                 vector<STR_String> parts = path.Explode('/');
963 #else  // WIN32
964                                                                 vector<STR_String> parts = path.Explode('\\');
965 #endif // WIN32                        
966                                                                 STR_String title;
967                                                                 if (parts.size())
968                                                                 {
969                                                                         title = parts[parts.size()-1];
970                                                                         parts = title.Explode('.');
971                                                                         if (parts.size() > 1)
972                                                                         {
973                                                                                 title = parts[0];
974                                                                         }
975                                                                 }
976                                                                 else
977                                                                 {
978                                                                         title = "blenderplayer";
979                                                                 }
980 #ifdef WIN32
981                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
982                                                                 {
983                                                                         app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples);
984                                                                 }
985                                                                 else
986 #endif
987                                                                 {
988                                                                                                                                                                                                                 if (parentWindow != 0)
989                                                                                 app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples);
990                                                                         else
991                                                                                 app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
992                                                                                 stereoWindow, stereomode, aasamples);
993                                                                 }
994                                                         }
995                                                 }
996                                                 else
997                                                 {
998                                                         app.StartGameEngine(stereomode);
999                                                         exitcode = KX_EXIT_REQUEST_NO_REQUEST;
1000                                                 }
1001                                                 
1002                                                 // Add the application as event consumer
1003                                                 system->addEventConsumer(&app);
1004                                                 
1005                                                 // Enter main loop
1006                                                 bool run = true;
1007                                                 char *python_main = NULL;
1008                                                 pynextframestate.state = NULL;
1009                                                 pynextframestate.func = NULL;
1010 #ifdef WITH_PYTHON
1011                                                 python_main = KX_GetPythonMain(scene);
1012 #endif // WITH_PYTHON
1013                                                 if (python_main) 
1014                                                 {
1015                                                         char *python_code = KX_GetPythonCode(maggie, python_main);
1016                                                         if (python_code)
1017                                                         {
1018 #ifdef WITH_PYTHON
1019                                                                 gpg_nextframestate.system = system;
1020                                                                 gpg_nextframestate.app = &app;
1021                                                                 gpg_nextframestate.gs = &gs;
1022                                                                 pynextframestate.state = &gpg_nextframestate;
1023                                                                 pynextframestate.func = &GPG_PyNextFrame;
1024
1025                                                                 printf("Yielding control to Python script '%s'...\n", python_main);
1026                                                                 PyRun_SimpleString(python_code);
1027                                                                 printf("Exit Python script '%s'\n", python_main);
1028 #endif // WITH_PYTHON
1029                                                                 MEM_freeN(python_code);
1030                                                         }
1031                                                         else {
1032                                                                 fprintf(stderr, "ERROR: cannot yield control to Python: no Python text data block named '%s'\n", python_main);
1033                                                         }
1034                                                 }
1035                                                 else
1036                                                 {
1037                                                         while (run)
1038                                                         {
1039                                                                 run = GPG_NextFrame(system, &app, exitcode, exitstring, &gs);
1040                                                         }
1041                                                 }
1042                                                 app.StopGameEngine();
1043
1044                                                 /* 'app' is freed automatic when out of scope. 
1045                                                  * removal is needed else the system will free an already freed value */
1046                                                 system->removeEventConsumer(&app);
1047
1048                                                 BLO_blendfiledata_free(bfd);
1049                                                 if (python_main) MEM_freeN(python_main);
1050                                         }
1051                                 } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
1052                         }
1053
1054                         // Seg Fault; icon.c gIcons == 0
1055                         BKE_icons_free();
1056
1057                         // Dispose the system
1058                         GHOST_ISystem::disposeSystem();
1059                 } else {
1060                         error = true;
1061                         printf("error: couldn't create a system.\n");
1062                 }
1063         }
1064
1065         // Cleanup
1066         RNA_exit();
1067         BLF_exit();
1068
1069 #ifdef WITH_INTERNATIONAL
1070         BLF_free_unifont();
1071         BLF_lang_free();
1072 #endif
1073
1074         IMB_exit();
1075         BKE_images_exit();
1076         free_nodesystem();
1077
1078         SYS_DeleteSystem(syshandle);
1079
1080         int totblock= MEM_get_memory_blocks_in_use();
1081         if (totblock!=0) {
1082                 printf("Error Totblock: %d\n",totblock);
1083                 MEM_set_error_callback(mem_error_cb);
1084                 MEM_printmemlist();
1085         }
1086
1087         return error ? -1 : 0;
1088 }
1089
1090