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>
37 #include <SDL_image.h>
40 #include "gameconfig.hpp"
41 #include "resources.hpp"
42 #include "gettext.hpp"
43 #include "audio/sound_manager.hpp"
44 #include "video/surface.hpp"
45 #include "video/texture_manager.hpp"
46 #include "video/glutil.hpp"
47 #include "control/joystickkeyboardcontroller.hpp"
48 #include "options_menu.hpp"
49 #include "mainloop.hpp"
51 #include "game_session.hpp"
52 #include "scripting/level.hpp"
53 #include "scripting/squirrel_util.hpp"
54 #include "file_system.hpp"
55 #include "physfs/physfs_sdl.hpp"
56 #include "random_generator.hpp"
58 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
62 static void init_config()
64 config = new Config();
67 } catch(std::exception& e) {
68 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
72 static void init_tinygettext()
74 dictionary_manager.add_directory("locale");
75 dictionary_manager.set_charset("UTF-8");
78 static void init_physfs(const char* argv0)
80 if(!PHYSFS_init(argv0)) {
81 std::stringstream msg;
82 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
83 throw std::runtime_error(msg.str());
86 // Initialize physfs (this is a slightly modified version of
87 // PHYSFS_setSaneConfig
88 const char* application = PACKAGE_NAME;
89 const char* userdir = PHYSFS_getUserDir();
90 const char* dirsep = PHYSFS_getDirSeparator();
91 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
93 // Set configuration directory
94 sprintf(writedir, "%s.%s", userdir, application);
95 if(!PHYSFS_setWriteDir(writedir)) {
96 // try to create the directory
97 char* mkdir = new char[strlen(application) + 2];
98 sprintf(mkdir, ".%s", application);
99 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
100 std::ostringstream msg;
101 msg << "Failed creating configuration directory '"
102 << writedir << "': " << PHYSFS_getLastError();
105 throw std::runtime_error(msg.str());
109 if(!PHYSFS_setWriteDir(writedir)) {
110 std::ostringstream msg;
111 msg << "Failed to use configuration directory '"
112 << writedir << "': " << PHYSFS_getLastError();
114 throw std::runtime_error(msg.str());
117 PHYSFS_addToSearchPath(writedir, 0);
120 // Search for archives and add them to the search path
121 const char* archiveExt = "zip";
122 char** rc = PHYSFS_enumerateFiles("/");
123 size_t extlen = strlen(archiveExt);
125 for(char** i = rc; *i != 0; ++i) {
126 size_t l = strlen(*i);
127 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
128 const char* ext = (*i) + (l - extlen);
129 if(strcasecmp(ext, archiveExt) == 0) {
130 const char* d = PHYSFS_getRealDir(*i);
131 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
132 sprintf(str, "%s%s%s", d, dirsep, *i);
133 PHYSFS_addToSearchPath(str, 1);
141 // when started from source dir...
142 std::string dir = PHYSFS_getBaseDir();
144 std::string testfname = dir;
145 testfname += "/credits.txt";
146 bool sourcedir = false;
147 FILE* f = fopen(testfname.c_str(), "r");
150 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
151 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
158 // when started from Application file on Mac OS X...
159 dir = PHYSFS_getBaseDir();
160 dir += "SuperTux.app/Contents/Resources/data";
161 testfname = dir + "/credits.txt";
163 f = fopen(testfname.c_str(), "r");
166 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
167 msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
175 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
177 #ifdef ENABLE_BINRELOC
178 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
182 datadir = APPDATADIR;
184 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
185 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
190 // allow symbolic links
191 PHYSFS_permitSymbolicLinks(1);
194 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
195 log_info << "[" << *i << "] is in the search path" << std::endl;
198 static void print_usage(const char* argv0)
200 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
203 " -f, --fullscreen Run in fullscreen mode\n"
204 " -w, --window Run in window mode\n"
205 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
206 " --disable-sfx Disable sound effects\n"
207 " --disable-music Disable music\n"
208 " --help Show this help message\n"
209 " --version Display SuperTux version and quit\n"
210 " --show-fps Display framerate in levels\n"
211 " --record-demo FILE LEVEL Record a demo to FILE\n"
212 " --play-demo FILE LEVEL Play a recorded demo\n"
216 static bool parse_commandline(int argc, char** argv)
218 for(int i = 1; i < argc; ++i) {
219 std::string arg = argv[i];
221 if(arg == "--fullscreen" || arg == "-f") {
222 config->use_fullscreen = true;
223 } else if(arg == "--window" || arg == "-w") {
224 config->use_fullscreen = false;
225 } else if(arg == "--geometry" || arg == "-g") {
227 print_usage(argv[0]);
228 throw std::runtime_error("Need to specify a parameter for geometry switch");
230 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
232 print_usage(argv[0]);
233 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
235 } else if(arg == "--show-fps") {
236 config->show_fps = true;
237 } else if(arg == "--disable-sfx") {
238 config->sound_enabled = false;
239 } else if(arg == "--disable-music") {
240 config->music_enabled = false;
241 } else if(arg == "--play-demo") {
243 print_usage(argv[0]);
244 throw std::runtime_error("Need to specify a demo filename");
246 config->start_demo = argv[++i];
247 } else if(arg == "--record-demo") {
249 print_usage(argv[0]);
250 throw std::runtime_error("Need to specify a demo filename");
252 config->record_demo = argv[++i];
253 } else if(arg == "-d") {
254 config->enable_script_debugger = true;
255 } else if(arg == "--help") {
256 print_usage(argv[0]);
258 } else if(arg == "--version") {
259 log_info << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
261 } else if(arg[0] != '-') {
262 config->start_level = arg;
264 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
271 static void init_sdl()
273 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
274 std::stringstream msg;
275 msg << "Couldn't initialize SDL: " << SDL_GetError();
276 throw std::runtime_error(msg.str());
281 SDL_EnableUNICODE(1);
283 // wait 100ms and clear SDL event queue because sometimes we have random
284 // joystick events in the queue on startup...
287 while(SDL_PollEvent(&dummy))
291 static void init_rand()
293 const char *how = config->random_seed? ", user fixed.": ", from time().";
295 config->random_seed = systemRandom.srand(config->random_seed);
297 log_info << "Using random seed " << config->random_seed << how << std::endl;
302 if(texture_manager != NULL)
303 texture_manager->save_textures();
305 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
306 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
307 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
308 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
310 int flags = SDL_OPENGL;
311 if(config->use_fullscreen)
312 flags |= SDL_FULLSCREEN;
313 int width = config->screenwidth;
314 int height = config->screenheight;
317 screen = SDL_SetVideoMode(width, height, bpp, flags);
319 std::stringstream msg;
320 msg << "Couldn't set video mode (" << width << "x" << height
321 << "-" << bpp << "bpp): " << SDL_GetError();
322 throw std::runtime_error(msg.str());
325 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
328 SDL_Surface* icon = IMG_Load_RW(
329 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
331 SDL_WM_SetIcon(icon, 0);
332 SDL_FreeSurface(icon);
336 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
340 // setup opengl state and transform
341 glDisable(GL_DEPTH_TEST);
342 glDisable(GL_CULL_FACE);
343 glEnable(GL_TEXTURE_2D);
345 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
347 glViewport(0, 0, screen->w, screen->h);
348 glMatrixMode(GL_PROJECTION);
350 // logical resolution here not real monitor resolution
351 glOrtho(0, 800, 600, 0, -1.0, 1.0);
352 glMatrixMode(GL_MODELVIEW);
354 glTranslatef(0, 0, 0);
356 check_gl_error("Setting up view matrices");
358 if(texture_manager != NULL)
359 texture_manager->reload_textures();
361 texture_manager = new TextureManager();
364 static void init_audio()
366 sound_manager = new SoundManager();
368 sound_manager->enable_sound(config->sound_enabled);
369 sound_manager->enable_music(config->music_enabled);
372 static void quit_audio()
374 if(sound_manager != NULL) {
375 delete sound_manager;
376 sound_manager = NULL;
380 void wait_for_event(float min_delay, float max_delay)
382 assert(min_delay <= max_delay);
384 Uint32 min = (Uint32) (min_delay * 1000);
385 Uint32 max = (Uint32) (max_delay * 1000);
387 Uint32 ticks = SDL_GetTicks();
388 while(SDL_GetTicks() - ticks < min) {
390 sound_manager->update();
395 while (SDL_PollEvent(&event))
399 bool running = false;
400 ticks = SDL_GetTicks();
402 while(SDL_PollEvent(&event)) {
408 case SDL_JOYBUTTONDOWN:
409 case SDL_MOUSEBUTTONDOWN:
413 if(SDL_GetTicks() - ticks >= (max - min))
415 sound_manager->update();
421 static Uint32 last_timelog_ticks = 0;
422 static const char* last_timelog_component = 0;
424 static inline void timelog(const char* component)
426 Uint32 current_ticks = SDL_GetTicks();
428 if(last_timelog_component != 0) {
429 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
432 last_timelog_ticks = current_ticks;
433 last_timelog_component = component;
436 static inline void timelog(const char* )
441 int main(int argc, char** argv)
446 Console::instance = new Console();
447 // srand(time(0)); // this breaks repeatability in random numbers
448 init_physfs(argv[0]);
451 timelog("controller");
452 main_controller = new JoystickKeyboardController();
455 timelog("tinygettext");
457 timelog("commandline");
458 if(parse_commandline(argc, argv))
464 Console::instance->init_graphics();
465 timelog("scripting");
466 Scripting::init_squirrel(config->enable_script_debugger);
467 timelog("resources");
471 main_loop = new MainLoop();
472 if(config->start_level != "") {
473 // we have a normal path specified at commandline not physfs paths.
474 // So we simply mount that path here...
475 std::string dir = FileSystem::dirname(config->start_level);
476 PHYSFS_addToSearchPath(dir.c_str(), true);
478 init_rand(); // play_demo sets seed, record_demo uses it
480 std::auto_ptr<GameSession> session
481 (new GameSession(FileSystem::basename(config->start_level)));
482 if(config->start_demo != "")
483 session->play_demo(config->start_demo);
485 if(config->record_demo != "")
486 session->record_demo(config->record_demo);
487 main_loop->push_screen(session.release());
490 main_loop->push_screen(new TitleScreen());
495 } catch(std::exception& e) {
496 log_fatal << "Unexpected exception: " << e.what() << std::endl;
499 log_fatal << "Unexpected exception" << std::endl;
514 delete main_controller;
515 main_controller = NULL;
516 delete Console::instance;
517 Console::instance = NULL;
518 Scripting::exit_squirrel();
519 delete texture_manager;
520 texture_manager = NULL;