Changed the logic of aspect ratio, aspect_width/height now give projection size
[supertux.git] / src / main.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 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 "log.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <physfs.h>
34 #include <SDL.h>
35 #include <SDL_image.h>
36
37 #ifdef MACOSX
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
40 }
41 #endif
42
43 #include "gameconfig.hpp"
44 #include "resources.hpp"
45 #include "gettext.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "video/surface.hpp"
48 #include "video/texture_manager.hpp"
49 #include "video/drawing_context.hpp"
50 #include "video/glutil.hpp"
51 #include "control/joystickkeyboardcontroller.hpp"
52 #include "options_menu.hpp"
53 #include "mainloop.hpp"
54 #include "title.hpp"
55 #include "game_session.hpp"
56 #include "scripting/level.hpp"
57 #include "scripting/squirrel_util.hpp"
58 #include "file_system.hpp"
59 #include "physfs/physfs_sdl.hpp"
60 #include "random_generator.hpp"
61 #include "worldmap/worldmap.hpp"
62 #include "binreloc/binreloc.h"
63
64 namespace { DrawingContext *context_pointer; }
65 SDL_Surface *screen;
66 JoystickKeyboardController* main_controller = 0;
67 TinyGetText::DictionaryManager dictionary_manager;
68
69 int SCREEN_WIDTH;
70 int SCREEN_HEIGHT;
71
72 static void init_config()
73 {
74   config = new Config();
75   try {
76     config->load();
77   } catch(std::exception& e) {
78     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
79   }
80 }
81
82 static void init_tinygettext()
83 {
84   dictionary_manager.add_directory("locale");
85   dictionary_manager.set_charset("UTF-8");
86
87   // Config setting "locale" overrides language detection
88   if (config->locale != "") {
89     dictionary_manager.set_language( config->locale );
90   }
91 }
92
93 static void init_physfs(const char* argv0)
94 {
95   if(!PHYSFS_init(argv0)) {
96     std::stringstream msg;
97     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
98     throw std::runtime_error(msg.str());
99   }
100
101   // Initialize physfs (this is a slightly modified version of
102   // PHYSFS_setSaneConfig
103   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
104   const char* userdir = PHYSFS_getUserDir();
105   const char* dirsep = PHYSFS_getDirSeparator();
106   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
107
108   // Set configuration directory
109   sprintf(writedir, "%s.%s", userdir, application);
110   if(!PHYSFS_setWriteDir(writedir)) {
111     // try to create the directory
112     char* mkdir = new char[strlen(application) + 2];
113     sprintf(mkdir, ".%s", application);
114     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
115       std::ostringstream msg;
116       msg << "Failed creating configuration directory '"
117           << writedir << "': " << PHYSFS_getLastError();
118       delete[] writedir;
119       delete[] mkdir;
120       throw std::runtime_error(msg.str());
121     }
122     delete[] mkdir;
123
124     if(!PHYSFS_setWriteDir(writedir)) {
125       std::ostringstream msg;
126       msg << "Failed to use configuration directory '"
127           <<  writedir << "': " << PHYSFS_getLastError();
128       delete[] writedir;
129       throw std::runtime_error(msg.str());
130     }
131   }
132   PHYSFS_addToSearchPath(writedir, 0);
133   delete[] writedir;
134
135   // Search for archives and add them to the search path
136   const char* archiveExt = "zip";
137   char** rc = PHYSFS_enumerateFiles("/");
138   size_t extlen = strlen(archiveExt);
139
140   for(char** i = rc; *i != 0; ++i) {
141     size_t l = strlen(*i);
142     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
143       const char* ext = (*i) + (l - extlen);
144       if(strcasecmp(ext, archiveExt) == 0) {
145         const char* d = PHYSFS_getRealDir(*i);
146         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
147         sprintf(str, "%s%s%s", d, dirsep, *i);
148         PHYSFS_addToSearchPath(str, 1);
149         delete[] str;
150       }
151     }
152   }
153
154   PHYSFS_freeList(rc);
155
156   // when started from source dir...
157   std::string dir = PHYSFS_getBaseDir();
158   dir += "/data";
159   std::string testfname = dir;
160   testfname += "/credits.txt";
161   bool sourcedir = false;
162   FILE* f = fopen(testfname.c_str(), "r");
163   if(f) {
164     fclose(f);
165     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
166       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167     } else {
168       sourcedir = true;
169     }
170   }
171
172 #ifdef MACOSX
173 {
174   using namespace supertux_apple;
175
176   // when started from Application file on Mac OS X...
177   char path[PATH_MAX];
178   CFBundleRef mainBundle = CFBundleGetMainBundle();
179   assert(mainBundle != 0);
180   CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
181   assert(mainBundleURL != 0);
182   CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
183   assert(pathStr != 0);
184   CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
185   CFRelease(mainBundleURL);
186   CFRelease(pathStr);
187
188   dir = std::string(path) + "/Contents/Resources/data";
189   testfname = dir + "/credits.txt";
190   sourcedir = false;
191   f = fopen(testfname.c_str(), "r");
192   if(f) {
193     fclose(f);
194     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
195       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
196     } else {
197       sourcedir = true;
198     }
199   }
200 }
201 #endif
202
203 #ifdef _WIN32
204   PHYSFS_addToSearchPath(".\\data", 1);
205 #endif
206
207   if(!sourcedir) {
208 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
209     std::string datadir;
210 #ifdef ENABLE_BINRELOC
211
212     char* dir;
213     br_init (NULL);
214     dir = br_find_data_dir(APPDATADIR);
215     datadir = dir;
216     free(dir);
217
218 #else
219     datadir = APPDATADIR;
220 #endif
221     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
222       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
223     }
224 #endif
225   }
226
227   // allow symbolic links
228   PHYSFS_permitSymbolicLinks(1);
229
230   //show search Path
231   char** searchpath = PHYSFS_getSearchPath();
232   for(char** i = searchpath; *i != NULL; i++)
233     log_info << "[" << *i << "] is in the search path" << std::endl;
234   PHYSFS_freeList(searchpath);
235 }
236
237 static void print_usage(const char* argv0)
238 {
239   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
240   fprintf(stderr,
241           _("Options:\n"
242             "  -f, --fullscreen             Run in fullscreen mode\n"
243             "  -w, --window                 Run in window mode\n"
244             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
245             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
246             "  -d, --default                Reset video settings to default values\n"
247             "  --disable-sfx                Disable sound effects\n"
248             "  --disable-music              Disable music\n"
249             "  --help                       Show this help message\n"
250             "  --version                    Display SuperTux version and quit\n"
251             "  --console                    Enable ingame scripting console\n"
252             "  --noconsole                  Disable ingame scripting console\n"
253             "  --show-fps                   Display framerate in levels\n"
254             "  --no-show-fps                Do not display framerate in levels\n"
255             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
256             "  --play-demo FILE LEVEL       Play a recorded demo\n"
257             "\n"));
258 }
259
260 /**
261  * Options that should be evaluated prior to any initializations at all go here
262  */
263 static bool pre_parse_commandline(int argc, char** argv)
264 {
265   for(int i = 1; i < argc; ++i) {
266     std::string arg = argv[i];
267
268     if(arg == "--version") {
269       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
270       return true;
271     }
272   }
273
274   return false;
275 }
276
277 /**
278  * Options that should be evaluated after config is read go here
279  */
280 static bool parse_commandline(int argc, char** argv)
281 {
282   for(int i = 1; i < argc; ++i) {
283     std::string arg = argv[i];
284
285     if(arg == "--help") {
286       print_usage(argv[0]);
287       return true;
288     } else if(arg == "--fullscreen" || arg == "-f") {
289       config->use_fullscreen = true;
290     } else if(arg == "--default" || arg == "-d") {
291       config->use_fullscreen = false;
292       config->aspect_width  = 800;
293       config->aspect_height = 600;
294       config->screenwidth   = 800;
295       config->screenheight  = 600;
296     } else if(arg == "--window" || arg == "-w") {
297       config->use_fullscreen = false;
298     } else if(arg == "--geometry" || arg == "-g") {
299       if(i+1 >= argc) {
300         print_usage(argv[0]);
301         throw std::runtime_error("Need to specify a parameter for geometry switch");
302       }
303       i += 1;
304       if (sscanf(argv[i], "%dx%d:%dx%d",
305                  &config->screenwidth,  &config->screenheight,
306                  &config->aspect_width, &config->aspect_height) != 4 &&
307           sscanf(argv[i], "%dx%d", &config->screenwidth, &config->screenheight) != 2)
308         {
309           print_usage(argv[0]);
310           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
311         }
312     } else if(arg == "--aspect" || arg == "-a") {
313       if(i+1 >= argc) {
314         print_usage(argv[0]);
315         throw std::runtime_error("Need to specify a parameter for aspect switch");
316       } else {
317         int aspect_width  = 4;
318         int aspect_height = 3;
319         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
320           print_usage(argv[0]);
321           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
322         } else {
323           float aspect_ratio = static_cast<double>(config->aspect_width) /
324             static_cast<double>(config->aspect_height);
325
326           // use aspect ratio to calculate logical resolution
327           if (aspect_ratio > 1) {
328             config->aspect_width  = static_cast<int> (600 * aspect_ratio + 0.5);
329             config->aspect_height = 600;
330           } else {
331             config->aspect_width  = 600;
332             config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
333           }
334         }
335       }
336     } else if(arg == "--show-fps") {
337       config->show_fps = true;
338     } else if(arg == "--no-show-fps") {
339       config->show_fps = false;
340     } else if(arg == "--console") {
341       config->console_enabled = true;
342     } else if(arg == "--noconsole") {
343       config->console_enabled = false;
344     } else if(arg == "--disable-sfx") {
345       config->sound_enabled = false;
346     } else if(arg == "--disable-music") {
347       config->music_enabled = false;
348     } else if(arg == "--play-demo") {
349       if(i+1 >= argc) {
350         print_usage(argv[0]);
351         throw std::runtime_error("Need to specify a demo filename");
352       }
353       config->start_demo = argv[++i];
354     } else if(arg == "--record-demo") {
355       if(i+1 >= argc) {
356         print_usage(argv[0]);
357         throw std::runtime_error("Need to specify a demo filename");
358       }
359       config->record_demo = argv[++i];
360     } else if(arg == "-d") {
361       config->enable_script_debugger = true;
362     } else if(arg[0] != '-') {
363       config->start_level = arg;
364     } else {
365       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
366       return true;
367     }
368   }
369
370   return false;
371 }
372
373 static void init_sdl()
374 {
375   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
376     std::stringstream msg;
377     msg << "Couldn't initialize SDL: " << SDL_GetError();
378     throw std::runtime_error(msg.str());
379   }
380   // just to be sure
381   atexit(SDL_Quit);
382
383   SDL_EnableUNICODE(1);
384
385   // wait 100ms and clear SDL event queue because sometimes we have random
386   // joystick events in the queue on startup...
387   SDL_Delay(100);
388   SDL_Event dummy;
389   while(SDL_PollEvent(&dummy))
390       ;
391 }
392
393 static void init_rand()
394 {
395   config->random_seed = systemRandom.srand(config->random_seed);
396
397   //const char *how = config->random_seed? ", user fixed.": ", from time().";
398   //log_info << "Using random seed " << config->random_seed << how << std::endl;
399 }
400
401 void init_video()
402 {
403   static int desktop_width = 0;
404   static int desktop_height = 0;
405
406 /* unfortunately only newer SDLs have these infos */
407 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
408   /* find which resolution the user normally uses */
409   if(desktop_width == 0) {
410     const SDL_VideoInfo *info = SDL_GetVideoInfo();
411     desktop_width  = info->current_w;
412     desktop_height = info->current_h;
413   }
414 #endif
415   
416   SCREEN_WIDTH  = config->aspect_width;
417   SCREEN_HEIGHT = config->aspect_height;
418
419   context_pointer->init_renderer();
420   screen = SDL_GetVideoSurface();
421
422   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
423
424   // set icon
425   #ifdef MACOSX
426   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
427   #else
428   const char* icon_fname = "images/engine/icons/supertux.xpm";
429   #endif
430   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
431   if(icon != 0) {
432     SDL_WM_SetIcon(icon, 0);
433     SDL_FreeSurface(icon);
434   }
435 #ifdef DEBUG
436   else {
437     log_warning << "Couldn't find icon '" << icon_fname << "'" << std::endl;
438   }
439 #endif
440
441   SDL_ShowCursor(0);
442
443   log_info << (config->use_fullscreen?"fullscreen ":"window ")
444            << " Window: " << config->screenwidth << "x" << config->screenheight
445            << " Area: "   << config->aspect_width << "x" << config->aspect_height << std::endl;
446 }
447
448 static void init_audio()
449 {
450   sound_manager = new SoundManager();
451
452   sound_manager->enable_sound(config->sound_enabled);
453   sound_manager->enable_music(config->music_enabled);
454 }
455
456 static void quit_audio()
457 {
458   if(sound_manager != NULL) {
459     delete sound_manager;
460     sound_manager = NULL;
461   }
462 }
463
464 void wait_for_event(float min_delay, float max_delay)
465 {
466   assert(min_delay <= max_delay);
467
468   Uint32 min = (Uint32) (min_delay * 1000);
469   Uint32 max = (Uint32) (max_delay * 1000);
470
471   Uint32 ticks = SDL_GetTicks();
472   while(SDL_GetTicks() - ticks < min) {
473     SDL_Delay(10);
474     sound_manager->update();
475   }
476
477   // clear event queue
478   SDL_Event event;
479   while (SDL_PollEvent(&event))
480   {}
481
482   /* Handle events: */
483   bool running = false;
484   ticks = SDL_GetTicks();
485   while(running) {
486     while(SDL_PollEvent(&event)) {
487       switch(event.type) {
488         case SDL_QUIT:
489           main_loop->quit();
490           break;
491         case SDL_KEYDOWN:
492         case SDL_JOYBUTTONDOWN:
493         case SDL_MOUSEBUTTONDOWN:
494           running = false;
495       }
496     }
497     if(SDL_GetTicks() - ticks >= (max - min))
498       running = false;
499     sound_manager->update();
500     SDL_Delay(10);
501   }
502 }
503
504 #ifdef DEBUG
505 static Uint32 last_timelog_ticks = 0;
506 static const char* last_timelog_component = 0;
507
508 static inline void timelog(const char* component)
509 {
510   Uint32 current_ticks = SDL_GetTicks();
511
512   if(last_timelog_component != 0) {
513     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
514   }
515
516   last_timelog_ticks = current_ticks;
517   last_timelog_component = component;
518 }
519 #else
520 static inline void timelog(const char* )
521 {
522 }
523 #endif
524
525 int main(int argc, char** argv)
526 {
527   int result = 0;
528
529 #ifndef NO_CATCH
530   try {
531 #endif
532
533     if(pre_parse_commandline(argc, argv))
534       return 0;
535
536     Console::instance = new Console();
537     init_physfs(argv[0]);
538     init_sdl();
539
540     timelog("controller");
541     main_controller = new JoystickKeyboardController();
542     timelog("config");
543     init_config();
544     timelog("tinygettext");
545     init_tinygettext();
546     timelog("commandline");
547     if(parse_commandline(argc, argv))
548       return 0;
549     timelog("audio");
550     init_audio();
551     timelog("video");
552     DrawingContext context;
553     context_pointer = &context;
554     init_video();
555     Console::instance->init_graphics();
556     timelog("scripting");
557     Scripting::init_squirrel(config->enable_script_debugger);
558     timelog("resources");
559     load_shared();
560     timelog(0);
561
562     main_loop = new MainLoop();
563     if(config->start_level != "") {
564       // we have a normal path specified at commandline not physfs paths.
565       // So we simply mount that path here...
566       std::string dir = FileSystem::dirname(config->start_level);
567       PHYSFS_addToSearchPath(dir.c_str(), true);
568
569       if(config->start_level.size() > 4 &&
570               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
571           init_rand();
572           main_loop->push_screen(new WorldMapNS::WorldMap(
573                       FileSystem::basename(config->start_level)));
574       } else {
575         init_rand();//If level uses random eg. for
576         // rain particles before we do this:
577         std::auto_ptr<GameSession> session (
578                 new GameSession(FileSystem::basename(config->start_level)));
579
580         config->random_seed =session->get_demo_random_seed(config->start_demo);
581         init_rand();//initialise generator with seed from session
582
583         if(config->start_demo != "")
584           session->play_demo(config->start_demo);
585
586         if(config->record_demo != "")
587           session->record_demo(config->record_demo);
588         main_loop->push_screen(session.release());
589       }
590     } else {
591       init_rand();
592       main_loop->push_screen(new TitleScreen());
593     }
594
595     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
596     main_loop->run(context);
597 #ifndef NO_CATCH
598   } catch(std::exception& e) {
599     log_fatal << "Unexpected exception: " << e.what() << std::endl;
600     result = 1;
601   } catch(...) {
602     log_fatal << "Unexpected exception" << std::endl;
603     result = 1;
604   }
605 #endif
606
607   delete main_loop;
608   main_loop = NULL;
609
610   unload_shared();
611   quit_audio();
612
613   if(config)
614     config->save();
615   delete config;
616   config = NULL;
617   delete main_controller;
618   main_controller = NULL;
619   delete Console::instance;
620   Console::instance = NULL;
621   Scripting::exit_squirrel();
622   delete texture_manager;
623   texture_manager = NULL;
624   SDL_Quit();
625   PHYSFS_deinit();
626
627   return result;
628 }