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"
57 #include "worldmap/worldmap.hpp"
58 #include "binreloc/binreloc.h"
60 SDL_Surface* screen = 0;
61 JoystickKeyboardController* main_controller = 0;
62 TinyGetText::DictionaryManager dictionary_manager;
67 static void init_config()
69 config = new Config();
72 } catch(std::exception& e) {
73 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
77 static void init_tinygettext()
79 dictionary_manager.add_directory("locale");
80 dictionary_manager.set_charset("UTF-8");
83 static void init_physfs(const char* argv0)
85 if(!PHYSFS_init(argv0)) {
86 std::stringstream msg;
87 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
88 throw std::runtime_error(msg.str());
91 // Initialize physfs (this is a slightly modified version of
92 // PHYSFS_setSaneConfig
93 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
94 const char* userdir = PHYSFS_getUserDir();
95 const char* dirsep = PHYSFS_getDirSeparator();
96 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
98 // Set configuration directory
99 sprintf(writedir, "%s.%s", userdir, application);
100 if(!PHYSFS_setWriteDir(writedir)) {
101 // try to create the directory
102 char* mkdir = new char[strlen(application) + 2];
103 sprintf(mkdir, ".%s", application);
104 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
105 std::ostringstream msg;
106 msg << "Failed creating configuration directory '"
107 << writedir << "': " << PHYSFS_getLastError();
110 throw std::runtime_error(msg.str());
114 if(!PHYSFS_setWriteDir(writedir)) {
115 std::ostringstream msg;
116 msg << "Failed to use configuration directory '"
117 << writedir << "': " << PHYSFS_getLastError();
119 throw std::runtime_error(msg.str());
122 PHYSFS_addToSearchPath(writedir, 0);
125 // Search for archives and add them to the search path
126 const char* archiveExt = "zip";
127 char** rc = PHYSFS_enumerateFiles("/");
128 size_t extlen = strlen(archiveExt);
130 for(char** i = rc; *i != 0; ++i) {
131 size_t l = strlen(*i);
132 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
133 const char* ext = (*i) + (l - extlen);
134 if(strcasecmp(ext, archiveExt) == 0) {
135 const char* d = PHYSFS_getRealDir(*i);
136 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
137 sprintf(str, "%s%s%s", d, dirsep, *i);
138 PHYSFS_addToSearchPath(str, 1);
146 // when started from source dir...
147 std::string dir = PHYSFS_getBaseDir();
149 std::string testfname = dir;
150 testfname += "/credits.txt";
151 bool sourcedir = false;
152 FILE* f = fopen(testfname.c_str(), "r");
155 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
156 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
163 // when started from Application file on Mac OS X...
164 dir = PHYSFS_getBaseDir();
165 dir += "SuperTux.app/Contents/Resources/data";
166 testfname = dir + "/credits.txt";
168 f = fopen(testfname.c_str(), "r");
171 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
172 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
180 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
182 #ifdef ENABLE_BINRELOC
186 dir = br_find_data_dir(APPDATADIR);
188 datadir += "/" PACKAGE_NAME;
192 datadir = APPDATADIR;
194 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
195 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
200 // allow symbolic links
201 PHYSFS_permitSymbolicLinks(1);
204 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
205 log_info << "[" << *i << "] is in the search path" << std::endl;
208 static void print_usage(const char* argv0)
210 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
213 " -f, --fullscreen Run in fullscreen mode\n"
214 " -w, --window Run in window mode\n"
215 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
216 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
217 " --disable-sfx Disable sound effects\n"
218 " --disable-music Disable music\n"
219 " --help Show this help message\n"
220 " --version Display SuperTux version and quit\n"
221 " --console Enable ingame scripting console\n"
222 " --noconsole Disable ingame scripting console\n"
223 " --show-fps Display framerate in levels\n"
224 " --no-show-fps Do not display framerate in levels\n"
225 " --record-demo FILE LEVEL Record a demo to FILE\n"
226 " --play-demo FILE LEVEL Play a recorded demo\n"
231 * Options that should be evaluated prior to any initializations at all go here
233 static bool pre_parse_commandline(int argc, char** argv)
235 for(int i = 1; i < argc; ++i) {
236 std::string arg = argv[i];
238 if(arg == "--help") {
239 print_usage(argv[0]);
241 } else if(arg == "--version") {
242 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
251 * Options that should be evaluated after config is read go here
253 static bool parse_commandline(int argc, char** argv)
255 for(int i = 1; i < argc; ++i) {
256 std::string arg = argv[i];
258 if(arg == "--fullscreen" || arg == "-f") {
259 config->use_fullscreen = true;
260 } else if(arg == "--window" || arg == "-w") {
261 config->use_fullscreen = false;
262 } else if(arg == "--geometry" || arg == "-g") {
264 print_usage(argv[0]);
265 throw std::runtime_error("Need to specify a parameter for geometry switch");
267 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
269 print_usage(argv[0]);
270 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
272 } else if(arg == "--aspect" || arg == "-a") {
274 print_usage(argv[0]);
275 throw std::runtime_error("Need to specify a parameter for aspect switch");
277 if(sscanf(argv[++i], "%d:%d", &config->aspectwidth, &config->aspectheight)
279 print_usage(argv[0]);
280 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
282 } else if(arg == "--show-fps") {
283 config->show_fps = true;
284 } else if(arg == "--no-show-fps") {
285 config->show_fps = false;
286 } else if(arg == "--console") {
287 config->console_enabled = true;
288 } else if(arg == "--noconsole") {
289 config->console_enabled = false;
290 } else if(arg == "--disable-sfx") {
291 config->sound_enabled = false;
292 } else if(arg == "--disable-music") {
293 config->music_enabled = false;
294 } else if(arg == "--play-demo") {
296 print_usage(argv[0]);
297 throw std::runtime_error("Need to specify a demo filename");
299 config->start_demo = argv[++i];
300 } else if(arg == "--record-demo") {
302 print_usage(argv[0]);
303 throw std::runtime_error("Need to specify a demo filename");
305 config->record_demo = argv[++i];
306 } else if(arg == "-d") {
307 config->enable_script_debugger = true;
308 } else if(arg[0] != '-') {
309 config->start_level = arg;
311 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
319 static void init_sdl()
321 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
322 std::stringstream msg;
323 msg << "Couldn't initialize SDL: " << SDL_GetError();
324 throw std::runtime_error(msg.str());
329 SDL_EnableUNICODE(1);
331 // wait 100ms and clear SDL event queue because sometimes we have random
332 // joystick events in the queue on startup...
335 while(SDL_PollEvent(&dummy))
339 static void init_rand()
341 const char *how = config->random_seed? ", user fixed.": ", from time().";
343 config->random_seed = systemRandom.srand(config->random_seed);
345 log_info << "Using random seed " << config->random_seed << how << std::endl;
350 if(texture_manager != NULL)
351 texture_manager->save_textures();
353 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
354 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
355 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
356 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
358 int flags = SDL_OPENGL;
359 if(config->use_fullscreen)
360 flags |= SDL_FULLSCREEN;
361 int width = config->screenwidth;
362 int height = config->screenheight;
365 screen = SDL_SetVideoMode(width, height, bpp, flags);
367 std::stringstream msg;
368 msg << "Couldn't set video mode (" << width << "x" << height
369 << "-" << bpp << "bpp): " << SDL_GetError();
370 throw std::runtime_error(msg.str());
373 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
376 SDL_Surface* icon = IMG_Load_RW(
377 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
379 SDL_WM_SetIcon(icon, 0);
380 SDL_FreeSurface(icon);
384 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
388 // use aspect ratio to calculate logical resolution
389 if (config->aspectwidth > config->aspectheight) {
391 SCREEN_WIDTH=600*config->aspectwidth/config->aspectheight;
395 SCREEN_HEIGHT=600*config->aspectheight/config->aspectwidth;
398 // setup opengl state and transform
399 glDisable(GL_DEPTH_TEST);
400 glDisable(GL_CULL_FACE);
401 glEnable(GL_TEXTURE_2D);
403 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
405 glViewport(0, 0, screen->w, screen->h);
406 glMatrixMode(GL_PROJECTION);
408 // logical resolution here not real monitor resolution
409 glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
410 glMatrixMode(GL_MODELVIEW);
412 glTranslatef(0, 0, 0);
414 check_gl_error("Setting up view matrices");
416 if(texture_manager != NULL)
417 texture_manager->reload_textures();
419 texture_manager = new TextureManager();
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)
505 if(pre_parse_commandline(argc, argv))
508 Console::instance = new Console();
509 init_physfs(argv[0]);
512 timelog("controller");
513 main_controller = new JoystickKeyboardController();
516 timelog("tinygettext");
518 timelog("commandline");
519 if(parse_commandline(argc, argv))
525 Console::instance->init_graphics();
526 timelog("scripting");
527 Scripting::init_squirrel(config->enable_script_debugger);
528 timelog("resources");
532 main_loop = new MainLoop();
533 if(config->start_level != "") {
534 // we have a normal path specified at commandline not physfs paths.
535 // So we simply mount that path here...
536 std::string dir = FileSystem::dirname(config->start_level);
537 PHYSFS_addToSearchPath(dir.c_str(), true);
539 if(config->start_level.size() > 4 &&
540 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
542 main_loop->push_screen(new WorldMapNS::WorldMap(
543 FileSystem::basename(config->start_level)));
545 init_rand();//If level uses random eg. for
546 // rain particles before we do this:
547 std::auto_ptr<GameSession> session (
548 new GameSession(FileSystem::basename(config->start_level)));
550 config->random_seed =session->get_demo_random_seed(config->start_demo);
551 init_rand();//initialise generator with seed from session
553 if(config->start_demo != "")
554 session->play_demo(config->start_demo);
556 if(config->record_demo != "")
557 session->record_demo(config->record_demo);
558 main_loop->push_screen(session.release());
562 main_loop->push_screen(new TitleScreen());
565 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
567 } catch(std::exception& e) {
568 log_fatal << "Unexpected exception: " << e.what() << std::endl;
571 log_fatal << "Unexpected exception" << std::endl;
586 delete main_controller;
587 main_controller = NULL;
588 delete Console::instance;
589 Console::instance = NULL;
590 Scripting::exit_squirrel();
591 delete texture_manager;
592 texture_manager = NULL;