-modified moving platform class to make use of the new path class.
[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.hpp"
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.hpp"
42 #include "resources.hpp"
43 #include "gettext.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "video/surface.hpp"
46 #include "control/joystickkeyboardcontroller.hpp"
47 #include "misc.hpp"
48 #include "title.hpp"
49 #include "game_session.hpp"
50 #include "file_system.hpp"
51 #include "physfs/physfs_sdl.hpp"
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   bool sourcedir = false;
144   FILE* f = fopen(testfname.c_str(), "r");
145   if(f) {
146     fclose(f);
147     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
148       std::cout << "Warning: Couldn't add '" << dir 
149                 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
150     } else {
151       sourcedir = true;
152     }
153   }
154
155   if(!sourcedir) {
156 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
157     std::string datadir;
158 #ifdef ENABLE_BINRELOC
159     char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
160     datadir = brdatadir;
161     free(brdatadir);
162 #else
163     datadir = APPDATADIR;
164 #endif
165     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
166       std::cout << "Couldn't add '" << datadir
167         << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
168     }
169 #endif
170   }
171
172   // allow symbolic links
173   PHYSFS_permitSymbolicLinks(1);
174
175   //show search Path
176   for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
177     printf("[%s] is in the search path.\n", *i);
178 }
179
180 static void print_usage(const char* argv0)
181 {
182   fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
183   fprintf(stderr,
184           _("Options:\n"
185             "  -f, --fullscreen             Run in fullscreen mode\n"
186             "  -w, --window                 Run in window mode\n"
187             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
188             "  --help                       Show this help message\n"
189             "  --version                    Display SuperTux version and quit\n"
190             "  --show-fps                   Display framerate in levels\n"
191             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
192             "  --play-demo FILE LEVEL       Play a recorded demo\n"
193             "\n"));
194 }
195
196 static void parse_commandline(int argc, char** argv)
197 {
198   for(int i = 1; i < argc; ++i) {
199     std::string arg = argv[i];
200
201     if(arg == "--fullscreen" || arg == "-f") {
202       config->use_fullscreen = true;
203     } else if(arg == "--window" || arg == "-w") {
204       config->use_fullscreen = false;
205     } else if(arg == "--geometry" || arg == "-g") {
206       if(i+1 >= argc) {
207         print_usage(argv[0]);
208         throw std::runtime_error("Need to specify a parameter for geometry switch");
209       }
210       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
211          != 2) {
212         print_usage(argv[0]);
213         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
214       }
215     } else if(arg == "--show-fps") {
216       config->show_fps = true;
217     } else if(arg == "--play-demo") {
218       if(i+1 >= argc) {
219         print_usage(argv[0]);
220         throw std::runtime_error("Need to specify a demo filename");
221       }
222       config->start_demo = argv[++i];
223     } else if(arg == "--record-demo") {
224       if(i+1 >= argc) {
225         print_usage(argv[0]);
226         throw std::runtime_error("Need to specify a demo filename");
227       }
228       config->record_demo = argv[++i];
229     } else if(arg == "--help") {
230       print_usage(argv[0]);
231       throw std::runtime_error("");
232     } else if(arg == "--version") {
233       std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
234       throw std::runtime_error("");
235     } else if(arg[0] != '-') {
236       config->start_level = arg;
237     } else {
238       std::cerr << "Unknown option '" << arg << "'.\n";
239       std::cerr << "Use --help to see a list of options.\n";
240     }
241   }
242
243   // TODO joystick switchyes...
244 }
245
246 static void init_sdl()
247 {
248   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
249     std::stringstream msg;
250     msg << "Couldn't initialize SDL: " << SDL_GetError();
251     throw std::runtime_error(msg.str());
252   }
253
254   SDL_EnableUNICODE(1);
255
256   // wait 100ms and clear SDL event queue because sometimes we have random
257   // joystick events in the queue on startup...
258   SDL_Delay(100);
259   SDL_Event dummy;
260   while(SDL_PollEvent(&dummy))
261       ;
262 }
263
264 static void check_gl_error()
265 {
266   GLenum glerror = glGetError();
267   std::string errormsg;
268   
269   if(glerror != GL_NO_ERROR) {
270     switch(glerror) {
271       case GL_INVALID_ENUM:
272         errormsg = "Invalid enumeration value";
273         break;
274       case GL_INVALID_VALUE:
275         errormsg = "Numeric argzment out of range";
276         break;
277       case GL_INVALID_OPERATION:
278         errormsg = "Invalid operation";
279         break;
280       case GL_STACK_OVERFLOW:
281         errormsg = "stack overflow";
282         break;
283       case GL_STACK_UNDERFLOW:
284         errormsg = "stack underflow";
285         break;
286       case GL_OUT_OF_MEMORY:
287         errormsg = "out of memory";
288         break;
289       case GL_TABLE_TOO_LARGE:
290         errormsg = "table too large";
291         break;
292       default:
293         errormsg = "unknown error number";
294         break;
295     }
296     std::stringstream msg;
297     msg << "OpenGL Error: " << errormsg;
298     throw std::runtime_error(msg.str());
299   }
300 }
301
302 void init_video()
303 {
304   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
305   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
306   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
307   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
308   
309   int flags = SDL_OPENGL;
310   if(config->use_fullscreen)
311     flags |= SDL_FULLSCREEN;
312   int width = config->screenwidth;
313   int height = config->screenheight;
314   int bpp = 0;
315
316   screen = SDL_SetVideoMode(width, height, bpp, flags);
317   if(screen == 0) {
318     std::stringstream msg;
319     msg << "Couldn't set video mode (" << width << "x" << height
320         << "-" << bpp << "bpp): " << SDL_GetError();
321     throw std::runtime_error(msg.str());
322   }
323
324   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
325
326   // set icon
327   SDL_Surface* icon = IMG_Load_RW(
328       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
329   if(icon != 0) {
330     SDL_WM_SetIcon(icon, 0);
331     SDL_FreeSurface(icon);
332   }
333 #ifdef DEBUG
334   else {
335     std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
336   }
337 #endif
338
339   // setup opengl state and transform
340   glDisable(GL_DEPTH_TEST);
341   glDisable(GL_CULL_FACE);
342
343   glViewport(0, 0, screen->w, screen->h);
344   glMatrixMode(GL_PROJECTION);
345   glLoadIdentity();
346   // logical resolution here not real monitor resolution
347   glOrtho(0, 800, 600, 0, -1.0, 1.0);
348   glMatrixMode(GL_MODELVIEW);
349   glLoadIdentity();
350   glTranslatef(0, 0, 0);
351
352   check_gl_error();
353
354   Surface::reload_all();
355 }
356
357 static void init_audio()
358 {
359   sound_manager = new SoundManager();
360   
361   sound_manager->enable_sound(config->sound_enabled);
362   sound_manager->enable_music(config->music_enabled);
363 }
364
365 static void quit_audio()
366 {
367   if(sound_manager) {
368     delete sound_manager;
369     sound_manager = 0;
370   }
371 }
372
373 void wait_for_event(float min_delay, float max_delay)
374 {
375   assert(min_delay <= max_delay);
376   
377   Uint32 min = (Uint32) (min_delay * 1000);
378   Uint32 max = (Uint32) (max_delay * 1000);
379
380   Uint32 ticks = SDL_GetTicks();
381   while(SDL_GetTicks() - ticks < min) {
382     SDL_Delay(10);
383     sound_manager->update();
384   }
385
386   // clear even queue
387   SDL_Event event;
388   while (SDL_PollEvent(&event))
389   {}
390
391   /* Handle events: */
392   bool running = false;
393   ticks = SDL_GetTicks();
394   while(running) {
395     while(SDL_PollEvent(&event)) {
396       switch(event.type) {
397         case SDL_QUIT:
398           throw std::runtime_error("received window close");
399         case SDL_KEYDOWN:
400         case SDL_JOYBUTTONDOWN:
401         case SDL_MOUSEBUTTONDOWN:
402           running = false;
403       }
404     }
405     if(SDL_GetTicks() - ticks >= (max - min))
406       running = false;
407     sound_manager->update();
408     SDL_Delay(10);
409   }
410 }
411
412 int main(int argc, char** argv) 
413 {
414   try {
415     srand(time(0));
416     init_physfs(argv[0]);
417     init_sdl();
418     main_controller = new JoystickKeyboardController();    
419     init_config();
420     init_tinygettext();
421     parse_commandline(argc, argv);
422     init_audio();
423     init_video();
424
425     setup_menu();
426     load_shared();
427     if(config->start_level != "") {
428       // we have a normal path specified at commandline not physfs paths.
429       // So we simply mount that path here...
430       std::string dir = FileSystem::dirname(config->start_level);
431       PHYSFS_addToSearchPath(dir.c_str(), true);
432       GameSession session(
433           FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
434       if(config->start_demo != "")
435         session.play_demo(config->start_demo);
436       if(config->record_demo != "")
437         session.record_demo(config->record_demo);
438       session.run();
439     } else {
440       // normal game
441       title();
442     }    
443   } catch(std::exception& e) {
444     std::cerr << "Unexpected exception: " << e.what() << std::endl;
445     return 1;
446   } catch(...) {
447     std::cerr << "Unexpected exception." << std::endl;
448     return 1;
449   }
450
451   free_menu();
452   unload_shared();
453 #ifdef DEBUG
454   Surface::debug_check();
455 #endif
456   quit_audio();
457
458   if(config)
459     config->save();
460   delete config;
461   delete main_controller;
462   SDL_Quit();
463   PHYSFS_deinit();
464   
465   return 0;
466 }