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