BGE: alpha on frame buffer and precedence of MSAA over swap.
[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 #include "KX_KetsjiEngine.h"
44 #include "KX_PythonInit.h"
45 #include "KX_PythonMain.h"
46 #include "KX_PyConstraintBinding.h" // for PHY_SetActiveEnvironment
47
48 /**********************************
49 * Begin Blender include block
50 **********************************/
51 #ifdef __cplusplus
52 extern "C"
53 {
54 #endif  // __cplusplus
55 #include "MEM_guardedalloc.h"
56 #include "MEM_CacheLimiterC-Api.h"
57
58 #include "BLI_threads.h"
59 #include "BLI_mempool.h"
60 #include "BLI_blenlib.h"
61
62 #include "DNA_scene_types.h"
63 #include "DNA_userdef_types.h"
64
65 #include "BLO_readfile.h"
66 #include "BLO_runtime.h"
67
68 #include "BKE_appdir.h"
69 #include "BKE_blender.h"
70 #include "BKE_depsgraph.h"
71 #include "BKE_global.h"
72 #include "BKE_icons.h"
73 #include "BKE_image.h"
74 #include "BKE_node.h"
75 #include "BKE_report.h"
76 #include "BKE_library.h"
77 #include "BKE_modifier.h"
78 #include "BKE_material.h"
79 #include "BKE_text.h"
80 #include "BKE_sound.h"
81
82 #include "IMB_imbuf.h"
83 #include "IMB_moviecache.h"
84         
85 #ifdef __APPLE__
86         int GHOST_HACK_getFirstFile(char buf[]);
87 #endif
88         
89 // For BLF
90 #include "BLF_api.h"
91 #include "BLT_translation.h"
92 #include "BLT_lang.h"
93 extern int datatoc_bfont_ttf_size;
94 extern char datatoc_bfont_ttf[];
95 extern int datatoc_bmonofont_ttf_size;
96 extern char datatoc_bmonofont_ttf[];
97
98 #ifdef __cplusplus
99 }
100 #endif // __cplusplus
101
102 #include "GPU_draw.h"
103
104 /**********************************
105 * End Blender include block
106 **********************************/
107
108 #include "BL_System.h"
109 #include "GPG_Application.h"
110
111 #include "GHOST_ISystem.h"
112 #include "RAS_IRasterizer.h"
113
114 #include "BKE_main.h"
115
116 #include "RNA_define.h"
117
118 #ifdef WIN32
119 #  include <windows.h>
120 #  if !defined(DEBUG)
121 #    include <wincon.h>
122 #  endif // !defined(DEBUG)
123 #  if defined(_MSC_VER) && defined(_M_X64)
124 #    include <math.h> /* needed for _set_FMA3_enable */
125 #  endif
126 #  include "utfconv.h"
127 #endif // WIN32
128
129 #ifdef WITH_SDL_DYNLOAD
130 #  include "sdlew.h"
131 #endif
132
133 const int kMinWindowWidth = 100;
134 const int kMinWindowHeight = 100;
135
136 static void mem_error_cb(const char *errorStr)
137 {
138         fprintf(stderr, "%s", errorStr);
139         fflush(stderr);
140 }
141
142 // library.c will only free window managers with a callback function.
143 // We don't actually use a wmWindowManager, but loading a blendfile
144 // loads wmWindows, so we need to free those.
145 static void wm_free(bContext *C, wmWindowManager *wm)
146 {
147         BLI_freelistN(&wm->windows);
148 }
149
150 #ifdef WIN32
151 typedef enum {
152         SCREEN_SAVER_MODE_NONE = 0,
153         SCREEN_SAVER_MODE_PREVIEW,
154         SCREEN_SAVER_MODE_SAVER,
155         SCREEN_SAVER_MODE_CONFIGURATION,
156         SCREEN_SAVER_MODE_PASSWORD,
157 } ScreenSaverMode;
158
159 static ScreenSaverMode scr_saver_mode = SCREEN_SAVER_MODE_NONE;
160 static HWND scr_saver_hwnd = NULL;
161
162 static BOOL scr_saver_init(int argc, char **argv) 
163 {
164         scr_saver_mode = SCREEN_SAVER_MODE_NONE;
165         scr_saver_hwnd = NULL;
166         BOOL ret = false;
167
168         int len = ::strlen(argv[0]);
169         if (len > 4 && !::stricmp(".scr", argv[0] + len - 4))
170         {
171                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
172                 ret = true;
173                 if (argc >= 2)
174                 {
175                         if (argc >= 3)
176                         {
177                                 scr_saver_hwnd = (HWND) ::atoi(argv[2]);
178                         }
179                         if (!::stricmp("/c", argv[1]))
180                         {
181                                 scr_saver_mode = SCREEN_SAVER_MODE_CONFIGURATION;
182                                 if (scr_saver_hwnd == NULL)
183                                         scr_saver_hwnd = ::GetForegroundWindow();
184                         }
185                         else if (!::stricmp("/s", argv[1]))
186                         {
187                                 scr_saver_mode = SCREEN_SAVER_MODE_SAVER;
188                         }
189                         else if (!::stricmp("/a", argv[1]))
190                         {
191                                 scr_saver_mode = SCREEN_SAVER_MODE_PASSWORD;
192                         }
193                         else if (!::stricmp("/p", argv[1])
194                                  || !::stricmp("/l", argv[1]))
195                         {
196                                 scr_saver_mode = SCREEN_SAVER_MODE_PREVIEW;
197                         }
198                 }
199         }
200         return ret;
201 }
202
203 #endif /* WIN32 */
204
205 static void usage(const char* program, bool isBlenderPlayer)
206 {
207         const char * consoleoption;
208         const char * example_filename = "";
209         const char * example_pathname = "";
210
211 #ifdef _WIN32
212         consoleoption = "[-c] ";
213 #else
214         consoleoption = "";
215 #endif
216
217         if (isBlenderPlayer) {
218                 example_filename = "filename.blend";
219 #ifdef _WIN32
220                 example_pathname = "c:\\";
221 #else
222                 example_pathname = "/home/user/";
223 #endif
224         }
225         printf("\n");
226         printf("usage:   %s [--options] %s\n\n", program, example_filename);
227         printf("Available options are: [-w [w h l t]] [-f [fw fh fb ff]] %s[-g gamengineoptions] ", consoleoption);
228         printf("[-s stereomode] [-m aasamples]\n");
229         printf("Optional parameters must be passed in order.\n");
230         printf("Default values are set in the blend file.\n\n");
231         printf("  -h: Prints this command summary\n\n");
232         printf("  -w: display in a window\n");
233         printf("       --Optional parameters--\n"); 
234         printf("       w = window width\n");
235         printf("       h = window height\n");
236         printf("       l = window left coordinate\n");
237         printf("       t = window top coordinate\n");
238         printf("       Note: To define 'w' or 'h', both must be used.");
239         printf("Also, to define 'l' or 't', all four parameters must be used.\n");
240         printf("       Example: -w   or  -w 500 300  or  -w 500 300 0 0\n\n");
241         printf("  -f: start game in fullscreen mode\n");
242         printf("       --Optional parameters--\n");
243         printf("       fw = fullscreen mode pixel width    (use 0 to detect automatically)\n");
244         printf("       fh = fullscreen mode pixel height   (use 0 to detect automatically)\n");
245         printf("       fb = fullscreen mode bits per pixel (default unless set in the blend file: 32)\n");
246         printf("       ff = fullscreen mode frequency      (default unless set in the blend file: 60)\n");
247         printf("       Note: To define 'fw'' or 'fh'', both must be used.\n");
248         printf("       Example: -f  or  -f 1024 768  or  -f 0 0 16  or  -f 1024 728 16 30\n\n");
249         printf("  -s: start player in stereoscopy mode (requires 3D capable hardware)\n");
250         printf("       stereomode: nostereo         (default unless stereo is set in the blend file)\n");
251         printf("                   anaglyph         (Red-Blue glasses)\n");
252         printf("                   sidebyside       (Left Right)\n");
253         printf("                   syncdoubling     (Above Below)\n");
254         printf("                   3dtvtopbottom    (Squashed Top-Bottom for passive glasses)\n");
255         printf("                   interlace        (Interlace horizontally)\n");
256         printf("                   vinterlace       (Vertical interlace for autostereo display)\n");
257         printf("                   hwpageflip       (Quad buffered shutter glasses)\n");
258         printf("       Example: -s sidebyside  or  -s vinterlace\n\n");
259         printf("  -D: start player in dome mode\n");
260         printf("       --Optional parameters--\n");
261         printf("       angle    = field of view in degrees\n");
262         printf("       tilt     = tilt angle in degrees\n");
263         printf("       warpdata = a file to use for warping the image (absolute path)\n");
264         printf("       mode: fisheye                (Fisheye)\n");
265         printf("             truncatedfront         (Front-Truncated)\n");
266         printf("             truncatedrear          (Rear-Truncated)\n");
267         printf("             cubemap                (Cube Map)\n");
268         printf("             sphericalpanoramic     (Spherical Panoramic)\n");
269         printf("       Example: -D  or  -D mode cubemap\n\n");
270         printf("  -m: maximum anti-aliasing (eg. 2,4,8,16)\n\n");
271         printf("  -i: parent window's ID\n\n");
272 #ifdef _WIN32
273         printf("  -c: keep console window open\n\n");
274 #endif
275         printf("  -d: turn debugging on\n\n");
276         printf("  -g: game engine options:\n\n");
277         printf("       Name                       Default      Description\n");
278         printf("       ------------------------------------------------------------------------\n");
279         printf("       fixedtime                      0         \"Enable all frames\"\n");
280         printf("       nomipmap                       0         Disable mipmaps\n");
281         printf("       show_framerate                 0         Show the frame rate\n");
282         printf("       show_properties                0         Show debug properties\n");
283         printf("       show_profile                   0         Show profiling information\n");
284         printf("       blender_material               0         Enable material settings\n");
285         printf("       ignore_deprecation_warnings    1         Ignore deprecation warnings\n");
286         printf("\n");
287         printf("  - : all arguments after this are ignored, allowing python to access them from sys.argv\n");
288         printf("\n");
289         printf("example: %s -w 320 200 10 10 -g noaudio %s%s\n", program, example_pathname, example_filename);
290         printf("example: %s -g show_framerate = 0 %s%s\n", program, example_pathname, example_filename);
291         printf("example: %s -i 232421 -m 16 %s%s\n\n", program, example_pathname, example_filename);
292 }
293
294 static void get_filename(int argc, char **argv, char *filename)
295 {
296 #ifdef __APPLE__
297         /* On Mac we park the game file (called game.blend) in the application bundle.
298          * The executable is located in the bundle as well.
299          * Therefore, we can locate the game relative to the executable.
300          */
301         int srclen = ::strlen(argv[0]);
302         int len = 0;
303         char *gamefile = NULL;
304         
305         filename[0] = '\0';
306
307         if (argc > 1) {
308                 if (BLI_exists(argv[argc-1])) {
309                         BLI_strncpy(filename, argv[argc-1], FILE_MAX);
310                 }
311                 if (::strncmp(argv[argc-1], "-psn_", 5)==0) {
312                         static char firstfilebuf[512];
313                         if (GHOST_HACK_getFirstFile(firstfilebuf)) {
314                                 BLI_strncpy(filename, firstfilebuf, FILE_MAX);
315                         }
316                 }
317         }
318         
319         srclen -= ::strlen("MacOS/blenderplayer");
320         if (srclen > 0) {
321                 len = srclen + ::strlen("Resources/game.blend"); 
322                 gamefile = new char [len + 1];
323                 ::strcpy(gamefile, argv[0]);
324                 ::strcpy(gamefile + srclen, "Resources/game.blend");
325                 //::printf("looking for file: %s\n", filename);
326                 
327                 if (BLI_exists(gamefile))
328                         BLI_strncpy(filename, gamefile, FILE_MAX);
329
330                 delete [] gamefile;
331         }
332         
333 #else
334         filename[0] = '\0';
335
336         if (argc > 1)
337                 BLI_strncpy(filename, argv[argc-1], FILE_MAX);
338 #endif // !_APPLE
339 }
340
341 static BlendFileData *load_game_data(const char *progname, char *filename = NULL, char *relativename = NULL)
342 {
343         ReportList reports;
344         BlendFileData *bfd = NULL;
345
346         BKE_reports_init(&reports, RPT_STORE);
347         
348         /* try to load ourself, will only work if we are a runtime */
349         if (BLO_is_a_runtime(progname)) {
350                 bfd= BLO_read_runtime(progname, &reports);
351                 if (bfd) {
352                         bfd->type= BLENFILETYPE_RUNTIME;
353                         BLI_strncpy(bfd->main->name, progname, sizeof(bfd->main->name));
354                 }
355         } else {
356                 bfd= BLO_read_from_file(progname, &reports);
357         }
358         
359         if (!bfd && filename) {
360                 bfd = load_game_data(filename);
361                 if (!bfd) {
362                         printf("Loading %s failed: ", filename);
363                         BKE_reports_print(&reports, RPT_ERROR);
364                 }
365         }
366
367         BKE_reports_clear(&reports);
368         
369         return bfd;
370 }
371
372 static bool GPG_NextFrame(GHOST_ISystem* system, GPG_Application *app, int &exitcode, STR_String &exitstring, GlobalSettings *gs)
373 {
374         bool run = true;
375         system->processEvents(false);
376         system->dispatchEvents();
377         app->EngineNextFrame();
378         if ((exitcode = app->getExitRequested())) {
379                 run = false;
380                 exitstring = app->getExitString();
381                 *gs = *app->getGlobalSettings();
382         }
383         return run;
384 }
385
386 struct GPG_NextFrameState {
387         GHOST_ISystem* system;
388         GPG_Application *app;
389         GlobalSettings *gs;
390 } gpg_nextframestate;
391
392 static int GPG_PyNextFrame(void *state0)
393 {
394         GPG_NextFrameState *state = (GPG_NextFrameState *) state0;
395         int exitcode;
396         STR_String exitstring;
397         bool run = GPG_NextFrame(state->system, state->app, exitcode, exitstring, state->gs);
398         if (run) return 0;  
399         else {
400                 if (exitcode) 
401                         fprintf(stderr, "Exit code %d: %s\n", exitcode, exitstring.ReadPtr());
402                 return 1;
403         }
404 }
405
406 int main(
407         int argc,
408 #ifdef WIN32
409         char **UNUSED(argv_c)
410 #else
411         char **argv
412 #endif
413         )
414 {
415         int i;
416         int argc_py_clamped= argc; /* use this so python args can be added after ' - ' */
417         bool error = false;
418         SYS_SystemHandle syshandle = SYS_GetSystem();
419         bool fullScreen = false;
420         bool fullScreenParFound = false;
421         bool windowParFound = false;
422 #ifdef WIN32
423         bool closeConsole = true;
424 #endif
425         RAS_IRasterizer::StereoMode stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
426         bool stereoWindow = false;
427         bool stereoParFound = false;
428         int stereoFlag = STEREO_NOSTEREO;
429         int domeFov = -1;
430         int domeTilt = -200;
431         int domeMode = 0;
432         char* domeWarp = NULL;
433         Text *domeText  = NULL;
434         int windowLeft = 100;
435         int windowTop = 100;
436         int windowWidth = 640;
437         int windowHeight = 480;
438         GHOST_TUns32 fullScreenWidth = 0;
439         GHOST_TUns32 fullScreenHeight= 0;
440         int fullScreenBpp = 32;
441         int fullScreenFrequency = 60;
442         GHOST_TEmbedderWindowID parentWindow = 0;
443         bool isBlenderPlayer = false; //true when lauching from blender or command line. false for bundled player
444         int validArguments=0;
445         bool samplesParFound = false;
446         GHOST_TUns16 aasamples = 0;
447         int alphaBackground = 0;
448         
449 #ifdef WIN32
450         char **argv;
451         int argv_num;
452
453         /* We delay loading of openmp so we can set the policy here. */
454 # if defined(_MSC_VER)
455         _putenv_s("OMP_WAIT_POLICY", "PASSIVE");
456 # endif
457
458         /* FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it. */
459 #  if defined(_MSC_VER) && defined(_M_X64)
460         _set_FMA3_enable(0);
461 #  endif
462
463         /* Win32 Unicode Args */
464         /* NOTE: cannot use guardedalloc malloc here, as it's not yet initialized
465         *       (it depends on the args passed in, which is what we're getting here!)
466         */
467         {
468                 wchar_t **argv_16 = CommandLineToArgvW(GetCommandLineW(), &argc);
469                 argv = (char**)malloc(argc * sizeof(char *));
470                 for (argv_num = 0; argv_num < argc; argv_num++) {
471                         argv[argv_num] = alloc_utf_8_from_16(argv_16[argv_num], 0);
472                 }
473                 LocalFree(argv_16);
474         }
475 #endif  /* WIN32 */
476
477 #ifdef __linux__
478 #ifdef __alpha__
479         signal (SIGFPE, SIG_IGN);
480 #endif /* __alpha__ */
481 #endif /* __linux__ */
482
483 #ifdef WITH_SDL_DYNLOAD
484         sdlewInit();
485 #endif
486
487         BKE_appdir_program_path_init(argv[0]);
488         BKE_tempdir_init(NULL);
489         
490         // We don't use threads directly in the BGE, but we need to call this so things like
491         // freeing up GPU_Textures works correctly.
492         BLI_threadapi_init();
493
494         RNA_init();
495
496         init_nodesystem();
497         
498         BKE_blender_globals_init();
499
500         // We load our own G.main, so free the one that BKE_blender_globals_init() gives us
501         BKE_main_free(G.main);
502         G.main = NULL;
503
504         MEM_CacheLimiter_set_disabled(true);
505         IMB_init();
506         BKE_images_init();
507         BKE_modifier_init();
508         DAG_init();
509
510 #ifdef WITH_FFMPEG
511         IMB_ffmpeg_init();
512 #endif
513
514         // Setup builtin font for BLF (mostly copied from creator.c, wm_init_exit.c and interface_style.c)
515         BLF_init(11, U.dpi);
516         BLT_lang_init();
517         BLT_lang_set("");
518
519         BLF_load_mem("default", (unsigned char*)datatoc_bfont_ttf, datatoc_bfont_ttf_size);
520         if (blf_mono_font == -1)
521                 blf_mono_font = BLF_load_mem_unique("monospace", (unsigned char*)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
522
523         // Parse command line options
524 #if defined(DEBUG)
525         printf("argv[0] = '%s'\n", argv[0]);
526 #endif
527
528 #ifdef WIN32
529         if (scr_saver_init(argc, argv))
530         {
531                 switch (scr_saver_mode)
532                 {
533                 case SCREEN_SAVER_MODE_CONFIGURATION:
534                         MessageBox(scr_saver_hwnd, "This screen saver has no options that you can set", "Screen Saver", MB_OK);
535                         break;
536                 case SCREEN_SAVER_MODE_PASSWORD:
537                         /* This is W95 only, which we currently do not support.
538                          * Fall-back to normal screen saver behavior in that case... */
539                 case SCREEN_SAVER_MODE_SAVER:
540                         fullScreen = true;
541                         fullScreenParFound = true;
542                         break;
543
544                 case SCREEN_SAVER_MODE_PREVIEW:
545                         /* This will actually be handled somewhere below... */
546                         break;
547                 }
548         }
549 #endif
550         // XXX add the ability to change this values to the command line parsing.
551         U.mixbufsize = 2048;
552         U.audiodevice = 2;
553         U.audiorate = 44100;
554         U.audioformat = 0x24;
555         U.audiochannels = 2;
556
557         // XXX this one too
558         U.anisotropic_filter = 2;
559         // enable fast mipmap generation
560         U.use_gpu_mipmap = 1;
561
562         BKE_sound_init_once();
563
564         // Initialize a default material for meshes without materials.
565         init_def_material();
566
567         BKE_library_callback_free_window_manager_set(wm_free);
568
569         /* if running blenderplayer the last argument can't be parsed since it has to be the filename. else it is bundled */
570         isBlenderPlayer = !BLO_is_a_runtime(argv[0]);
571         if (isBlenderPlayer)
572                 validArguments = argc - 1;
573         else
574                 validArguments = argc;
575
576
577         /* Parsing command line arguments (can be set from WM_OT_blenderplayer_start) */
578 #if defined(DEBUG)
579                 printf("Parsing command line arguments...\n");
580                 printf("Num of arguments is: %i\n", validArguments-1); //-1 because i starts at 1
581 #endif
582
583         for (i = 1; (i < validArguments) && !error 
584 #ifdef WIN32
585                 && scr_saver_mode == SCREEN_SAVER_MODE_NONE
586 #endif
587                 ;)
588
589         {
590 #if defined(DEBUG)
591                 printf("argv[%d] = '%s'\n", i, argv[i]);
592 #endif
593                 if (argv[i][0] == '-')
594                 {
595                         /* ignore all args after " - ", allow python to have own args */
596                         if (argv[i][1]=='\0') {
597                                 argc_py_clamped= i;
598                                 break;
599                         }
600                         
601                         switch (argv[i][1])
602                         {
603                         case 'g': //game engine options (show_framerate, fixedtime, etc)
604                         {
605                                 i++;
606                                 if (i <= validArguments)
607                                 {
608                                         char* paramname = argv[i];
609                                         // Check for single value versus assignment
610                                         if (i+1 <= validArguments && (*(argv[i+1]) == '='))
611                                         {
612                                                 i++;
613                                                 if (i + 1 <= validArguments)
614                                                 {
615                                                         i++;
616                                                         // Assignment
617                                                         SYS_WriteCommandLineInt(syshandle, paramname, atoi(argv[i]));
618                                                         SYS_WriteCommandLineFloat(syshandle, paramname, atof(argv[i]));
619                                                         SYS_WriteCommandLineString(syshandle, paramname, argv[i]);
620 #if defined(DEBUG)
621                                                         printf("%s = '%s'\n", paramname, argv[i]);
622 #endif
623                                                         i++;
624                                                 }
625                                                 else
626                                                 {
627                                                         error = true;
628                                                         printf("error: argument assignment %s without value.\n", paramname);
629                                                 }
630                                         }
631                                         else
632                                         {
633 //                                              SYS_WriteCommandLineInt(syshandle, argv[i++], 1);
634                                         }
635                                 }
636                                 break;
637                         }
638                         case 'd': //debug on
639                         {
640                                 i++;
641                                 G.debug |= G_DEBUG;
642                                 MEM_set_memory_debug();
643 #ifndef NDEBUG
644                                 BLI_mempool_set_memory_debug();
645 #endif
646                                 break;
647                         }
648                         case 'f': //fullscreen mode
649                         {
650                                 i++;
651                                 fullScreen = true;
652                                 fullScreenParFound = true;
653                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
654                                 {
655                                         fullScreenWidth = atoi(argv[i++]);
656                                         fullScreenHeight = atoi(argv[i++]);
657                                         if ((i + 1) <= validArguments && argv[i][0] != '-')
658                                         {
659                                                 fullScreenBpp = atoi(argv[i++]);
660                                                 if ((i + 1) <= validArguments && argv[i][0] != '-')
661                                                         fullScreenFrequency = atoi(argv[i++]);
662                                         }
663                                 }
664                                 else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
665                                 {
666                                         error = true;
667                                         printf("error: to define fullscreen width or height, both options must be used.\n");
668                                 }
669                                 break;
670                         }
671                         case 'w': //display in a window
672                         {
673                                 i++;
674                                 fullScreen = false;
675                                 windowParFound = true;
676
677                                 // Parse window position and size options
678                                 if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
679                                 {
680                                         windowWidth = atoi(argv[i++]);
681                                         windowHeight = atoi(argv[i++]);
682
683                                         if ((i + 2) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
684                                         {
685                                                 windowLeft = atoi(argv[i++]);
686                                                 windowTop = atoi(argv[i++]);
687                                         }
688                                         else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
689                                         {
690                                                 error = true;
691                                                 printf("error: to define the window left or right coordinates, both options must be used.\n");
692                                         }
693                                 }
694                                 else if ((i + 1) <= validArguments && argv[i][0] != '-' && argv[i+1][0] != '-')
695                                 {
696                                         error = true;
697                                         printf("error: to define the window's width or height, both options must be used.\n");
698                                 }
699                                 break;
700                         }
701                         case 'h': //display help
702                         {
703                                 usage(argv[0], isBlenderPlayer);
704                                 return 0;
705                                 break;
706                         }
707                         case 'i': //parent window ID
708                         {
709                                 i++;
710                                 if ( (i + 1) <= validArguments )
711                                         parentWindow = atoi(argv[i++]);
712                                 else {
713                                         error = true;
714                                         printf("error: too few options for parent window argument.\n");
715                                 }
716 #if defined(DEBUG)
717                                 printf("XWindows ID = %d\n", parentWindow);
718 #endif // defined(DEBUG)
719                                 break;
720                         }
721                         case 'm': //maximum anti-aliasing (eg. 2,4,8,16)
722                         {
723                                 i++;
724                                 samplesParFound = true;
725                                 if ((i+1) <= validArguments )
726                                         aasamples = atoi(argv[i++]);
727                                 else
728                                 {
729                                         error = true;
730                                         printf("error: No argument supplied for -m");
731                                 }
732                                 break;
733                         }
734                         case 'c': //keep console (windows only)
735                         {
736                                 i++;
737 #ifdef WIN32
738                                 closeConsole = false;
739 #endif
740                                 break;
741                         }
742                         case 's': //stereo mode
743                         {
744                                 i++;
745                                 if ((i + 1) <= validArguments)
746                                 {
747                                         stereoParFound = true;
748                                         stereoFlag = STEREO_ENABLED;
749
750                                         if (!strcmp(argv[i], "nostereo"))  // may not be redundant if the file has different setting
751                                         {
752                                                 stereomode = RAS_IRasterizer::RAS_STEREO_NOSTEREO;
753                                                 stereoFlag = STEREO_NOSTEREO;
754                                         }
755
756                                         // only the hardware pageflip method needs a stereo window
757                                         else if (!strcmp(argv[i], "hwpageflip")) {
758                                                 stereomode = RAS_IRasterizer::RAS_STEREO_QUADBUFFERED;
759                                                 stereoWindow = true;
760                                         }
761                                         else if (!strcmp(argv[i], "syncdoubling"))
762                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ABOVEBELOW;
763
764                                         else if (!strcmp(argv[i], "3dtvtopbottom"))
765                                                 stereomode = RAS_IRasterizer::RAS_STEREO_3DTVTOPBOTTOM;
766
767                                         else if (!strcmp(argv[i], "anaglyph"))
768                                                 stereomode = RAS_IRasterizer::RAS_STEREO_ANAGLYPH;
769
770                                         else if (!strcmp(argv[i], "sidebyside"))
771                                                 stereomode = RAS_IRasterizer::RAS_STEREO_SIDEBYSIDE;
772
773                                         else if (!strcmp(argv[i], "interlace"))
774                                                 stereomode = RAS_IRasterizer::RAS_STEREO_INTERLACED;
775
776                                         else if (!strcmp(argv[i], "vinterlace"))
777                                                 stereomode = RAS_IRasterizer::RAS_STEREO_VINTERLACE;
778
779 #if 0
780 //                                      // future stuff
781 //                                      else if (!strcmp(argv[i], "stencil")
782 //                                              stereomode = RAS_STEREO_STENCIL;
783 #endif
784                                         else
785                                         {
786                                                 error = true;
787                                                 printf("error: stereomode '%s' unrecognized.\n", argv[i]);
788                                         }
789
790                                         i++;
791                                 }
792                                 else
793                                 {
794                                         error = true;
795                                         printf("error: too few options for stereo argument.\n");
796                                 }
797                                 break;
798                         }
799                         case 'D': //dome mode
800                         {
801                                 stereoFlag = STEREO_DOME;
802                                 stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
803                                 i++;
804                                 if ((i + 1) <= validArguments)
805                                 {
806                                         if (!strcmp(argv[i], "angle")) {
807                                                 i++;
808                                                 domeFov = atoi(argv[i++]);
809                                         }
810                                         if (!strcmp(argv[i], "tilt")) {
811                                                 i++;
812                                                 domeTilt = atoi(argv[i++]);
813                                         }
814                                         if (!strcmp(argv[i], "warpdata")) {
815                                                 i++;
816                                                 domeWarp = argv[i++];
817                                         }
818                                         if (!strcmp(argv[i], "mode")) {
819                                                 i++;
820                                                 if (!strcmp(argv[i], "fisheye"))
821                                                         domeMode = DOME_FISHEYE;
822                                                         
823                                                 else if (!strcmp(argv[i], "truncatedfront"))
824                                                         domeMode = DOME_TRUNCATED_FRONT;
825                                                         
826                                                 else if (!strcmp(argv[i], "truncatedrear"))
827                                                         domeMode = DOME_TRUNCATED_REAR;
828                                                         
829                                                 else if (!strcmp(argv[i], "cubemap"))
830                                                         domeMode = DOME_ENVMAP;
831                                                         
832                                                 else if (!strcmp(argv[i], "sphericalpanoramic"))
833                                                         domeMode = DOME_PANORAM_SPH;
834
835                                                 else
836                                                         printf("error: %s is not a valid dome mode.\n", argv[i]);
837                                         }
838                                         i++;
839                                 }
840                                 break;
841                         }
842                         case 'a':   // allow window to blend with display background
843                         {
844                                 i++;
845                                 alphaBackground = 1;
846                                 break;
847                         }
848                         default:  //not recognized
849                         {
850                                 printf("Unknown argument: %s\n", argv[i++]);
851                                 break;
852                         }
853                         }
854                 }
855                 else
856                 {
857                         i++;
858                 }
859         }
860
861         if ((windowWidth < kMinWindowWidth) || (windowHeight < kMinWindowHeight))
862         {
863                 error = true;
864                 printf("error: window size too small.\n");
865         }
866         
867         if (error )
868         {
869                 usage(argv[0], isBlenderPlayer);
870                 return 0;
871         }
872
873 #ifdef WIN32
874         if (scr_saver_mode != SCREEN_SAVER_MODE_CONFIGURATION)
875 #endif
876         {
877                 // Create the system
878                 if (GHOST_ISystem::createSystem() == GHOST_kSuccess) {
879                         GHOST_ISystem* system = GHOST_ISystem::getSystem();
880                         assertd(system);
881                         
882                         if (!fullScreenWidth || !fullScreenHeight)
883                                 system->getMainDisplayDimensions(fullScreenWidth, fullScreenHeight);
884                         // process first batch of events. If the user
885                         // drops a file on top off the blenderplayer icon, we
886                         // receive an event with the filename
887                         
888                         system->processEvents(0);
889                         
890                         // this bracket is needed for app (see below) to get out
891                         // of scope before GHOST_ISystem::disposeSystem() is called.
892                         {
893                                 int exitcode = KX_EXIT_REQUEST_NO_REQUEST;
894                                 STR_String exitstring = "";
895                                 GPG_Application app(system);
896                                 bool firstTimeRunning = true;
897                                 char filename[FILE_MAX];
898                                 char pathname[FILE_MAX];
899                                 char *titlename;
900
901                                 get_filename(argc_py_clamped, argv, filename);
902                                 if (filename[0])
903                                         BLI_path_cwd(filename, sizeof(filename));
904                                 
905
906                                 // fill the GlobalSettings with the first scene files
907                                 // those may change during the game and persist after using Game Actuator
908                                 GlobalSettings gs;
909
910                                 do {
911                                         // Read the Blender file
912                                         BlendFileData *bfd;
913                                         
914                                         // if we got an exitcode 3 (KX_EXIT_REQUEST_START_OTHER_GAME) load a different file
915                                         if (exitcode == KX_EXIT_REQUEST_START_OTHER_GAME)
916                                         {
917                                                 char basedpath[FILE_MAX];
918                                                 
919                                                 // base the actuator filename relative to the last file
920                                                 BLI_strncpy(basedpath, exitstring.Ptr(), sizeof(basedpath));
921                                                 BLI_path_abs(basedpath, pathname);
922                                                 
923                                                 bfd = load_game_data(basedpath);
924
925                                                 if (!bfd) {
926                                                         // just add "//" in front of it
927                                                         char temppath[FILE_MAX] = "//";
928                                                         BLI_strncpy(temppath + 2, basedpath, FILE_MAX - 2);
929
930                                                         BLI_path_abs(temppath, pathname);
931                                                         bfd = load_game_data(temppath);
932                                                 }
933                                         }
934                                         else {
935                                                 bfd = load_game_data(BKE_appdir_program_path(), filename[0]? filename: NULL);
936                                         }
937
938 #if defined(DEBUG)
939                                         printf("Game data loaded from %s\n", filename);
940 #endif
941                                         
942                                         if (!bfd) {
943                                                 usage(argv[0], isBlenderPlayer);
944                                                 error = true;
945                                                 exitcode = KX_EXIT_REQUEST_QUIT_GAME;
946                                         }
947                                         else {
948                                                 /* Setting options according to the blend file if not overriden in the command line */
949 #ifdef WIN32
950 #if !defined(DEBUG)
951                                                 if (closeConsole) {
952                                                         system->toggleConsole(0); // Close a console window
953                                                 }
954 #endif // !defined(DEBUG)
955 #endif // WIN32
956                                                 Main *maggie = bfd->main;
957                                                 Scene *scene = bfd->curscene;
958                                                 G.main = maggie;
959
960                                                 if (firstTimeRunning) {
961                                                         G.fileflags  = bfd->fileflags;
962
963                                                         gs.matmode= scene->gm.matmode;
964                                                         gs.glslflag= scene->gm.flag;
965                                                 }
966
967                                                 //Seg Fault; icon.c gIcons == 0
968                                                 BKE_icons_init(1);
969                                                 
970                                                 titlename = maggie->name;
971                                                 
972                                                 // Check whether the game should be displayed full-screen
973                                                 if ((!fullScreenParFound) && (!windowParFound)) {
974                                                         // Only use file settings when command line did not override
975                                                         if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
976                                                                 //printf("fullscreen option found in Blender file\n");
977                                                                 fullScreen = true;
978                                                                 fullScreenWidth= scene->gm.xplay;
979                                                                 fullScreenHeight= scene->gm.yplay;
980                                                                 fullScreenFrequency= scene->gm.freqplay;
981                                                                 fullScreenBpp = scene->gm.depth;
982                                                         }
983                                                         else
984                                                         {
985                                                                 fullScreen = false;
986                                                                 windowWidth = scene->gm.xplay;
987                                                                 windowHeight = scene->gm.yplay;
988                                                         }
989                                                 }
990                                                 
991                                                 
992                                                 // Check whether the game should be displayed in stereo (dome included)
993                                                 if (!stereoParFound) {
994                                                         // Only use file settings when command line did not override
995                                                         if (scene->gm.stereoflag == STEREO_ENABLED) {
996                                                                 stereomode = (RAS_IRasterizer::StereoMode) scene->gm.stereomode;
997                                                                 if (stereomode == RAS_IRasterizer::RAS_STEREO_QUADBUFFERED)
998                                                                         stereoWindow = true;
999                                                         }
1000                                                 }
1001                                                 else {
1002                                                         scene->gm.stereoflag = STEREO_ENABLED;
1003                                                 }
1004
1005                                                 if (!samplesParFound)
1006                                                         aasamples = scene->gm.aasamples;
1007
1008                                                 // Dome specific settings
1009                                                 if (stereoFlag == STEREO_DOME) {
1010                                                         stereomode = RAS_IRasterizer::RAS_STEREO_DOME;
1011                                                         scene->gm.stereoflag = STEREO_DOME;
1012                                                         if (domeFov > 89)
1013                                                                 scene->gm.dome.angle = domeFov;
1014                                                         if (domeTilt > -180)
1015                                                                 scene->gm.dome.tilt = domeTilt;
1016                                                         if (domeMode > 0)
1017                                                                 scene->gm.dome.mode = domeMode;
1018                                                         if (domeWarp) {
1019                                                                 //XXX to do: convert relative to absolute path
1020                                                                 domeText= BKE_text_load(G.main, domeWarp, "");
1021                                                                 if (!domeText)
1022                                                                         printf("error: invalid warpdata text file - %s\n", domeWarp);
1023                                                                 else
1024                                                                         scene->gm.dome.warptext = domeText;
1025                                                         }
1026                                                 }
1027                                                 
1028                                                 //                                      GPG_Application app (system, maggie, startscenename);
1029                                                 app.SetGameEngineData(maggie, scene, &gs, argc, argv); /* this argc cant be argc_py_clamped, since python uses it */
1030                                                 BLI_strncpy(pathname, maggie->name, sizeof(pathname));
1031                                                 if (G.main != maggie) {
1032                                                         BLI_strncpy(G.main->name, maggie->name, sizeof(G.main->name));
1033                                                 }
1034 #ifdef WITH_PYTHON
1035                                                 setGamePythonPath(G.main->name);
1036 #endif
1037                                                 if (firstTimeRunning) {
1038                                                         firstTimeRunning = false;
1039
1040                                                         if (fullScreen) {
1041 #ifdef WIN32
1042                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_SAVER)
1043                                                                 {
1044                                                                         app.startScreenSaverFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
1045                                                                                                        stereoWindow, stereomode, aasamples);
1046                                                                 }
1047                                                                 else
1048 #endif
1049                                                                 {
1050                                                                         app.startFullScreen(fullScreenWidth, fullScreenHeight, fullScreenBpp, fullScreenFrequency,
1051                                                                                             stereoWindow, stereomode, alphaBackground, aasamples, (scene->gm.playerflag & GAME_PLAYER_DESKTOP_RESOLUTION));
1052                                                                 }
1053                                                         }
1054                                                         else
1055                                                         {
1056 #ifdef __APPLE__
1057                                                                 // on Mac's we'll show the executable name instead of the 'game.blend' name
1058                                                                 char tempname[1024], *appstring;
1059                                                                 ::strcpy(tempname, titlename);
1060                                                                 
1061                                                                 appstring = strstr(tempname, ".app/");
1062                                                                 if (appstring) {
1063                                                                         appstring[2] = 0;
1064                                                                         titlename = &tempname[0];
1065                                                                 }
1066 #endif
1067                                                                 // Strip the path so that we have the name of the game file
1068                                                                 STR_String path = titlename;
1069 #ifndef WIN32
1070                                                                 vector<STR_String> parts = path.Explode('/');
1071 #else  // WIN32
1072                                                                 vector<STR_String> parts = path.Explode('\\');
1073 #endif // WIN32                        
1074                                                                 STR_String title;
1075                                                                 if (parts.size()) {
1076                                                                         title = parts[parts.size()-1];
1077                                                                         parts = title.Explode('.');
1078                                                                         if (parts.size() > 1)
1079                                                                         {
1080                                                                                 title = parts[0];
1081                                                                         }
1082                                                                 }
1083                                                                 else {
1084                                                                         title = "blenderplayer";
1085                                                                 }
1086 #ifdef WIN32
1087                                                                 if (scr_saver_mode == SCREEN_SAVER_MODE_PREVIEW)
1088                                                                 {
1089                                                                         app.startScreenSaverPreview(scr_saver_hwnd, stereoWindow, stereomode, aasamples);
1090                                                                 }
1091                                                                 else
1092 #endif
1093                                                                 {
1094                                                                         if (parentWindow != 0)
1095                                                                                 app.startEmbeddedWindow(title, parentWindow, stereoWindow, stereomode, aasamples);
1096                                                                         else
1097                                                                                 app.startWindow(title, windowLeft, windowTop, windowWidth, windowHeight,
1098                                                                                                 stereoWindow, stereomode, alphaBackground, aasamples);
1099
1100                                                                         if (SYS_GetCommandLineInt(syshandle, "nomipmap", 0)) {
1101                                                                                 GPU_set_mipmap(0);
1102                                                                         }
1103
1104                                                                         GPU_set_anisotropic(U.anisotropic_filter);
1105                                                                         GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
1106                                                                 }
1107                                                         }
1108                                                 }
1109                                                 else {
1110                                                         app.StartGameEngine(stereomode);
1111                                                         exitcode = KX_EXIT_REQUEST_NO_REQUEST;
1112                                                 }
1113                                                 
1114                                                 // Add the application as event consumer
1115                                                 system->addEventConsumer(&app);
1116                                                 
1117                                                 // Enter main loop
1118                                                 bool run = true;
1119                                                 char *python_main = NULL;
1120                                                 pynextframestate.state = NULL;
1121                                                 pynextframestate.func = NULL;
1122 #ifdef WITH_PYTHON
1123                                                 python_main = KX_GetPythonMain(scene);
1124 #endif // WITH_PYTHON
1125                                                 if (python_main) {
1126                                                         char *python_code = KX_GetPythonCode(maggie, python_main);
1127                                                         if (python_code) {
1128 #ifdef WITH_PYTHON
1129                                                                 // Set python environement variable.
1130                                                                 KX_Scene *startscene = app.GetStartScene();
1131                                                                 KX_SetActiveScene(startscene);
1132                                                                 PHY_SetActiveEnvironment(startscene->GetPhysicsEnvironment());
1133
1134                                                                 gpg_nextframestate.system = system;
1135                                                                 gpg_nextframestate.app = &app;
1136                                                                 gpg_nextframestate.gs = &gs;
1137                                                                 pynextframestate.state = &gpg_nextframestate;
1138                                                                 pynextframestate.func = &GPG_PyNextFrame;
1139
1140                                                                 printf("Yielding control to Python script '%s'...\n", python_main);
1141                                                                 PyRun_SimpleString(python_code);
1142                                                                 printf("Exit Python script '%s'\n", python_main);
1143 #endif // WITH_PYTHON
1144                                                                 MEM_freeN(python_code);
1145                                                         }
1146                                                         else {
1147                                                                 fprintf(stderr, "ERROR: cannot yield control to Python: no Python text data block named '%s'\n", python_main);
1148                                                         }
1149                                                 }
1150                                                 else {
1151                                                         while (run) {
1152                                                                 run = GPG_NextFrame(system, &app, exitcode, exitstring, &gs);
1153                                                         }
1154                                                 }
1155                                                 app.StopGameEngine();
1156
1157                                                 /* 'app' is freed automatic when out of scope.
1158                                                  * removal is needed else the system will free an already freed value */
1159                                                 system->removeEventConsumer(&app);
1160
1161                                                 BLO_blendfiledata_free(bfd);
1162                                                 /* G.main == bfd->main, it gets referenced in free_nodesystem so we can't have a dangling pointer */
1163                                                 G.main = NULL;
1164                                                 if (python_main) MEM_freeN(python_main);
1165                                         }
1166                                 } while (exitcode == KX_EXIT_REQUEST_RESTART_GAME || exitcode == KX_EXIT_REQUEST_START_OTHER_GAME);
1167                         }
1168
1169                         // Seg Fault; icon.c gIcons == 0
1170                         BKE_icons_free();
1171
1172                         // Dispose the system
1173                         GHOST_ISystem::disposeSystem();
1174                 }
1175                 else {
1176                         error = true;
1177                         printf("error: couldn't create a system.\n");
1178                 }
1179         }
1180
1181         /* refer to WM_exit_ext() and BKE_blender_free(),
1182          * these are not called in the player but we need to match some of there behavior here,
1183          * if the order of function calls or blenders state isn't matching that of blender proper,
1184          * we may get troubles later on */
1185
1186         free_nodesystem();
1187
1188         // Cleanup
1189         RNA_exit();
1190         BLF_exit();
1191
1192 #ifdef WITH_INTERNATIONAL
1193         BLF_free_unifont();
1194         BLF_free_unifont_mono();
1195         BLT_lang_free();
1196 #endif
1197
1198         IMB_exit();
1199         BKE_images_exit();
1200         DAG_exit();
1201         IMB_moviecache_destruct();
1202
1203         SYS_DeleteSystem(syshandle);
1204
1205         int totblock= MEM_get_memory_blocks_in_use();
1206         if (totblock!=0) {
1207                 printf("Error Totblock: %d\n",totblock);
1208                 MEM_set_error_callback(mem_error_cb);
1209                 MEM_printmemlist();
1210         }
1211
1212         BKE_tempdir_session_purge();
1213
1214 #ifdef WIN32
1215         while (argv_num) {
1216                 free(argv[--argv_num]);
1217         }
1218         free(argv);
1219         argv = NULL;
1220 #endif
1221
1222         return error ? -1 : 0;
1223 }