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