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 {
29 #include "addon/addon_manager.hpp"
30 #include "audio/sound_manager.hpp"
31 #include "binreloc/binreloc.h"
32 #include "control/joystickkeyboardcontroller.hpp"
33 #include "math/random_generator.hpp"
34 #include "physfs/physfs_sdl.hpp"
35 #include "scripting/squirrel_util.hpp"
36 #include "supertux/gameconfig.hpp"
37 #include "supertux/mainloop.hpp"
38 #include "supertux/resources.hpp"
39 #include "supertux/title.hpp"
40 #include "util/file_system.hpp"
41 #include "util/gettext.hpp"
42 #include "video/drawing_context.hpp"
43 #include "worldmap/worldmap.hpp"
45 namespace { DrawingContext *context_pointer; }
47 SDL_Surface* g_screen;
48 JoystickKeyboardController* g_main_controller = 0;
49 TinyGetText::DictionaryManager dictionary_manager;
54 static void init_config()
56 g_config = new Config();
59 } catch(std::exception& e) {
60 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
64 static void init_tinygettext()
66 dictionary_manager.add_directory("locale");
67 dictionary_manager.set_charset("UTF-8");
69 // Config setting "locale" overrides language detection
70 if (g_config->locale != "") {
71 dictionary_manager.set_language( g_config->locale );
75 static void init_physfs(const char* argv0)
77 if(!PHYSFS_init(argv0)) {
78 std::stringstream msg;
79 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
80 throw std::runtime_error(msg.str());
83 // allow symbolic links
84 PHYSFS_permitSymbolicLinks(1);
86 // Initialize physfs (this is a slightly modified version of
87 // PHYSFS_setSaneConfig
88 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
89 const char* userdir = PHYSFS_getUserDir();
90 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
92 // Set configuration directory
93 sprintf(writedir, "%s.%s", userdir, application);
94 if(!PHYSFS_setWriteDir(writedir)) {
95 // try to create the directory
96 char* mkdir = new char[strlen(application) + 2];
97 sprintf(mkdir, ".%s", application);
98 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
99 std::ostringstream msg;
100 msg << "Failed creating configuration directory '"
101 << writedir << "': " << PHYSFS_getLastError();
104 throw std::runtime_error(msg.str());
108 if(!PHYSFS_setWriteDir(writedir)) {
109 std::ostringstream msg;
110 msg << "Failed to use configuration directory '"
111 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
116 PHYSFS_addToSearchPath(writedir, 0);
119 // when started from source dir...
120 std::string dir = PHYSFS_getBaseDir();
122 std::string testfname = dir;
123 testfname += "/credits.txt";
124 bool sourcedir = false;
125 FILE* f = fopen(testfname.c_str(), "r");
128 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
129 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
137 using namespace supertux_apple;
139 // when started from Application file on Mac OS X...
141 CFBundleRef mainBundle = CFBundleGetMainBundle();
142 assert(mainBundle != 0);
143 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
144 assert(mainBundleURL != 0);
145 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
146 assert(pathStr != 0);
147 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
148 CFRelease(mainBundleURL);
151 dir = std::string(path) + "/Contents/Resources/data";
152 testfname = dir + "/credits.txt";
154 f = fopen(testfname.c_str(), "r");
157 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
158 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167 PHYSFS_addToSearchPath(".\\data", 1);
171 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
173 #ifdef ENABLE_BINRELOC
177 dir = br_find_data_dir(APPDATADIR);
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;
191 char** searchpath = PHYSFS_getSearchPath();
192 for(char** i = searchpath; *i != NULL; i++)
193 log_info << "[" << *i << "] is in the search path" << std::endl;
194 PHYSFS_freeList(searchpath);
197 static void print_usage(const char* argv0)
199 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
202 " -f, --fullscreen Run in fullscreen mode\n"
203 " -w, --window Run in window mode\n"
204 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
205 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
206 " -d, --default Reset video settings to default values\n"
207 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
208 " --disable-sfx Disable sound effects\n"
209 " --disable-music Disable music\n"
210 " -h, --help Show this help message and quit\n"
211 " -v, --version Show SuperTux version and quit\n"
212 " --console Enable ingame scripting console\n"
213 " --noconsole Disable ingame scripting console\n"
214 " --show-fps Display framerate in levels\n"
215 " --no-show-fps Do not display framerate in levels\n"
216 " --record-demo FILE LEVEL Record a demo to FILE\n"
217 " --play-demo FILE LEVEL Play a recorded demo\n"
218 " -s, --debug-scripts Enable script debugger.\n"
223 * Options that should be evaluated prior to any initializations at all go here
225 static bool pre_parse_commandline(int argc, char** argv)
227 for(int i = 1; i < argc; ++i) {
228 std::string arg = argv[i];
230 if(arg == "--version" || arg == "-v") {
231 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
234 if(arg == "--help" || arg == "-h") {
235 print_usage(argv[0]);
244 * Options that should be evaluated after config is read go here
246 static bool parse_commandline(int argc, char** argv)
248 for(int i = 1; i < argc; ++i) {
249 std::string arg = argv[i];
251 if(arg == "--fullscreen" || arg == "-f") {
252 g_config->use_fullscreen = true;
253 } else if(arg == "--default" || arg == "-d") {
254 g_config->use_fullscreen = false;
256 g_config->window_width = 800;
257 g_config->window_height = 600;
259 g_config->fullscreen_width = 800;
260 g_config->fullscreen_height = 600;
262 g_config->aspect_width = 0; // auto detect
263 g_config->aspect_height = 0;
265 } else if(arg == "--window" || arg == "-w") {
266 g_config->use_fullscreen = false;
267 } else if(arg == "--geometry" || arg == "-g") {
271 print_usage(argv[0]);
272 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
277 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
279 print_usage(argv[0]);
280 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
284 g_config->window_width = width;
285 g_config->window_height = height;
287 g_config->fullscreen_width = width;
288 g_config->fullscreen_height = height;
291 } else if(arg == "--aspect" || arg == "-a") {
295 print_usage(argv[0]);
296 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
300 int aspect_width = 0;
301 int aspect_height = 0;
302 if (strcmp(argv[i], "auto") == 0)
307 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
309 print_usage(argv[0]);
310 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
314 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
315 static_cast<double>(g_config->aspect_height);
317 // use aspect ratio to calculate logical resolution
318 if (aspect_ratio > 1) {
319 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
320 g_config->aspect_height = 600;
322 g_config->aspect_width = 600;
323 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
327 } else if(arg == "--renderer") {
331 print_usage(argv[0]);
332 throw std::runtime_error("Need to specify a renderer for renderer argument");
336 g_config->video = get_video_system(argv[i]);
338 } else if(arg == "--show-fps") {
339 g_config->show_fps = true;
340 } else if(arg == "--no-show-fps") {
341 g_config->show_fps = false;
342 } else if(arg == "--console") {
343 g_config->console_enabled = true;
344 } else if(arg == "--noconsole") {
345 g_config->console_enabled = false;
346 } else if(arg == "--disable-sfx") {
347 g_config->sound_enabled = false;
348 } else if(arg == "--disable-music") {
349 g_config->music_enabled = false;
350 } else if(arg == "--play-demo") {
352 print_usage(argv[0]);
353 throw std::runtime_error("Need to specify a demo filename");
355 g_config->start_demo = argv[++i];
356 } else if(arg == "--record-demo") {
358 print_usage(argv[0]);
359 throw std::runtime_error("Need to specify a demo filename");
361 g_config->record_demo = argv[++i];
362 } else if(arg == "--debug-scripts" || arg == "-s") {
363 g_config->enable_script_debugger = true;
364 } else if(arg[0] != '-') {
365 g_config->start_level = arg;
367 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
375 static void init_sdl()
377 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
378 std::stringstream msg;
379 msg << "Couldn't initialize SDL: " << SDL_GetError();
380 throw std::runtime_error(msg.str());
385 SDL_EnableUNICODE(1);
387 // wait 100ms and clear SDL event queue because sometimes we have random
388 // joystick events in the queue on startup...
391 while(SDL_PollEvent(&dummy))
395 static void init_rand()
397 g_config->random_seed = systemRandom.srand(g_config->random_seed);
399 //const char *how = config->random_seed? ", user fixed.": ", from time().";
400 //log_info << "Using random seed " << config->random_seed << how << std::endl;
405 // FIXME: Add something here
409 context_pointer->init_renderer();
410 g_screen = SDL_GetVideoSurface();
412 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
416 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
418 const char* icon_fname = "images/engine/icons/supertux.xpm";
422 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
423 } catch (const std::runtime_error& err) {
425 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
428 SDL_WM_SetIcon(icon, 0);
429 SDL_FreeSurface(icon);
433 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
439 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
440 << " Window: " << g_config->window_width << "x" << g_config->window_height
441 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
442 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
445 static void init_audio()
447 sound_manager = new SoundManager();
449 sound_manager->enable_sound(g_config->sound_enabled);
450 sound_manager->enable_music(g_config->music_enabled);
453 static void quit_audio()
455 if(sound_manager != NULL) {
456 delete sound_manager;
457 sound_manager = NULL;
461 void wait_for_event(float min_delay, float max_delay)
463 assert(min_delay <= max_delay);
465 Uint32 min = (Uint32) (min_delay * 1000);
466 Uint32 max = (Uint32) (max_delay * 1000);
468 Uint32 ticks = SDL_GetTicks();
469 while(SDL_GetTicks() - ticks < min) {
471 sound_manager->update();
476 while (SDL_PollEvent(&event))
480 bool running = false;
481 ticks = SDL_GetTicks();
483 while(SDL_PollEvent(&event)) {
489 case SDL_JOYBUTTONDOWN:
490 case SDL_MOUSEBUTTONDOWN:
494 if(SDL_GetTicks() - ticks >= (max - min))
496 sound_manager->update();
502 static Uint32 last_timelog_ticks = 0;
503 static const char* last_timelog_component = 0;
505 static inline void timelog(const char* component)
507 Uint32 current_ticks = SDL_GetTicks();
509 if(last_timelog_component != 0) {
510 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
513 last_timelog_ticks = current_ticks;
514 last_timelog_component = component;
517 static inline void timelog(const char* )
522 int supertux_main(int argc, char** argv)
528 if(pre_parse_commandline(argc, argv))
531 Console::instance = new Console();
532 init_physfs(argv[0]);
535 timelog("controller");
536 g_main_controller = new JoystickKeyboardController();
542 AddonManager::get_instance().load_addons();
544 timelog("tinygettext");
547 timelog("commandline");
548 if(parse_commandline(argc, argv))
555 DrawingContext context;
556 context_pointer = &context;
559 Console::instance->init_graphics();
561 timelog("scripting");
562 Scripting::init_squirrel(g_config->enable_script_debugger);
564 timelog("resources");
569 g_main_loop = new MainLoop();
570 if(g_config->start_level != "") {
571 // we have a normal path specified at commandline, not a physfs path.
572 // So we simply mount that path here...
573 std::string dir = FileSystem::dirname(g_config->start_level);
574 log_debug << "Adding dir: " << dir << std::endl;
575 PHYSFS_addToSearchPath(dir.c_str(), true);
577 if(g_config->start_level.size() > 4 &&
578 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
580 g_main_loop->push_screen(new WorldMapNS::WorldMap(
581 FileSystem::basename(g_config->start_level)));
583 init_rand();//If level uses random eg. for
584 // rain particles before we do this:
585 std::auto_ptr<GameSession> session (
586 new GameSession(FileSystem::basename(g_config->start_level)));
588 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
589 init_rand();//initialise generator with seed from session
591 if(g_config->start_demo != "")
592 session->play_demo(g_config->start_demo);
594 if(g_config->record_demo != "")
595 session->record_demo(g_config->record_demo);
596 g_main_loop->push_screen(session.release());
600 g_main_loop->push_screen(new TitleScreen());
603 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
604 g_main_loop->run(context);
605 } catch(std::exception& e) {
606 log_fatal << "Unexpected exception: " << e.what() << std::endl;
609 log_fatal << "Unexpected exception" << std::endl;
623 delete g_main_controller;
624 g_main_controller = NULL;
625 delete Console::instance;
626 Console::instance = NULL;
627 Scripting::exit_squirrel();
628 delete texture_manager;
629 texture_manager = NULL;