4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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.
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.
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
31 #include <sys/types.h>
35 #include <SDL_image.h>
37 #include "gameconfig.hpp"
38 #include "resources.hpp"
39 #include "gettext.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "video/surface.hpp"
42 #include "video/texture_manager.hpp"
43 #include "video/drawing_context.hpp"
44 #include "video/glutil.hpp"
45 #include "control/joystickkeyboardcontroller.hpp"
46 #include "options_menu.hpp"
47 #include "mainloop.hpp"
49 #include "game_session.hpp"
50 #include "scripting/level.hpp"
51 #include "scripting/squirrel_util.hpp"
52 #include "file_system.hpp"
53 #include "physfs/physfs_sdl.hpp"
54 #include "random_generator.hpp"
55 #include "worldmap/worldmap.hpp"
56 #include "binreloc/binreloc.h"
58 namespace { DrawingContext *context_pointer; }
60 JoystickKeyboardController* main_controller = 0;
61 TinyGetText::DictionaryManager dictionary_manager;
66 static void init_config()
68 config = new Config();
71 } catch(std::exception& e) {
72 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
76 static void init_tinygettext()
78 dictionary_manager.add_directory("locale");
79 dictionary_manager.set_charset("UTF-8");
81 // Config setting "locale" overrides language detection
82 if (config->locale != "") {
83 dictionary_manager.set_language( config->locale );
87 static void init_physfs(const char* argv0)
89 if(!PHYSFS_init(argv0)) {
90 std::stringstream msg;
91 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
92 throw std::runtime_error(msg.str());
95 // Initialize physfs (this is a slightly modified version of
96 // PHYSFS_setSaneConfig
97 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
98 const char* userdir = PHYSFS_getUserDir();
99 const char* dirsep = PHYSFS_getDirSeparator();
100 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
102 // Set configuration directory
103 sprintf(writedir, "%s.%s", userdir, application);
104 if(!PHYSFS_setWriteDir(writedir)) {
105 // try to create the directory
106 char* mkdir = new char[strlen(application) + 2];
107 sprintf(mkdir, ".%s", application);
108 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
109 std::ostringstream msg;
110 msg << "Failed creating configuration directory '"
111 << writedir << "': " << PHYSFS_getLastError();
114 throw std::runtime_error(msg.str());
118 if(!PHYSFS_setWriteDir(writedir)) {
119 std::ostringstream msg;
120 msg << "Failed to use configuration directory '"
121 << writedir << "': " << PHYSFS_getLastError();
123 throw std::runtime_error(msg.str());
126 PHYSFS_addToSearchPath(writedir, 0);
129 // Search for archives and add them to the search path
130 const char* archiveExt = "zip";
131 char** rc = PHYSFS_enumerateFiles("/");
132 size_t extlen = strlen(archiveExt);
134 for(char** i = rc; *i != 0; ++i) {
135 size_t l = strlen(*i);
136 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
137 const char* ext = (*i) + (l - extlen);
138 if(strcasecmp(ext, archiveExt) == 0) {
139 const char* d = PHYSFS_getRealDir(*i);
140 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
141 sprintf(str, "%s%s%s", d, dirsep, *i);
142 PHYSFS_addToSearchPath(str, 1);
150 // when started from source dir...
151 std::string dir = PHYSFS_getBaseDir();
153 std::string testfname = dir;
154 testfname += "/credits.txt";
155 bool sourcedir = false;
156 FILE* f = fopen(testfname.c_str(), "r");
159 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
160 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167 // when started from Application file on Mac OS X...
168 dir = PHYSFS_getBaseDir();
169 dir += "SuperTux.app/Contents/Resources/data";
170 testfname = dir + "/credits.txt";
172 f = fopen(testfname.c_str(), "r");
175 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
176 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
184 PHYSFS_addToSearchPath(".\\data", 1);
188 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
190 #ifdef ENABLE_BINRELOC
194 dir = br_find_data_dir(APPDATADIR);
196 datadir += "/" PACKAGE_NAME;
200 datadir = APPDATADIR;
202 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
203 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
208 // allow symbolic links
209 PHYSFS_permitSymbolicLinks(1);
212 char** searchpath = PHYSFS_getSearchPath();
213 for(char** i = searchpath; *i != NULL; i++)
214 log_info << "[" << *i << "] is in the search path" << std::endl;
215 PHYSFS_freeList(searchpath);
218 static void print_usage(const char* argv0)
220 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
223 " -f, --fullscreen Run in fullscreen mode\n"
224 " -w, --window Run in window mode\n"
225 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
226 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
227 " --disable-sfx Disable sound effects\n"
228 " --disable-music Disable music\n"
229 " --help Show this help message\n"
230 " --version Display SuperTux version and quit\n"
231 " --console Enable ingame scripting console\n"
232 " --noconsole Disable ingame scripting console\n"
233 " --show-fps Display framerate in levels\n"
234 " --no-show-fps Do not display framerate in levels\n"
235 " --record-demo FILE LEVEL Record a demo to FILE\n"
236 " --play-demo FILE LEVEL Play a recorded demo\n"
241 * Options that should be evaluated prior to any initializations at all go here
243 static bool pre_parse_commandline(int argc, char** argv)
245 for(int i = 1; i < argc; ++i) {
246 std::string arg = argv[i];
248 if(arg == "--version") {
249 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
258 * Options that should be evaluated after config is read go here
260 static bool parse_commandline(int argc, char** argv)
262 for(int i = 1; i < argc; ++i) {
263 std::string arg = argv[i];
265 if(arg == "--help") {
266 print_usage(argv[0]);
268 } else if(arg == "--fullscreen" || arg == "-f") {
269 config->use_fullscreen = true;
270 } else if(arg == "--window" || arg == "-w") {
271 config->use_fullscreen = false;
272 } else if(arg == "--geometry" || arg == "-g") {
274 print_usage(argv[0]);
275 throw std::runtime_error("Need to specify a parameter for geometry switch");
277 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
279 print_usage(argv[0]);
280 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
282 } else if(arg == "--aspect" || arg == "-a") {
284 print_usage(argv[0]);
285 throw std::runtime_error("Need to specify a parameter for aspect switch");
287 if(strcasecmp(argv[i+1], "auto") == 0) {
289 config->aspect_ratio = -1;
291 int aspect_width, aspect_height;
292 if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
293 print_usage(argv[0]);
294 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
296 config->aspect_ratio = static_cast<double>(aspect_width) /
297 static_cast<double>(aspect_height);
299 } else if(arg == "--show-fps") {
300 config->show_fps = true;
301 } else if(arg == "--no-show-fps") {
302 config->show_fps = false;
303 } else if(arg == "--console") {
304 config->console_enabled = true;
305 } else if(arg == "--noconsole") {
306 config->console_enabled = false;
307 } else if(arg == "--disable-sfx") {
308 config->sound_enabled = false;
309 } else if(arg == "--disable-music") {
310 config->music_enabled = false;
311 } else if(arg == "--play-demo") {
313 print_usage(argv[0]);
314 throw std::runtime_error("Need to specify a demo filename");
316 config->start_demo = argv[++i];
317 } else if(arg == "--record-demo") {
319 print_usage(argv[0]);
320 throw std::runtime_error("Need to specify a demo filename");
322 config->record_demo = argv[++i];
323 } else if(arg == "-d") {
324 config->enable_script_debugger = true;
325 } else if(arg[0] != '-') {
326 config->start_level = arg;
328 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
336 static void init_sdl()
338 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
339 std::stringstream msg;
340 msg << "Couldn't initialize SDL: " << SDL_GetError();
341 throw std::runtime_error(msg.str());
346 SDL_EnableUNICODE(1);
348 // wait 100ms and clear SDL event queue because sometimes we have random
349 // joystick events in the queue on startup...
352 while(SDL_PollEvent(&dummy))
356 static void init_rand()
358 config->random_seed = systemRandom.srand(config->random_seed);
360 //const char *how = config->random_seed? ", user fixed.": ", from time().";
361 //log_info << "Using random seed " << config->random_seed << how << std::endl;
366 static int desktop_width = 0;
367 static int desktop_height = 0;
369 /* unfortunately only newer SDLs have these infos */
370 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
371 /* find which resolution the user normally uses */
372 if(desktop_width == 0) {
373 const SDL_VideoInfo *info = SDL_GetVideoInfo();
374 desktop_width = info->current_w;
375 desktop_height = info->current_h;
379 double aspect_ratio = config->aspect_ratio;
381 // try to guess aspect ratio of monitor if needed
382 if (aspect_ratio <= 0) {
383 if(config->use_fullscreen && desktop_width > 0) {
384 aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
386 aspect_ratio = 4.0 / 3.0;
390 // use aspect ratio to calculate logical resolution
391 if (aspect_ratio > 1) {
392 SCREEN_WIDTH = static_cast<int> (600 * aspect_ratio + 0.5);
396 SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
399 context_pointer->init_renderer();
400 screen = SDL_GetVideoSurface();
402 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
405 SDL_Surface* icon = IMG_Load_RW(
406 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
408 SDL_WM_SetIcon(icon, 0);
409 SDL_FreeSurface(icon);
413 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
419 log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
422 static void init_audio()
424 sound_manager = new SoundManager();
426 sound_manager->enable_sound(config->sound_enabled);
427 sound_manager->enable_music(config->music_enabled);
430 static void quit_audio()
432 if(sound_manager != NULL) {
433 delete sound_manager;
434 sound_manager = NULL;
438 void wait_for_event(float min_delay, float max_delay)
440 assert(min_delay <= max_delay);
442 Uint32 min = (Uint32) (min_delay * 1000);
443 Uint32 max = (Uint32) (max_delay * 1000);
445 Uint32 ticks = SDL_GetTicks();
446 while(SDL_GetTicks() - ticks < min) {
448 sound_manager->update();
453 while (SDL_PollEvent(&event))
457 bool running = false;
458 ticks = SDL_GetTicks();
460 while(SDL_PollEvent(&event)) {
466 case SDL_JOYBUTTONDOWN:
467 case SDL_MOUSEBUTTONDOWN:
471 if(SDL_GetTicks() - ticks >= (max - min))
473 sound_manager->update();
479 static Uint32 last_timelog_ticks = 0;
480 static const char* last_timelog_component = 0;
482 static inline void timelog(const char* component)
484 Uint32 current_ticks = SDL_GetTicks();
486 if(last_timelog_component != 0) {
487 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
490 last_timelog_ticks = current_ticks;
491 last_timelog_component = component;
494 static inline void timelog(const char* )
499 int main(int argc, char** argv)
507 if(pre_parse_commandline(argc, argv))
510 Console::instance = new Console();
511 init_physfs(argv[0]);
514 timelog("controller");
515 main_controller = new JoystickKeyboardController();
518 timelog("tinygettext");
520 timelog("commandline");
521 if(parse_commandline(argc, argv))
526 DrawingContext context;
527 context_pointer = &context;
529 Console::instance->init_graphics();
530 timelog("scripting");
531 Scripting::init_squirrel(config->enable_script_debugger);
532 timelog("resources");
536 main_loop = new MainLoop();
537 if(config->start_level != "") {
538 // we have a normal path specified at commandline not physfs paths.
539 // So we simply mount that path here...
540 std::string dir = FileSystem::dirname(config->start_level);
541 PHYSFS_addToSearchPath(dir.c_str(), true);
543 if(config->start_level.size() > 4 &&
544 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
546 main_loop->push_screen(new WorldMapNS::WorldMap(
547 FileSystem::basename(config->start_level)));
549 init_rand();//If level uses random eg. for
550 // rain particles before we do this:
551 std::auto_ptr<GameSession> session (
552 new GameSession(FileSystem::basename(config->start_level)));
554 config->random_seed =session->get_demo_random_seed(config->start_demo);
555 init_rand();//initialise generator with seed from session
557 if(config->start_demo != "")
558 session->play_demo(config->start_demo);
560 if(config->record_demo != "")
561 session->record_demo(config->record_demo);
562 main_loop->push_screen(session.release());
566 main_loop->push_screen(new TitleScreen());
569 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
570 main_loop->run(context);
572 } catch(std::exception& e) {
573 log_fatal << "Unexpected exception: " << e.what() << std::endl;
576 log_fatal << "Unexpected exception" << std::endl;
592 delete main_controller;
593 main_controller = NULL;
594 delete Console::instance;
595 Console::instance = NULL;
596 Scripting::exit_squirrel();
597 delete texture_manager;
598 texture_manager = NULL;