supertux is using physfs now, this simplifies the code and generalises file handling
[supertux.git] / src / main.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2005 Matthias Braun <matze@braunis.de>
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
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "main.h"
24
25 #include <stdexcept>
26 #include <iostream>
27 #include <sstream>
28 #include <time.h>
29 #include <stdlib.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <dirent.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <physfs.h>
36 #include <SDL.h>
37 #include <SDL_mixer.h>
38 #include <SDL_image.h>
39 #include <SDL_opengl.h>
40
41 #include "gameconfig.h"
42 #include "resources.h"
43 #include "gettext.h"
44 #include "audio/sound_manager.h"
45 #include "video/surface.h"
46 #include "control/joystickkeyboardcontroller.h"
47 #include "misc.h"
48 #include "title.h"
49 #include "game_session.h"
50 #include "file_system.h"
51 #include "physfs/physfs_sdl.h"
52
53 SDL_Surface* screen = 0;
54 JoystickKeyboardController* main_controller = 0;
55 TinyGetText::DictionaryManager dictionary_manager;
56
57 static void init_config()
58 {
59   config = new Config();
60   try {
61     config->load();
62   } catch(std::exception& e) {
63 #ifdef DEBUG
64     std::cerr << "Couldn't load config file: " << e.what() << "\n";
65 #endif
66   }
67 }
68
69 static void init_tinygettext()
70 {
71   dictionary_manager.add_directory("locale");
72   dictionary_manager.set_charset("UTF-8");
73 }
74
75 static void init_physfs(const char* argv0)
76 {
77   if(!PHYSFS_init(argv0)) {
78     std::stringstream msg;
79     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
80     throw std::runtime_error(msg.str());
81   }
82
83   // Initialize physfs (this is a slightly modified version of
84   // PHYSFS_setSaneConfig
85   const char* application = PACKAGE_NAME;
86   const char* userdir = PHYSFS_getUserDir();
87   const char* dirsep = PHYSFS_getDirSeparator();
88   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
89
90   // Set configuration directory
91   sprintf(writedir, "%s.%s", userdir, application);
92   if(!PHYSFS_setWriteDir(writedir)) {
93     // try to create the directory
94     char* mkdir = new char[strlen(application) + 2];
95     sprintf(mkdir, ".%s", application);
96     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
97       std::ostringstream msg;
98       msg << "Failed creating configuration directory '" 
99           << writedir << "': " << PHYSFS_getLastError();
100       delete[] writedir;
101       delete[] mkdir;
102       throw std::runtime_error(msg.str());
103     }
104     delete[] mkdir;
105     
106     if(!PHYSFS_setWriteDir(writedir)) {
107       std::ostringstream msg;
108       msg << "Failed to use configuration directory '" 
109           <<  writedir << "': " << PHYSFS_getLastError();
110       delete[] writedir;
111       throw std::runtime_error(msg.str());
112     }
113   }
114   PHYSFS_addToSearchPath(writedir, 0);
115   delete[] writedir;
116
117   // Search for archives and add them to the search path
118   const char* archiveExt = "zip";
119   char** rc = PHYSFS_enumerateFiles("/");
120   size_t extlen = strlen(archiveExt);
121
122   for(char** i = rc; *i != 0; ++i) {
123     size_t l = strlen(*i);
124     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
125       const char* ext = (*i) + (l - extlen);
126       if(strcasecmp(ext, archiveExt) == 0) {
127         const char* d = PHYSFS_getRealDir(*i);
128         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
129         sprintf(str, "%s%s%s", d, dirsep, *i);
130         PHYSFS_addToSearchPath(str, 1);
131         delete[] str;
132       }
133     }
134   }
135   
136   PHYSFS_freeList(rc);
137
138   // when started from source dir...
139   std::string dir = PHYSFS_getBaseDir();
140   dir += "/data";
141   std::string testfname = dir;
142   testfname += "/credits.txt";
143   FILE* f = fopen(testfname.c_str(), "r");
144   if(f) {
145     fclose(f);
146     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
147       std::cout << "Warning: Couldn't add '" << dir 
148                 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
149     }
150   }
151
152 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
153   std::string datadir;
154 #ifdef ENABLE_BINRELOC
155   char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
156   datadir = brdatadir;
157   free(brdatadir);
158 #else
159   datadir = APPDATADIR;
160 #endif
161   if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
162     std::cout << "Couldn't add '" << datadir
163               << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
164   }
165 #endif
166
167   // allow symbolic links
168   PHYSFS_permitSymbolicLinks(1);
169
170   //show search Path
171   for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
172     printf("[%s] is in the search path.\n", *i);
173 }
174
175 static void print_usage(const char* argv0)
176 {
177   fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
178   fprintf(stderr,
179           _("Options:\n"
180             "  -f, --fullscreen             Run in fullscreen mode.\n"
181             "  -w, --window                 Run in window mode.\n"
182             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in give resolution\n"
183             "  --help                       Show this help message\n"
184             "  --version                    Display SuperTux version and quit\n"
185             "\n"));
186 }
187
188 static void parse_commandline(int argc, char** argv)
189 {
190   for(int i = 1; i < argc; ++i) {
191     std::string arg = argv[i];
192
193     if(arg == "--fullscreen" || arg == "-f") {
194       config->use_fullscreen = true;
195     } else if(arg == "--window" || arg == "-w") {
196       config->use_fullscreen = false;
197     } else if(arg == "--geometry" || arg == "-g") {
198       if(i+1 >= argc) {
199         print_usage(argv[0]);
200         throw std::runtime_error("Need to specify a parameter for geometry switch");
201       }
202       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
203          != 2) {
204         print_usage(argv[0]);
205         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
206       }
207     } else if(arg == "--show-fps") {
208       config->show_fps = true;
209     } else if(arg == "--play-demo") {
210       if(i+1 >= argc) {
211         print_usage(argv[0]);
212         throw std::runtime_error("Need to specify a demo filename");
213       }
214       config->start_demo = argv[++i];
215     } else if(arg == "--record-demo") {
216       if(i+1 >= argc) {
217         print_usage(argv[0]);
218         throw std::runtime_error("Need to specify a demo filename");
219       }
220       config->record_demo = argv[++i];
221     } else if(arg == "--help") {
222       print_usage(argv[0]);
223       throw std::runtime_error("");
224     } else if(arg == "--version") {
225       std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
226       throw std::runtime_error("");
227     } else if(arg[0] != '-') {
228       config->start_level = arg;
229     } else {
230       std::cerr << "Unknown option '" << arg << "'.\n";
231       std::cerr << "Use --help to see a list of options.\n";
232     }
233   }
234
235   // TODO joystick switchyes...
236 }
237
238 static void init_sdl()
239 {
240   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
241     std::stringstream msg;
242     msg << "Couldn't initialize SDL: " << SDL_GetError();
243     throw std::runtime_error(msg.str());
244   }
245
246   SDL_EnableUNICODE(1);
247
248   // wait 100ms and clear SDL event queue because sometimes we have random
249   // joystick events in the queue on startup...
250   SDL_Delay(100);
251   SDL_Event dummy;
252   while(SDL_PollEvent(&dummy))
253       ;
254 }
255
256 static void check_gl_error()
257 {
258   GLenum glerror = glGetError();
259   std::string errormsg;
260   
261   if(glerror != GL_NO_ERROR) {
262     switch(glerror) {
263       case GL_INVALID_ENUM:
264         errormsg = "Invalid enumeration value";
265         break;
266       case GL_INVALID_VALUE:
267         errormsg = "Numeric argzment out of range";
268         break;
269       case GL_INVALID_OPERATION:
270         errormsg = "Invalid operation";
271         break;
272       case GL_STACK_OVERFLOW:
273         errormsg = "stack overflow";
274         break;
275       case GL_STACK_UNDERFLOW:
276         errormsg = "stack underflow";
277         break;
278       case GL_OUT_OF_MEMORY:
279         errormsg = "out of memory";
280         break;
281       case GL_TABLE_TOO_LARGE:
282         errormsg = "table too large";
283         break;
284       default:
285         errormsg = "unknown error number";
286         break;
287     }
288     std::stringstream msg;
289     msg << "OpenGL Error: " << errormsg;
290     throw std::runtime_error(msg.str());
291   }
292 }
293
294 void init_video()
295 {
296   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
297   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
298   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
299   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
300   
301   int flags = SDL_OPENGL;
302   if(config->use_fullscreen)
303     flags |= SDL_FULLSCREEN;
304   int width = config->screenwidth;
305   int height = config->screenheight;
306   int bpp = 0;
307
308   screen = SDL_SetVideoMode(width, height, bpp, flags);
309   if(screen == 0) {
310     std::stringstream msg;
311     msg << "Couldn't set video mode (" << width << "x" << height
312         << "-" << bpp << "bpp): " << SDL_GetError();
313     throw std::runtime_error(msg.str());
314   }
315
316   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
317
318   // set icon
319   SDL_Surface* icon = IMG_Load_RW(
320       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
321   if(icon != 0) {
322     SDL_WM_SetIcon(icon, 0);
323     SDL_FreeSurface(icon);
324   }
325 #ifdef DEBUG
326   else {
327     std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
328   }
329 #endif
330
331   // setup opengl state and transform
332   glDisable(GL_DEPTH_TEST);
333   glDisable(GL_CULL_FACE);
334
335   glViewport(0, 0, screen->w, screen->h);
336   glMatrixMode(GL_PROJECTION);
337   glLoadIdentity();
338   // logical resolution here not real monitor resolution
339   glOrtho(0, 800, 600, 0, -1.0, 1.0);
340   glMatrixMode(GL_MODELVIEW);
341   glLoadIdentity();
342   glTranslatef(0, 0, 0);
343
344   check_gl_error();
345
346   Surface::reload_all();
347 }
348
349 static void init_audio()
350 {
351   sound_manager = new SoundManager();
352   
353   int format = MIX_DEFAULT_FORMAT;
354   if(Mix_OpenAudio(config->audio_frequency, format, config->audio_channels,
355                    config->audio_chunksize) < 0) {
356     std::cerr << "Couldn't initialize audio ("
357               << config->audio_frequency << "HZ, " << config->audio_channels
358               << " Channels, Format " << format << ", ChunkSize "
359               << config->audio_chunksize << "): " << SDL_GetError() << "\n";
360     return;
361   }
362   sound_manager->set_audio_device_available(true);
363   sound_manager->enable_sound(config->sound_enabled);
364   sound_manager->enable_music(config->music_enabled);
365   
366   if(Mix_AllocateChannels(config->audio_voices) < 0) {
367     std::cerr << "Couldn't allocate '" << config->audio_voices << "' audio voices: "
368               << SDL_GetError() << "\n";
369     return;
370   }
371 }
372
373 static void quit_audio()
374 {
375   if(sound_manager) {
376     if(sound_manager->audio_device_available())
377       Mix_CloseAudio();
378
379     delete sound_manager;
380     sound_manager = 0;
381   }
382 }
383
384 void wait_for_event(float min_delay, float max_delay)
385 {
386   assert(min_delay <= max_delay);
387   
388   Uint32 min = (Uint32) (min_delay * 1000);
389   Uint32 max = (Uint32) (max_delay * 1000);
390
391   SDL_Delay(min);
392
393   // clear even queue
394   SDL_Event event;
395   while (SDL_PollEvent(&event))
396   {}
397
398   /* Handle events: */
399   bool running = false;
400   Uint32 ticks = SDL_GetTicks();
401   while(running) {
402     while(SDL_PollEvent(&event)) {
403       switch(event.type) {
404         case SDL_QUIT:
405           throw std::runtime_error("received window close");
406         case SDL_KEYDOWN:
407         case SDL_JOYBUTTONDOWN:
408         case SDL_MOUSEBUTTONDOWN:
409           running = false;
410       }
411     }
412     if(SDL_GetTicks() - ticks >= (max - min))
413       running = false;
414     SDL_Delay(10);
415   }
416 }
417
418 int main(int argc, char** argv) 
419 {
420 #ifndef DEBUG // we want backtraces in debug mode so don't catch exceptions
421   try {
422 #endif
423     srand(time(0));
424     init_physfs(argv[0]);
425     init_sdl();
426     main_controller = new JoystickKeyboardController();    
427     init_config();
428     init_tinygettext();
429     parse_commandline(argc, argv);
430     init_audio();
431     init_video();
432
433     setup_menu();
434     load_shared();
435     if(config->start_level != "") {
436       // we have a normal path specified at commandline not physfs paths.
437       // So we simply mount that path here...
438       std::string dir = FileSystem::dirname(config->start_level);
439       PHYSFS_addToSearchPath(dir.c_str(), true);
440       GameSession session(
441           FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
442       if(config->start_demo != "")
443         session.play_demo(config->start_demo);
444       if(config->record_demo != "")
445         session.record_demo(config->record_demo);
446       session.run();
447     } else {
448       // normal game
449       title();
450     }    
451     
452 #ifndef DEBUG
453   } catch(std::exception& e) {
454     std::cerr << "Unexpected exception: " << e.what() << std::endl;
455     return 1;
456   } catch(...) {
457     std::cerr << "Unexpected exception." << std::endl;
458     return 1;
459   }
460 #endif
461
462   free_menu();
463   unload_shared();
464 #ifdef DEBUG
465   Surface::debug_check();
466 #endif
467   quit_audio();
468
469   if(config)
470     config->save();
471   delete config;
472   delete main_controller;
473   SDL_Quit();
474   PHYSFS_deinit();
475   
476   return 0;
477 }