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>
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
43 #include "gameconfig.hpp"
44 #include "resources.hpp"
45 #include "gettext.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "video/surface.hpp"
48 #include "video/texture_manager.hpp"
49 #include "video/drawing_context.hpp"
50 #include "video/glutil.hpp"
51 #include "control/joystickkeyboardcontroller.hpp"
52 #include "options_menu.hpp"
53 #include "mainloop.hpp"
55 #include "game_session.hpp"
56 #include "scripting/level.hpp"
57 #include "scripting/squirrel_util.hpp"
58 #include "file_system.hpp"
59 #include "physfs/physfs_sdl.hpp"
60 #include "random_generator.hpp"
61 #include "worldmap/worldmap.hpp"
62 #include "binreloc/binreloc.h"
64 namespace { DrawingContext *context_pointer; }
66 JoystickKeyboardController* main_controller = 0;
67 TinyGetText::DictionaryManager dictionary_manager;
72 static void init_config()
74 config = new Config();
77 } catch(std::exception& e) {
78 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
82 static void init_tinygettext()
84 dictionary_manager.add_directory("locale");
85 dictionary_manager.set_charset("UTF-8");
87 // Config setting "locale" overrides language detection
88 if (config->locale != "") {
89 dictionary_manager.set_language( config->locale );
93 static void init_physfs(const char* argv0)
95 if(!PHYSFS_init(argv0)) {
96 std::stringstream msg;
97 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
98 throw std::runtime_error(msg.str());
101 // Initialize physfs (this is a slightly modified version of
102 // PHYSFS_setSaneConfig
103 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
104 const char* userdir = PHYSFS_getUserDir();
105 const char* dirsep = PHYSFS_getDirSeparator();
106 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
108 // Set configuration directory
109 sprintf(writedir, "%s.%s", userdir, application);
110 if(!PHYSFS_setWriteDir(writedir)) {
111 // try to create the directory
112 char* mkdir = new char[strlen(application) + 2];
113 sprintf(mkdir, ".%s", application);
114 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
115 std::ostringstream msg;
116 msg << "Failed creating configuration directory '"
117 << writedir << "': " << PHYSFS_getLastError();
120 throw std::runtime_error(msg.str());
124 if(!PHYSFS_setWriteDir(writedir)) {
125 std::ostringstream msg;
126 msg << "Failed to use configuration directory '"
127 << writedir << "': " << PHYSFS_getLastError();
129 throw std::runtime_error(msg.str());
132 PHYSFS_addToSearchPath(writedir, 0);
135 // Search for archives and add them to the search path
136 const char* archiveExt = "zip";
137 char** rc = PHYSFS_enumerateFiles("/");
138 size_t extlen = strlen(archiveExt);
140 for(char** i = rc; *i != 0; ++i) {
141 size_t l = strlen(*i);
142 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
143 const char* ext = (*i) + (l - extlen);
144 if(strcasecmp(ext, archiveExt) == 0) {
145 const char* d = PHYSFS_getRealDir(*i);
146 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
147 sprintf(str, "%s%s%s", d, dirsep, *i);
148 PHYSFS_addToSearchPath(str, 1);
156 // when started from source dir...
157 std::string dir = PHYSFS_getBaseDir();
159 std::string testfname = dir;
160 testfname += "/credits.txt";
161 bool sourcedir = false;
162 FILE* f = fopen(testfname.c_str(), "r");
165 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
166 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
174 using namespace supertux_apple;
176 // when started from Application file on Mac OS X...
178 CFBundleRef mainBundle = CFBundleGetMainBundle();
179 assert(mainBundle != 0);
180 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
181 assert(mainBundleURL != 0);
182 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
183 assert(pathStr != 0);
184 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
185 CFRelease(mainBundleURL);
188 dir = std::string(path) + "/Contents/Resources/data";
189 testfname = dir + "/credits.txt";
191 f = fopen(testfname.c_str(), "r");
194 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
195 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
204 PHYSFS_addToSearchPath(".\\data", 1);
208 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
210 #ifdef ENABLE_BINRELOC
214 dir = br_find_data_dir(APPDATADIR);
219 datadir = APPDATADIR;
221 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
222 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
227 // allow symbolic links
228 PHYSFS_permitSymbolicLinks(1);
231 char** searchpath = PHYSFS_getSearchPath();
232 for(char** i = searchpath; *i != NULL; i++)
233 log_info << "[" << *i << "] is in the search path" << std::endl;
234 PHYSFS_freeList(searchpath);
237 static void print_usage(const char* argv0)
239 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
242 " -f, --fullscreen Run in fullscreen mode\n"
243 " -w, --window Run in window mode\n"
244 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
245 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
246 " --disable-sfx Disable sound effects\n"
247 " --disable-music Disable music\n"
248 " --help Show this help message\n"
249 " --version Display SuperTux version and quit\n"
250 " --console Enable ingame scripting console\n"
251 " --noconsole Disable ingame scripting console\n"
252 " --show-fps Display framerate in levels\n"
253 " --no-show-fps Do not display framerate in levels\n"
254 " --record-demo FILE LEVEL Record a demo to FILE\n"
255 " --play-demo FILE LEVEL Play a recorded demo\n"
260 * Options that should be evaluated prior to any initializations at all go here
262 static bool pre_parse_commandline(int argc, char** argv)
264 for(int i = 1; i < argc; ++i) {
265 std::string arg = argv[i];
267 if(arg == "--version") {
268 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
277 * Options that should be evaluated after config is read go here
279 static bool parse_commandline(int argc, char** argv)
281 for(int i = 1; i < argc; ++i) {
282 std::string arg = argv[i];
284 if(arg == "--help") {
285 print_usage(argv[0]);
287 } else if(arg == "--fullscreen" || arg == "-f") {
288 config->use_fullscreen = true;
289 } else if(arg == "--window" || arg == "-w") {
290 config->use_fullscreen = false;
291 } else if(arg == "--geometry" || arg == "-g") {
293 print_usage(argv[0]);
294 throw std::runtime_error("Need to specify a parameter for geometry switch");
296 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
298 print_usage(argv[0]);
299 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
301 } else if(arg == "--aspect" || arg == "-a") {
303 print_usage(argv[0]);
304 throw std::runtime_error("Need to specify a parameter for aspect switch");
306 if(strcasecmp(argv[i+1], "auto") == 0) {
308 config->aspect_ratio = -1;
310 int aspect_width, aspect_height;
311 if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
312 print_usage(argv[0]);
313 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
315 config->aspect_ratio = static_cast<double>(aspect_width) /
316 static_cast<double>(aspect_height);
318 } else if(arg == "--show-fps") {
319 config->show_fps = true;
320 } else if(arg == "--no-show-fps") {
321 config->show_fps = false;
322 } else if(arg == "--console") {
323 config->console_enabled = true;
324 } else if(arg == "--noconsole") {
325 config->console_enabled = false;
326 } else if(arg == "--disable-sfx") {
327 config->sound_enabled = false;
328 } else if(arg == "--disable-music") {
329 config->music_enabled = false;
330 } else if(arg == "--play-demo") {
332 print_usage(argv[0]);
333 throw std::runtime_error("Need to specify a demo filename");
335 config->start_demo = argv[++i];
336 } else if(arg == "--record-demo") {
338 print_usage(argv[0]);
339 throw std::runtime_error("Need to specify a demo filename");
341 config->record_demo = argv[++i];
342 } else if(arg == "-d") {
343 config->enable_script_debugger = true;
344 } else if(arg[0] != '-') {
345 config->start_level = arg;
347 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
355 static void init_sdl()
357 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
358 std::stringstream msg;
359 msg << "Couldn't initialize SDL: " << SDL_GetError();
360 throw std::runtime_error(msg.str());
365 SDL_EnableUNICODE(1);
367 // wait 100ms and clear SDL event queue because sometimes we have random
368 // joystick events in the queue on startup...
371 while(SDL_PollEvent(&dummy))
375 static void init_rand()
377 config->random_seed = systemRandom.srand(config->random_seed);
379 //const char *how = config->random_seed? ", user fixed.": ", from time().";
380 //log_info << "Using random seed " << config->random_seed << how << std::endl;
385 static int desktop_width = 0;
386 static int desktop_height = 0;
388 /* unfortunately only newer SDLs have these infos */
389 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
390 /* find which resolution the user normally uses */
391 if(desktop_width == 0) {
392 const SDL_VideoInfo *info = SDL_GetVideoInfo();
393 desktop_width = info->current_w;
394 desktop_height = info->current_h;
398 double aspect_ratio = config->aspect_ratio;
400 // try to guess aspect ratio of monitor if needed
401 if (aspect_ratio <= 0) {
402 // TODO: commented out because
403 // 1) it tends to guess wrong if widescreen-monitors don't stretch 800x600 to fit, but just display black borders
404 // 2) aspect ratios other than 4:3 are largely untested
406 if(config->use_fullscreen && desktop_width > 0) {
407 aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
410 aspect_ratio = 4.0 / 3.0;
416 // use aspect ratio to calculate logical resolution
417 if (aspect_ratio > 1) {
418 SCREEN_WIDTH = static_cast<int> (600 * aspect_ratio + 0.5);
422 SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
425 context_pointer->init_renderer();
426 screen = SDL_GetVideoSurface();
428 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
432 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
434 const char* icon_fname = "images/engine/icons/supertux.xpm";
436 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
438 SDL_WM_SetIcon(icon, 0);
439 SDL_FreeSurface(icon);
443 log_warning << "Couldn't find icon '" << icon_fname << "'" << std::endl;
449 log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
452 static void init_audio()
454 sound_manager = new SoundManager();
456 sound_manager->enable_sound(config->sound_enabled);
457 sound_manager->enable_music(config->music_enabled);
460 static void quit_audio()
462 if(sound_manager != NULL) {
463 delete sound_manager;
464 sound_manager = NULL;
468 void wait_for_event(float min_delay, float max_delay)
470 assert(min_delay <= max_delay);
472 Uint32 min = (Uint32) (min_delay * 1000);
473 Uint32 max = (Uint32) (max_delay * 1000);
475 Uint32 ticks = SDL_GetTicks();
476 while(SDL_GetTicks() - ticks < min) {
478 sound_manager->update();
483 while (SDL_PollEvent(&event))
487 bool running = false;
488 ticks = SDL_GetTicks();
490 while(SDL_PollEvent(&event)) {
496 case SDL_JOYBUTTONDOWN:
497 case SDL_MOUSEBUTTONDOWN:
501 if(SDL_GetTicks() - ticks >= (max - min))
503 sound_manager->update();
509 static Uint32 last_timelog_ticks = 0;
510 static const char* last_timelog_component = 0;
512 static inline void timelog(const char* component)
514 Uint32 current_ticks = SDL_GetTicks();
516 if(last_timelog_component != 0) {
517 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
520 last_timelog_ticks = current_ticks;
521 last_timelog_component = component;
524 static inline void timelog(const char* )
529 int main(int argc, char** argv)
537 if(pre_parse_commandline(argc, argv))
540 Console::instance = new Console();
541 init_physfs(argv[0]);
544 timelog("controller");
545 main_controller = new JoystickKeyboardController();
548 timelog("tinygettext");
550 timelog("commandline");
551 if(parse_commandline(argc, argv))
556 DrawingContext context;
557 context_pointer = &context;
559 Console::instance->init_graphics();
560 timelog("scripting");
561 Scripting::init_squirrel(config->enable_script_debugger);
562 timelog("resources");
566 main_loop = new MainLoop();
567 if(config->start_level != "") {
568 // we have a normal path specified at commandline not physfs paths.
569 // So we simply mount that path here...
570 std::string dir = FileSystem::dirname(config->start_level);
571 PHYSFS_addToSearchPath(dir.c_str(), true);
573 if(config->start_level.size() > 4 &&
574 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
576 main_loop->push_screen(new WorldMapNS::WorldMap(
577 FileSystem::basename(config->start_level)));
579 init_rand();//If level uses random eg. for
580 // rain particles before we do this:
581 std::auto_ptr<GameSession> session (
582 new GameSession(FileSystem::basename(config->start_level)));
584 config->random_seed =session->get_demo_random_seed(config->start_demo);
585 init_rand();//initialise generator with seed from session
587 if(config->start_demo != "")
588 session->play_demo(config->start_demo);
590 if(config->record_demo != "")
591 session->record_demo(config->record_demo);
592 main_loop->push_screen(session.release());
596 main_loop->push_screen(new TitleScreen());
599 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
600 main_loop->run(context);
602 } catch(std::exception& e) {
603 log_fatal << "Unexpected exception: " << e.what() << std::endl;
606 log_fatal << "Unexpected exception" << std::endl;
621 delete main_controller;
622 main_controller = NULL;
623 delete Console::instance;
624 Console::instance = NULL;
625 Scripting::exit_squirrel();
626 delete texture_manager;
627 texture_manager = NULL;