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