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