Added a new concept to the menu, the ID.
[supertux.git] / src / setup.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 #include <assert.h>
21 #include <stdio.h>
22 #include <iostream>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <SDL.h>
29 #include <SDL_image.h>
30 #ifndef NOOPENGL
31 #include <SDL_opengl.h>
32 #endif
33
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <dirent.h>
37 #ifndef WIN32
38 #include <libgen.h>
39 #endif
40 #include <ctype.h>
41
42 #include "defines.h"
43 #include "globals.h"
44 #include "setup.h"
45 #include "screen.h"
46 #include "texture.h"
47 #include "menu.h"
48 #include "gameloop.h"
49 #include "configfile.h"
50 #include "scene.h"
51 #include "worldmap.h"
52
53 #include "player.h"
54
55 #ifdef WIN32
56 #define mkdir(dir, mode)    mkdir(dir)
57 // on win32 we typically don't want LFS paths
58 #undef DATA_PREFIX
59 #define DATA_PREFIX "./data/"
60 #endif
61
62 /* Local function prototypes: */
63
64 void seticon(void);
65 void usage(char * prog, int ret);
66
67 /* Does the given file exist and is it accessible? */
68 int faccessible(const char *filename)
69 {
70   struct stat filestat;
71   if (stat(filename, &filestat) == -1)
72     {
73       return false;
74     }
75   else
76     {
77       if(S_ISREG(filestat.st_mode))
78         return true;
79       else
80         return false;
81     }
82 }
83
84 /* Can we write to this location? */
85 int fwriteable(const char *filename)
86 {
87   FILE* fi;
88   fi = fopen(filename, "wa");
89   if (fi == NULL)
90     {
91       return false;
92     }
93   return true;
94 }
95
96 /* Makes sure a directory is created in either the SuperTux home directory or the SuperTux base directory.*/
97 int fcreatedir(const char* relative_dir)
98 {
99   char path[1024];
100   snprintf(path, 1024, "%s/%s/", st_dir, relative_dir);
101   if(mkdir(path,0755) != 0)
102     {
103       snprintf(path, 1024, "%s/%s/", datadir.c_str(), relative_dir);
104       if(mkdir(path,0755) != 0)
105         {
106           return false;
107         }
108       else
109         {
110           return true;
111         }
112     }
113   else
114     {
115       return true;
116     }
117 }
118
119 FILE * opendata(const char * rel_filename, const char * mode)
120 {
121   char * filename = NULL;
122   FILE * fi;
123
124   filename = (char *) malloc(sizeof(char) * (strlen(st_dir) +
125                                              strlen(rel_filename) + 1));
126
127   strcpy(filename, st_dir);
128   /* Open the high score file: */
129
130   strcat(filename, rel_filename);
131
132   /* Try opening the file: */
133   fi = fopen(filename, mode);
134
135   if (fi == NULL)
136     {
137       fprintf(stderr, "Warning: Unable to open the file \"%s\" ", filename);
138
139       if (strcmp(mode, "r") == 0)
140         fprintf(stderr, "for read!!!\n");
141       else if (strcmp(mode, "w") == 0)
142         fprintf(stderr, "for write!!!\n");
143     }
144   free( filename );
145
146   return(fi);
147 }
148
149 /* Get all names of sub-directories in a certain directory. */
150 /* Returns the number of sub-directories found. */
151 /* Note: The user has to free the allocated space. */
152 string_list_type dsubdirs(const char *rel_path,const  char* expected_file)
153 {
154   DIR *dirStructP;
155   struct dirent *direntp;
156   string_list_type sdirs;
157   char filename[1024];
158   char path[1024];
159
160   string_list_init(&sdirs);
161   sprintf(path,"%s/%s",st_dir,rel_path);
162   if((dirStructP = opendir(path)) != NULL)
163     {
164       while((direntp = readdir(dirStructP)) != NULL)
165         {
166           char absolute_filename[1024];
167           struct stat buf;
168
169           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
170
171           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
172             {
173               if(expected_file != NULL)
174                 {
175                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
176                   if(!faccessible(filename))
177                     continue;
178                 }
179
180               string_list_add_item(&sdirs,direntp->d_name);
181             }
182         }
183       closedir(dirStructP);
184     }
185
186   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
187   if((dirStructP = opendir(path)) != NULL)
188     {
189       while((direntp = readdir(dirStructP)) != NULL)
190         {
191           char absolute_filename[1024];
192           struct stat buf;
193
194           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
195
196           if (stat(absolute_filename, &buf) == 0 && S_ISDIR(buf.st_mode))
197             {
198               if(expected_file != NULL)
199                 {
200                   sprintf(filename,"%s/%s/%s",path,direntp->d_name,expected_file);
201                   if(!faccessible(filename))
202                     {
203                       continue;
204                     }
205                   else
206                     {
207                       sprintf(filename,"%s/%s/%s/%s",st_dir,rel_path,direntp->d_name,expected_file);
208                       if(faccessible(filename))
209                         continue;
210                     }
211                 }
212
213               string_list_add_item(&sdirs,direntp->d_name);
214             }
215         }
216       closedir(dirStructP);
217     }
218
219   return sdirs;
220 }
221
222 string_list_type dfiles(const char *rel_path, const  char* glob, const  char* exception_str)
223 {
224   DIR *dirStructP;
225   struct dirent *direntp;
226   string_list_type sdirs;
227   char path[1024];
228
229   string_list_init(&sdirs);
230   sprintf(path,"%s/%s",st_dir,rel_path);
231   if((dirStructP = opendir(path)) != NULL)
232     {
233       while((direntp = readdir(dirStructP)) != NULL)
234         {
235           char absolute_filename[1024];
236           struct stat buf;
237
238           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
239
240           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
241             {
242               if(exception_str != NULL)
243                 {
244                   if(strstr(direntp->d_name,exception_str) != NULL)
245                     continue;
246                 }
247               if(glob != NULL)
248                 if(strstr(direntp->d_name,glob) == NULL)
249                   continue;
250
251               string_list_add_item(&sdirs,direntp->d_name);
252             }
253         }
254       closedir(dirStructP);
255     }
256
257   sprintf(path,"%s/%s",datadir.c_str(),rel_path);
258   if((dirStructP = opendir(path)) != NULL)
259     {
260       while((direntp = readdir(dirStructP)) != NULL)
261         {
262           char absolute_filename[1024];
263           struct stat buf;
264
265           sprintf(absolute_filename, "%s/%s", path, direntp->d_name);
266
267           if (stat(absolute_filename, &buf) == 0 && S_ISREG(buf.st_mode))
268             {
269               if(exception_str != NULL)
270                 {
271                   if(strstr(direntp->d_name,exception_str) != NULL)
272                     continue;
273                 }
274               if(glob != NULL)
275                 if(strstr(direntp->d_name,glob) == NULL)
276                   continue;
277
278               string_list_add_item(&sdirs,direntp->d_name);
279             }
280         }
281       closedir(dirStructP);
282     }
283
284   return sdirs;
285 }
286
287 void free_strings(char **strings, int num)
288 {
289   int i;
290   for(i=0; i < num; ++i)
291     free(strings[i]);
292 }
293
294 /* --- SETUP --- */
295 /* Set SuperTux configuration and save directories */
296 void st_directory_setup(void)
297 {
298   char *home;
299   char str[1024];
300   /* Get home directory (from $HOME variable)... if we can't determine it,
301      use the current directory ("."): */
302   if (getenv("HOME") != NULL)
303     home = getenv("HOME");
304   else
305     home = ".";
306
307   st_dir = (char *) malloc(sizeof(char) * (strlen(home) +
308                                            strlen("/.supertux") + 1));
309   strcpy(st_dir, home);
310   strcat(st_dir, "/.supertux");
311
312   /* Remove .supertux config-file from old SuperTux versions */
313   if(faccessible(st_dir))
314     {
315       remove
316         (st_dir);
317     }
318
319   st_save_dir = (char *) malloc(sizeof(char) * (strlen(st_dir) + strlen("/save") + 1));
320
321   strcpy(st_save_dir,st_dir);
322   strcat(st_save_dir,"/save");
323
324   /* Create them. In the case they exist they won't destroy anything. */
325   mkdir(st_dir, 0755);
326   mkdir(st_save_dir, 0755);
327
328   sprintf(str, "%s/levels", st_dir);
329   mkdir(str, 0755);
330
331   // User has not that a datadir, so we try some magic
332   if (datadir.empty())
333     {
334 #ifndef WIN32
335       // Detect datadir
336       char exe_file[PATH_MAX];
337       if (readlink("/proc/self/exe", exe_file, PATH_MAX) < 0)
338         {
339           puts("Couldn't read /proc/self/exe, using default path: " DATA_PREFIX);
340           datadir = DATA_PREFIX;
341         }
342       else
343         {
344           std::string exedir = std::string(dirname(exe_file)) + "/";
345           
346           datadir = exedir + "../data/"; // SuperTux run from source dir
347           if (access(datadir.c_str(), F_OK) != 0)
348             {
349               datadir = exedir + "../share/supertux/"; // SuperTux run from PATH
350               if (access(datadir.c_str(), F_OK) != 0) 
351                 { // If all fails, fall back to compiled path
352                   datadir = DATA_PREFIX; 
353                 }
354             }
355         }
356 #else
357   datadir = DATA_PREFIX;
358 #endif
359     }
360   printf("Datadir: %s\n", datadir.c_str());
361 }
362
363 /* Create and setup menus. */
364 void st_menu(void)
365 {
366   main_menu      = new Menu();
367   options_menu   = new Menu();
368   options_keys_menu     = new Menu();
369   options_joystick_menu = new Menu();
370   load_game_menu = new Menu();
371   save_game_menu = new Menu();
372   game_menu      = new Menu();
373   highscore_menu = new Menu();
374   contrib_menu   = new Menu();
375   contrib_subset_menu   = new Menu();
376   worldmap_menu  = new Menu();
377
378   main_menu->set_pos(screen->w/2, 335);
379   main_menu->additem(MN_GOTO, "Start Game",0,load_game_menu, MNID_STARTGAME);
380   main_menu->additem(MN_GOTO, "Contrib Levels",0,contrib_menu, MNID_CONTRIB);
381   main_menu->additem(MN_GOTO, "Options",0,options_menu);
382   main_menu->additem(MN_ACTION,"Level editor",0,0, MNID_LEVELEDITOR);
383   main_menu->additem(MN_ACTION,"Credits",0,0, MNID_CREDITS);
384   main_menu->additem(MN_ACTION,"Quit",0,0, MNID_QUITMAINMENU);
385
386   options_menu->additem(MN_LABEL,"Options",0,0);
387   options_menu->additem(MN_HL,"",0,0);
388 #ifndef NOOPENGL
389   options_menu->additem(MN_TOGGLE,"OpenGL",use_gl,0, MNID_OPENGL);
390 #else
391   options_menu->additem(MN_DEACTIVE,"OpenGL (not supported)",use_gl,MNID_OPENGL);
392 #endif
393   options_menu->additem(MN_TOGGLE,"Fullscreen",use_fullscreen,0, MNID_FULLSCREEN);
394   if(audio_device)
395     {
396       options_menu->additem(MN_TOGGLE,"Sound     ",use_sound,0, MNID_SOUND);
397       options_menu->additem(MN_TOGGLE,"Music     ",use_music,0, MNID_MUSIC);
398     }
399   else
400     {
401       options_menu->additem(MN_DEACTIVE,"Sound     ",use_sound,0, MNID_SOUND);
402       options_menu->additem(MN_DEACTIVE,"Music     ",use_music,0, MNID_MUSIC);
403     }
404   options_menu->additem(MN_TOGGLE,"Show FPS  ",show_fps,0, MNID_SHOWFPS);
405   options_menu->additem(MN_GOTO,"Key Setup",0,options_keys_menu);
406   if(use_joystick)
407     options_menu->additem(MN_GOTO,"Joystick Setup",0,options_joystick_menu);
408   options_menu->additem(MN_HL,"",0,0);
409   options_menu->additem(MN_BACK,"Back",0,0);
410   
411   options_keys_menu->additem(MN_LABEL,"Key Setup",0,0);
412   options_keys_menu->additem(MN_HL,"",0,0);
413   options_keys_menu->additem(MN_CONTROLFIELD,"Left move", 0,0, 0,&keymap.left);
414   options_keys_menu->additem(MN_CONTROLFIELD,"Right move", 0,0, 0,&keymap.right);
415   options_keys_menu->additem(MN_CONTROLFIELD,"Jump", 0,0, 0,&keymap.jump);
416   options_keys_menu->additem(MN_CONTROLFIELD,"Duck", 0,0, 0,&keymap.duck);
417   options_keys_menu->additem(MN_CONTROLFIELD,"Power", 0,0, 0,&keymap.fire);
418   options_keys_menu->additem(MN_HL,"",0,0);
419   options_keys_menu->additem(MN_BACK,"Back",0,0);
420
421   if(use_joystick)
422     {
423     options_joystick_menu->additem(MN_LABEL,"Joystick Setup",0,0);
424     options_joystick_menu->additem(MN_HL,"",0,0);
425     options_joystick_menu->additem(MN_CONTROLFIELD,"X axis", 0,0, 0,&joystick_keymap.x_axis);
426     options_joystick_menu->additem(MN_CONTROLFIELD,"Y axis", 0,0, 0,&joystick_keymap.y_axis);
427     options_joystick_menu->additem(MN_CONTROLFIELD,"A button", 0,0, 0,&joystick_keymap.a_button);
428     options_joystick_menu->additem(MN_CONTROLFIELD,"B button", 0,0, 0,&joystick_keymap.b_button);
429     options_joystick_menu->additem(MN_CONTROLFIELD,"Start", 0,0, 0,&joystick_keymap.start_button);
430     options_joystick_menu->additem(MN_CONTROLFIELD,"DeadZone", 0,0, 0,&joystick_keymap.dead_zone);
431     options_joystick_menu->additem(MN_HL,"",0,0);
432     options_joystick_menu->additem(MN_BACK,"Back",0,0);
433     }
434   
435   load_game_menu->additem(MN_LABEL,"Start Game",0,0);
436   load_game_menu->additem(MN_HL,"",0,0);
437   load_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
438   load_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
439   load_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
440   load_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
441   load_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
442   load_game_menu->additem(MN_HL,"",0,0);
443   load_game_menu->additem(MN_BACK,"Back",0,0);
444
445   save_game_menu->additem(MN_LABEL,"Save Game",0,0);
446   save_game_menu->additem(MN_HL,"",0,0);
447   save_game_menu->additem(MN_DEACTIVE,"Slot 1",0,0);
448   save_game_menu->additem(MN_DEACTIVE,"Slot 2",0,0);
449   save_game_menu->additem(MN_DEACTIVE,"Slot 3",0,0);
450   save_game_menu->additem(MN_DEACTIVE,"Slot 4",0,0);
451   save_game_menu->additem(MN_DEACTIVE,"Slot 5",0,0);
452   save_game_menu->additem(MN_HL,"",0,0);
453   save_game_menu->additem(MN_BACK,"Back",0,0);
454
455   game_menu->additem(MN_LABEL,"Pause",0,0);
456   game_menu->additem(MN_HL,"",0,0);
457   game_menu->additem(MN_ACTION,"Continue",0,0,MNID_CONTINUE);
458   game_menu->additem(MN_GOTO,"Options",0,options_menu);
459   game_menu->additem(MN_HL,"",0,0);
460   game_menu->additem(MN_ACTION,"Abort Level",0,0,MNID_ABORTLEVEL);
461
462   worldmap_menu->additem(MN_LABEL,"Pause",0,0);
463   worldmap_menu->additem(MN_HL,"",0,0);
464   worldmap_menu->additem(MN_ACTION,"Continue",0,0,MNID_RETURNWORLDMAP);
465   worldmap_menu->additem(MN_ACTION,"Save",0,0,MNID_SAVEGAME);
466   worldmap_menu->additem(MN_GOTO,"Options",0,options_menu);
467   worldmap_menu->additem(MN_HL,"",0,0);
468   worldmap_menu->additem(MN_ACTION,"Quit Game",0,0,MNID_QUITWORLDMAP);
469
470   highscore_menu->additem(MN_TEXTFIELD,"Enter your name:",0,0);
471 }
472
473 void update_load_save_game_menu(Menu* pmenu)
474 {
475   for(int i = 2; i < 7; ++i)
476     {
477       // FIXME: Insert a real savegame struct/class here instead of
478       // doing string vodoo
479       std::string tmp = slotinfo(i - 1);
480       pmenu->item[i].kind = MN_ACTION;
481       pmenu->item[i].change_text(tmp.c_str());
482     }
483 }
484
485 bool process_load_game_menu()
486 {
487   int slot = load_game_menu->check();
488
489   if(slot != -1 && load_game_menu->get_item(slot).kind == MN_ACTION)
490     {
491       WorldMapNS::WorldMap worldmap;
492
493       char slotfile[1024];
494       snprintf(slotfile, 1024, "%s/slot%d.stsg", st_save_dir, slot-1);
495      
496       // Load the game or at least set the savegame_file variable
497       worldmap.loadgame(slotfile);
498
499       worldmap.display();
500       
501       Menu::set_current(main_menu);
502
503       st_pause_ticks_stop();
504       return true;
505     }
506   else
507     {
508       return false;
509     }
510 }
511
512 /* Handle changes made to global settings in the options menu. */
513 void process_options_menu(void)
514 {
515   switch (options_menu->check())
516     {
517     case MNID_OPENGL:
518 #ifndef NOOPENGL
519       if(use_gl != options_menu->item[MNID_OPENGL].toggled)
520         {
521           use_gl = !use_gl;
522           st_video_setup();
523         }
524 #else
525       options_menu->item[MNID_OPENGL].toggled = false;
526 #endif
527       break;
528     case MNID_FULLSCREEN:
529       if(use_fullscreen != options_menu->item[MNID_FULLSCREEN].toggled)
530         {
531           use_fullscreen = !use_fullscreen;
532           st_video_setup();
533         }
534       break;
535     case MNID_SOUND:
536       if(use_sound != options_menu->item[MNID_SOUND].toggled)
537         use_sound = !use_sound;
538       break;
539     case MNID_MUSIC:
540       if(use_music != options_menu->item[MNID_MUSIC].toggled)
541         {
542           enable_music(options_menu->item[MNID_MUSIC].toggled);
543         }
544       break;
545     case MNID_SHOWFPS:
546       if(show_fps != options_menu->item[MNID_SHOWFPS].toggled)
547         show_fps = !show_fps;
548       break;
549     }
550 }
551
552 void st_general_setup(void)
553 {
554   /* Seed random number generator: */
555
556   srand(SDL_GetTicks());
557
558   /* Set icon image: */
559
560   seticon();
561
562   /* Unicode needed for input handling: */
563
564   SDL_EnableUNICODE(1);
565
566   /* Load global images: */
567
568   black_text  = new Text(datadir + "/images/status/letters-black.png", TEXT_TEXT, 16,18);
569   gold_text   = new Text(datadir + "/images/status/letters-gold.png", TEXT_TEXT, 16,18);
570   blue_text   = new Text(datadir + "/images/status/letters-blue.png", TEXT_TEXT, 16,18);
571   red_text    = new Text(datadir + "/images/status/letters-red.png", TEXT_TEXT, 16,18);
572   white_text  = new Text(datadir + "/images/status/letters-white.png", TEXT_TEXT, 16,18);
573   white_small_text = new Text(datadir + "/images/status/letters-white-small.png", TEXT_TEXT, 8,9);
574   white_big_text   = new Text(datadir + "/images/status/letters-white-big.png", TEXT_TEXT, 20,23);
575   yellow_nums = new Text(datadir + "/images/status/numbers.png", TEXT_NUM, 32,32);
576
577   /* Load GUI/menu images: */
578   checkbox = new Surface(datadir + "/images/status/checkbox.png", USE_ALPHA);
579   checkbox_checked = new Surface(datadir + "/images/status/checkbox-checked.png", USE_ALPHA);
580   back = new Surface(datadir + "/images/status/back.png", USE_ALPHA);
581   arrow_left = new Surface(datadir + "/images/icons/left.png", USE_ALPHA);
582   arrow_right = new Surface(datadir + "/images/icons/right.png", USE_ALPHA);
583
584   /* Load the mouse-cursor */
585   mouse_cursor = new MouseCursor( datadir + "/images/status/mousecursor.png",1);
586   
587 }
588
589 void st_general_free(void)
590 {
591
592   /* Free global images: */
593
594   delete black_text;
595   delete gold_text;
596   delete white_text;
597   delete blue_text;
598   delete red_text;
599   delete white_small_text;
600   delete white_big_text;
601
602   /* Free GUI/menu images: */
603   delete checkbox;
604   delete checkbox_checked;
605   delete back;
606   delete arrow_left;
607   delete arrow_right;
608
609   /* Free mouse-cursor */
610   delete mouse_cursor;
611   
612   /* Free menus */
613   delete main_menu;
614   delete game_menu;
615   delete options_menu;
616   delete highscore_menu;
617   delete save_game_menu;
618   delete load_game_menu;
619 }
620
621 void st_video_setup(void)
622 {
623   if(screen != NULL)
624     SDL_FreeSurface(screen);
625
626   /* Init SDL Video: */
627
628   if (SDL_Init(SDL_INIT_VIDEO) < 0)
629     {
630       fprintf(stderr,
631               "\nError: I could not initialize video!\n"
632               "The Simple DirectMedia error that occured was:\n"
633               "%s\n\n", SDL_GetError());
634       exit(1);
635     }
636
637   /* Open display: */
638   if(use_gl)
639     st_video_setup_gl();
640   else
641     st_video_setup_sdl();
642
643   Surface::reload_all();
644
645   /* Set window manager stuff: */
646   SDL_WM_SetCaption("SuperTux " VERSION, "SuperTux");
647 }
648
649 void st_video_setup_sdl(void)
650 {
651   SDL_FreeSurface(screen);
652
653   if (use_fullscreen)
654     {
655       screen = SDL_SetVideoMode(640, 480, 0, SDL_FULLSCREEN ) ; /* | SDL_HWSURFACE); */
656       if (screen == NULL)
657         {
658           fprintf(stderr,
659                   "\nWarning: I could not set up fullscreen video for "
660                   "640x480 mode.\n"
661                   "The Simple DirectMedia error that occured was:\n"
662                   "%s\n\n", SDL_GetError());
663           use_fullscreen = false;
664         }
665     }
666   else
667     {
668       screen = SDL_SetVideoMode(640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF );
669
670       if (screen == NULL)
671         {
672           fprintf(stderr,
673                   "\nError: I could not set up video for 640x480 mode.\n"
674                   "The Simple DirectMedia error that occured was:\n"
675                   "%s\n\n", SDL_GetError());
676           exit(1);
677         }
678     }
679 }
680
681 void st_video_setup_gl(void)
682 {
683 #ifndef NOOPENGL
684
685   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
686   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
687   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
688   SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
689   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
690
691   if (use_fullscreen)
692     {
693       screen = SDL_SetVideoMode(640, 480, 0, SDL_FULLSCREEN | SDL_OPENGL) ; /* | SDL_HWSURFACE); */
694       if (screen == NULL)
695         {
696           fprintf(stderr,
697                   "\nWarning: I could not set up fullscreen video for "
698                   "640x480 mode.\n"
699                   "The Simple DirectMedia error that occured was:\n"
700                   "%s\n\n", SDL_GetError());
701           use_fullscreen = false;
702         }
703     }
704   else
705     {
706       screen = SDL_SetVideoMode(640, 480, 0, SDL_OPENGL);
707
708       if (screen == NULL)
709         {
710           fprintf(stderr,
711                   "\nError: I could not set up video for 640x480 mode.\n"
712                   "The Simple DirectMedia error that occured was:\n"
713                   "%s\n\n", SDL_GetError());
714           exit(1);
715         }
716     }
717
718   /*
719    * Set up OpenGL for 2D rendering.
720    */
721   glDisable(GL_DEPTH_TEST);
722   glDisable(GL_CULL_FACE);
723
724   glViewport(0, 0, screen->w, screen->h);
725   glMatrixMode(GL_PROJECTION);
726   glLoadIdentity();
727   glOrtho(0, screen->w, screen->h, 0, -1.0, 1.0);
728
729   glMatrixMode(GL_MODELVIEW);
730   glLoadIdentity();
731   glTranslatef(0.0f, 0.0f, 0.0f);
732
733 #endif
734
735 }
736
737 void st_joystick_setup(void)
738 {
739
740   /* Init Joystick: */
741
742   use_joystick = true;
743
744   if (SDL_Init(SDL_INIT_JOYSTICK) < 0)
745     {
746       fprintf(stderr, "Warning: I could not initialize joystick!\n"
747               "The Simple DirectMedia error that occured was:\n"
748               "%s\n\n", SDL_GetError());
749
750       use_joystick = false;
751     }
752   else
753     {
754       /* Open joystick: */
755       if (SDL_NumJoysticks() <= 0)
756         {
757           fprintf(stderr, "Warning: No joysticks are available.\n");
758
759           use_joystick = false;
760         }
761       else
762         {
763           js = SDL_JoystickOpen(joystick_num);
764
765           if (js == NULL)
766             {
767               fprintf(stderr, "Warning: Could not open joystick %d.\n"
768                       "The Simple DirectMedia error that occured was:\n"
769                       "%s\n\n", joystick_num, SDL_GetError());
770
771               use_joystick = false;
772             }
773           else
774             {
775               if (SDL_JoystickNumAxes(js) < 2)
776                 {
777                   fprintf(stderr,
778                           "Warning: Joystick does not have enough axes!\n");
779
780                   use_joystick = false;
781                 }
782               else
783                 {
784                   if (SDL_JoystickNumButtons(js) < 2)
785                     {
786                       fprintf(stderr,
787                               "Warning: "
788                               "Joystick does not have enough buttons!\n");
789
790                       use_joystick = false;
791                     }
792                 }
793             }
794         }
795     }
796 }
797
798 void st_audio_setup(void)
799 {
800
801   /* Init SDL Audio silently even if --disable-sound : */
802
803   if (audio_device)
804     {
805       if (SDL_Init(SDL_INIT_AUDIO) < 0)
806         {
807           /* only print out message if sound or music
808              was not disabled at command-line
809            */
810           if (use_sound || use_music)
811             {
812               fprintf(stderr,
813                       "\nWarning: I could not initialize audio!\n"
814                       "The Simple DirectMedia error that occured was:\n"
815                       "%s\n\n", SDL_GetError());
816             }
817           /* keep the programming logic the same :-)
818              because in this case, use_sound & use_music' values are ignored
819              when there's no available audio device
820           */
821           use_sound = false;
822           use_music = false;
823           audio_device = false;
824         }
825     }
826
827
828   /* Open sound silently regarless the value of "use_sound": */
829
830   if (audio_device)
831     {
832       if (open_audio(44100, AUDIO_S16, 2, 2048) < 0)
833         {
834           /* only print out message if sound or music
835              was not disabled at command-line
836            */
837           if (use_sound || use_music)
838             {
839               fprintf(stderr,
840                       "\nWarning: I could not set up audio for 44100 Hz "
841                       "16-bit stereo.\n"
842                       "The Simple DirectMedia error that occured was:\n"
843                       "%s\n\n", SDL_GetError());
844             }
845           use_sound = false;
846           use_music = false;
847           audio_device = false;
848         }
849     }
850
851 }
852
853
854 /* --- SHUTDOWN --- */
855
856 void st_shutdown(void)
857 {
858   close_audio();
859   SDL_Quit();
860   saveconfig();
861 }
862
863 /* --- ABORT! --- */
864
865 void st_abort(const std::string& reason, const std::string& details)
866 {
867   fprintf(stderr, "\nError: %s\n%s\n\n", reason.c_str(), details.c_str());
868   st_shutdown();
869   abort();
870 }
871
872
873 /* Set Icon (private) */
874
875 void seticon(void)
876 {
877 //  int masklen;
878 //  Uint8 * mask;
879   SDL_Surface * icon;
880
881
882   /* Load icon into a surface: */
883
884   icon = IMG_Load((datadir + "/images/icon.xpm").c_str());
885   if (icon == NULL)
886     {
887       fprintf(stderr,
888               "\nError: I could not load the icon image: %s%s\n"
889               "The Simple DirectMedia error that occured was:\n"
890               "%s\n\n", datadir.c_str(), "/images/icon.xpm", SDL_GetError());
891       exit(1);
892     }
893
894
895   /* Create mask: */
896 /*
897   masklen = (((icon -> w) + 7) / 8) * (icon -> h);
898   mask = (Uint8*) malloc(masklen * sizeof(Uint8));
899   memset(mask, 0xFF, masklen);
900 */
901
902   /* Set icon: */
903
904   SDL_WM_SetIcon(icon, NULL);//mask);
905
906
907   /* Free icon surface & mask: */
908
909 //  free(mask);
910   SDL_FreeSurface(icon);
911 }
912
913
914 /* Parse command-line arguments: */
915
916 void parseargs(int argc, char * argv[])
917 {
918   int i;
919
920   loadconfig();
921
922   /* Parse arguments: */
923
924   for (i = 1; i < argc; i++)
925     {
926       if (strcmp(argv[i], "--fullscreen") == 0 ||
927           strcmp(argv[i], "-f") == 0)
928         {
929           /* Use full screen: */
930
931           use_fullscreen = true;
932         }
933       else if (strcmp(argv[i], "--joystick") == 0 || strcmp(argv[i], "-j") == 0)
934         {
935           assert(i+1 < argc);
936           joystick_num = atoi(argv[++i]);
937         }
938       else if (strcmp(argv[i], "--joymap") == 0)
939         {
940           assert(i+1 < argc);
941           if (sscanf(argv[++i],
942                      "%d:%d:%d:%d:%d", 
943                      &joystick_keymap.x_axis, 
944                      &joystick_keymap.y_axis, 
945                      &joystick_keymap.a_button, 
946                      &joystick_keymap.b_button, 
947                      &joystick_keymap.start_button) != 5)
948             {
949               puts("Warning: Invalid or incomplete joymap, should be: 'XAXIS:YAXIS:A:B:START'");
950             }
951           else
952             {
953               std::cout << "Using new joymap:\n"
954                         << "  X-Axis:       " << joystick_keymap.x_axis << "\n"
955                         << "  Y-Axis:       " << joystick_keymap.y_axis << "\n"
956                         << "  A-Button:     " << joystick_keymap.a_button << "\n"
957                         << "  B-Button:     " << joystick_keymap.b_button << "\n"
958                         << "  Start-Button: " << joystick_keymap.start_button << std::endl;
959             }
960         }
961       else if (strcmp(argv[i], "--worldmap") == 0)
962         {
963           launch_worldmap_mode = true;
964         }
965       else if (strcmp(argv[i], "--datadir") == 0 
966                || strcmp(argv[i], "-d") == 0 )
967         {
968           assert(i+1 < argc);
969           datadir = argv[++i];
970         }
971       else if (strcmp(argv[i], "--show-fps") == 0)
972         {
973           /* Use full screen: */
974
975           show_fps = true;
976         }
977       else if (strcmp(argv[i], "--opengl") == 0 ||
978                strcmp(argv[i], "-gl") == 0)
979         {
980 #ifndef NOOPENGL
981           /* Use OpengGL: */
982
983           use_gl = true;
984 #endif
985         }
986       else if (strcmp(argv[i], "--sdl") == 0)
987           {
988             use_gl = false;
989           }
990       else if (strcmp(argv[i], "--usage") == 0)
991         {
992           /* Show usage: */
993
994           usage(argv[0], 0);
995         }
996       else if (strcmp(argv[i], "--version") == 0)
997         {
998           /* Show version: */
999           printf("SuperTux " VERSION "\n");
1000           exit(0);
1001         }
1002       else if (strcmp(argv[i], "--disable-sound") == 0)
1003         {
1004           /* Disable the compiled in sound feature */
1005           printf("Sounds disabled \n");
1006           use_sound = false;
1007           audio_device = false;
1008         }
1009       else if (strcmp(argv[i], "--disable-music") == 0)
1010         {
1011           /* Disable the compiled in sound feature */
1012           printf("Music disabled \n");
1013           use_music = false;
1014         }
1015       else if (strcmp(argv[i], "--debug-mode") == 0)
1016         {
1017           /* Enable the debug-mode */
1018           debug_mode = true;
1019
1020         }
1021       else if (strcmp(argv[i], "--help") == 0)
1022         {     /* Show help: */
1023           puts("Super Tux " VERSION "\n"
1024                "  Please see the file \"README.txt\" for more details.\n");
1025           printf("Usage: %s [OPTIONS] FILENAME\n\n", argv[0]);
1026           puts("Display Options:\n"
1027                "  --fullscreen        Run in fullscreen mode.\n"
1028                "  --opengl            If opengl support was compiled in, this will enable\n"
1029                "                      the EXPERIMENTAL OpenGL mode.\n"
1030                "  --sdl               Use non-opengl renderer\n"
1031                "\n"
1032                "Sound Options:\n"
1033                "  --disable-sound     If sound support was compiled in,  this will\n"
1034                "                      disable sound for this session of the game.\n"
1035                "  --disable-music     Like above, but this will disable music.\n"
1036                "\n"
1037                "Misc Options:\n"
1038                "  -j, --joystick NUM  Use joystick NUM (default: 0)\n" 
1039                "  --joymap XAXIS:YAXIS:A:B:START\n"
1040                "                      Define how joystick buttons and axis should be mapped\n"
1041                "  --worldmap          Start in worldmap-mode (EXPERIMENTAL)\n"          
1042                "  -d, --datadir DIR   Load Game data from DIR (default: automatic)\n"
1043                "  --debug-mode        Enables the debug-mode, which is useful for developers.\n"
1044                "  --help              Display a help message summarizing command-line\n"
1045                "                      options, license and game controls.\n"
1046                "  --usage             Display a brief message summarizing command-line options.\n"
1047                "  --version           Display the version of SuperTux you're running.\n\n"
1048                );
1049           exit(0);
1050         }
1051       else if (argv[i][0] != '-')
1052         {
1053           level_startup_file = argv[i];
1054         }
1055       else
1056         {
1057           /* Unknown - complain! */
1058
1059           usage(argv[0], 1);
1060         }
1061     }
1062 }
1063
1064
1065 /* Display usage: */
1066
1067 void usage(char * prog, int ret)
1068 {
1069   FILE * fi;
1070
1071
1072   /* Determine which stream to write to: */
1073
1074   if (ret == 0)
1075     fi = stdout;
1076   else
1077     fi = stderr;
1078
1079
1080   /* Display the usage message: */
1081
1082   fprintf(fi, "Usage: %s [--fullscreen] [--opengl] [--disable-sound] [--disable-music] [--debug-mode] | [--usage | --help | --version] [--worldmap] FILENAME\n",
1083           prog);
1084
1085
1086   /* Quit! */
1087
1088   exit(ret);
1089 }
1090