2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include <SDL_image.h>
25 namespace supertux_apple {
26 # include <CoreFoundation/CoreFoundation.h>
27 } // namespace supertux_apple
30 #include "tinygettext/log.hpp"
32 #include "addon/addon_manager.hpp"
33 #include "audio/sound_manager.hpp"
34 #include "binreloc/binreloc.h"
35 #include "control/joystickkeyboardcontroller.hpp"
36 #include "math/random_generator.hpp"
37 #include "physfs/ifile_stream.hpp"
38 #include "physfs/physfs_sdl.hpp"
39 #include "physfs/physfs_file_system.hpp"
40 #include "scripting/squirrel_util.hpp"
41 #include "supertux/gameconfig.hpp"
42 #include "supertux/globals.hpp"
43 #include "supertux/mainloop.hpp"
44 #include "supertux/resources.hpp"
45 #include "supertux/title_screen.hpp"
46 #include "util/file_system.hpp"
47 #include "util/gettext.hpp"
48 #include "video/drawing_context.hpp"
49 #include "worldmap/worldmap.hpp"
51 namespace { DrawingContext *context_pointer; }
53 static void init_config()
55 g_config = new Config();
58 } catch(std::exception& e) {
59 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
63 static void init_tinygettext()
65 tinygettext::Log::set_log_info_callback(0);
66 dictionary_manager.set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
68 dictionary_manager.add_directory("locale");
69 dictionary_manager.set_charset("UTF-8");
71 // Config setting "locale" overrides language detection
72 if (g_config->locale != "") {
73 dictionary_manager.set_language(tinygettext::Language::from_name(g_config->locale));
77 static void init_physfs(const char* argv0)
79 if(!PHYSFS_init(argv0)) {
80 std::stringstream msg;
81 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
82 throw std::runtime_error(msg.str());
85 // allow symbolic links
86 PHYSFS_permitSymbolicLinks(1);
88 // Initialize physfs (this is a slightly modified version of
89 // PHYSFS_setSaneConfig
90 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
91 const char* userdir = PHYSFS_getUserDir();
92 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
94 // Set configuration directory
95 sprintf(writedir, "%s.%s", userdir, application);
96 if(!PHYSFS_setWriteDir(writedir)) {
97 // try to create the directory
98 char* mkdir = new char[strlen(application) + 2];
99 sprintf(mkdir, ".%s", application);
100 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
101 std::ostringstream msg;
102 msg << "Failed creating configuration directory '"
103 << writedir << "': " << PHYSFS_getLastError();
106 throw std::runtime_error(msg.str());
110 if(!PHYSFS_setWriteDir(writedir)) {
111 std::ostringstream msg;
112 msg << "Failed to use configuration directory '"
113 << writedir << "': " << PHYSFS_getLastError();
115 throw std::runtime_error(msg.str());
118 PHYSFS_addToSearchPath(writedir, 0);
121 // when started from source dir...
122 std::string dir = PHYSFS_getBaseDir();
124 std::string testfname = dir;
125 testfname += "/credits.txt";
126 bool sourcedir = false;
127 FILE* f = fopen(testfname.c_str(), "r");
130 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
131 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
139 using namespace supertux_apple;
141 // when started from Application file on Mac OS X...
143 CFBundleRef mainBundle = CFBundleGetMainBundle();
144 assert(mainBundle != 0);
145 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
146 assert(mainBundleURL != 0);
147 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
148 assert(pathStr != 0);
149 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
150 CFRelease(mainBundleURL);
153 dir = std::string(path) + "/Contents/Resources/data";
154 testfname = dir + "/credits.txt";
156 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;
169 PHYSFS_addToSearchPath(".\\data", 1);
173 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
175 #ifdef ENABLE_BINRELOC
179 dir = br_find_data_dir(APPDATADIR);
184 datadir = APPDATADIR;
186 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
187 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
193 char** searchpath = PHYSFS_getSearchPath();
194 for(char** i = searchpath; *i != NULL; i++)
195 log_info << "[" << *i << "] is in the search path" << std::endl;
196 PHYSFS_freeList(searchpath);
199 static void print_usage(const char* argv0)
201 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
204 " -f, --fullscreen Run in fullscreen mode\n"
205 " -w, --window Run in window mode\n"
206 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
207 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
208 " -d, --default Reset video settings to default values\n"
209 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
210 " --disable-sfx Disable sound effects\n"
211 " --disable-music Disable music\n"
212 " -h, --help Show this help message and quit\n"
213 " -v, --version Show SuperTux version and quit\n"
214 " --console Enable ingame scripting console\n"
215 " --noconsole Disable ingame scripting console\n"
216 " --show-fps Display framerate in levels\n"
217 " --no-show-fps Do not display framerate in levels\n"
218 " --record-demo FILE LEVEL Record a demo to FILE\n"
219 " --play-demo FILE LEVEL Play a recorded demo\n"
220 " -s, --debug-scripts Enable script debugger.\n"
225 * Options that should be evaluated prior to any initializations at all go here
227 static bool pre_parse_commandline(int argc, char** argv)
229 for(int i = 1; i < argc; ++i) {
230 std::string arg = argv[i];
232 if(arg == "--version" || arg == "-v") {
233 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
236 if(arg == "--help" || arg == "-h") {
237 print_usage(argv[0]);
246 * Options that should be evaluated after config is read go here
248 static bool parse_commandline(int argc, char** argv)
250 for(int i = 1; i < argc; ++i) {
251 std::string arg = argv[i];
253 if(arg == "--fullscreen" || arg == "-f") {
254 g_config->use_fullscreen = true;
255 } else if(arg == "--default" || arg == "-d") {
256 g_config->use_fullscreen = false;
258 g_config->window_width = 800;
259 g_config->window_height = 600;
261 g_config->fullscreen_width = 800;
262 g_config->fullscreen_height = 600;
264 g_config->aspect_width = 0; // auto detect
265 g_config->aspect_height = 0;
267 } else if(arg == "--window" || arg == "-w") {
268 g_config->use_fullscreen = false;
269 } else if(arg == "--geometry" || arg == "-g") {
273 print_usage(argv[0]);
274 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
279 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
281 print_usage(argv[0]);
282 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
286 g_config->window_width = width;
287 g_config->window_height = height;
289 g_config->fullscreen_width = width;
290 g_config->fullscreen_height = height;
293 } else if(arg == "--aspect" || arg == "-a") {
297 print_usage(argv[0]);
298 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
302 int aspect_width = 0;
303 int aspect_height = 0;
304 if (strcmp(argv[i], "auto") == 0)
309 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
311 print_usage(argv[0]);
312 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
316 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
317 static_cast<double>(g_config->aspect_height);
319 // use aspect ratio to calculate logical resolution
320 if (aspect_ratio > 1) {
321 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
322 g_config->aspect_height = 600;
324 g_config->aspect_width = 600;
325 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
329 } else if(arg == "--renderer") {
333 print_usage(argv[0]);
334 throw std::runtime_error("Need to specify a renderer for renderer argument");
338 g_config->video = get_video_system(argv[i]);
340 } else if(arg == "--show-fps") {
341 g_config->show_fps = true;
342 } else if(arg == "--no-show-fps") {
343 g_config->show_fps = false;
344 } else if(arg == "--console") {
345 g_config->console_enabled = true;
346 } else if(arg == "--noconsole") {
347 g_config->console_enabled = false;
348 } else if(arg == "--disable-sfx") {
349 g_config->sound_enabled = false;
350 } else if(arg == "--disable-music") {
351 g_config->music_enabled = false;
352 } else if(arg == "--play-demo") {
354 print_usage(argv[0]);
355 throw std::runtime_error("Need to specify a demo filename");
357 g_config->start_demo = argv[++i];
358 } else if(arg == "--record-demo") {
360 print_usage(argv[0]);
361 throw std::runtime_error("Need to specify a demo filename");
363 g_config->record_demo = argv[++i];
364 } else if(arg == "--debug-scripts" || arg == "-s") {
365 g_config->enable_script_debugger = true;
366 } else if(arg[0] != '-') {
367 g_config->start_level = arg;
369 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
377 static void init_sdl()
379 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
380 std::stringstream msg;
381 msg << "Couldn't initialize SDL: " << SDL_GetError();
382 throw std::runtime_error(msg.str());
387 SDL_EnableUNICODE(1);
389 // wait 100ms and clear SDL event queue because sometimes we have random
390 // joystick events in the queue on startup...
393 while(SDL_PollEvent(&dummy))
397 static void init_rand()
399 g_config->random_seed = systemRandom.srand(g_config->random_seed);
401 //const char *how = config->random_seed? ", user fixed.": ", from time().";
402 //log_info << "Using random seed " << config->random_seed << how << std::endl;
407 // FIXME: Add something here
411 context_pointer->init_renderer();
412 g_screen = SDL_GetVideoSurface();
414 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
418 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
420 const char* icon_fname = "images/engine/icons/supertux.xpm";
424 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
425 } catch (const std::runtime_error& err) {
427 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
430 SDL_WM_SetIcon(icon, 0);
431 SDL_FreeSurface(icon);
435 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
441 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
442 << " Window: " << g_config->window_width << "x" << g_config->window_height
443 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
444 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
447 static void init_audio()
449 sound_manager = new SoundManager();
451 sound_manager->enable_sound(g_config->sound_enabled);
452 sound_manager->enable_music(g_config->music_enabled);
455 static void quit_audio()
457 if(sound_manager != NULL) {
458 delete sound_manager;
459 sound_manager = NULL;
463 void wait_for_event(float min_delay, float max_delay)
465 assert(min_delay <= max_delay);
467 Uint32 min = (Uint32) (min_delay * 1000);
468 Uint32 max = (Uint32) (max_delay * 1000);
470 Uint32 ticks = SDL_GetTicks();
471 while(SDL_GetTicks() - ticks < min) {
473 sound_manager->update();
478 while (SDL_PollEvent(&event))
482 bool running = false;
483 ticks = SDL_GetTicks();
485 while(SDL_PollEvent(&event)) {
491 case SDL_JOYBUTTONDOWN:
492 case SDL_MOUSEBUTTONDOWN:
496 if(SDL_GetTicks() - ticks >= (max - min))
498 sound_manager->update();
504 static Uint32 last_timelog_ticks = 0;
505 static const char* last_timelog_component = 0;
507 static inline void timelog(const char* component)
509 Uint32 current_ticks = SDL_GetTicks();
511 if(last_timelog_component != 0) {
512 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
515 last_timelog_ticks = current_ticks;
516 last_timelog_component = component;
519 static inline void timelog(const char* )
524 std::istream* physfs_open_file(const char* name)
526 return new IFileStream(name);
529 void physfs_free_list(char** name)
531 PHYSFS_freeList(name);
534 int supertux_main(int argc, char** argv)
540 if(pre_parse_commandline(argc, argv))
543 Console::instance = new Console();
544 init_physfs(argv[0]);
547 timelog("controller");
548 g_main_controller = new JoystickKeyboardController();
554 AddonManager::get_instance().load_addons();
556 timelog("tinygettext");
559 timelog("commandline");
560 if(parse_commandline(argc, argv))
567 DrawingContext context;
568 context_pointer = &context;
571 Console::instance->init_graphics();
573 timelog("scripting");
574 Scripting::init_squirrel(g_config->enable_script_debugger);
576 timelog("resources");
581 g_main_loop = new MainLoop();
582 if(g_config->start_level != "") {
583 // we have a normal path specified at commandline, not a physfs path.
584 // So we simply mount that path here...
585 std::string dir = FileSystem::dirname(g_config->start_level);
586 log_debug << "Adding dir: " << dir << std::endl;
587 PHYSFS_addToSearchPath(dir.c_str(), true);
589 if(g_config->start_level.size() > 4 &&
590 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
592 g_main_loop->push_screen(new WorldMapNS::WorldMap(
593 FileSystem::basename(g_config->start_level)));
595 init_rand();//If level uses random eg. for
596 // rain particles before we do this:
597 std::auto_ptr<GameSession> session (
598 new GameSession(FileSystem::basename(g_config->start_level)));
600 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
601 init_rand();//initialise generator with seed from session
603 if(g_config->start_demo != "")
604 session->play_demo(g_config->start_demo);
606 if(g_config->record_demo != "")
607 session->record_demo(g_config->record_demo);
608 g_main_loop->push_screen(session.release());
612 g_main_loop->push_screen(new TitleScreen());
615 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
616 g_main_loop->run(context);
617 } catch(std::exception& e) {
618 log_fatal << "Unexpected exception: " << e.what() << std::endl;
621 log_fatal << "Unexpected exception" << std::endl;
635 delete g_main_controller;
636 g_main_controller = NULL;
637 delete Console::instance;
638 Console::instance = NULL;
639 Scripting::exit_squirrel();
640 delete texture_manager;
641 texture_manager = NULL;