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