4 // Copyright (C) 2005 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_mixer.h>
38 #include <SDL_image.h>
39 #include <SDL_opengl.h>
41 #include "gameconfig.hpp"
42 #include "resources.hpp"
43 #include "gettext.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "video/surface.hpp"
46 #include "video/texture_manager.hpp"
47 #include "control/joystickkeyboardcontroller.hpp"
50 #include "game_session.hpp"
51 #include "file_system.hpp"
52 #include "physfs/physfs_sdl.hpp"
54 SDL_Surface* screen = 0;
55 JoystickKeyboardController* main_controller = 0;
56 TinyGetText::DictionaryManager dictionary_manager;
58 static void init_config()
60 config = new Config();
63 } catch(std::exception& e) {
65 std::cerr << "Couldn't load config file: " << e.what() << "\n";
70 static void init_tinygettext()
72 dictionary_manager.add_directory("locale");
73 dictionary_manager.set_charset("UTF-8");
76 static void init_physfs(const char* argv0)
78 if(!PHYSFS_init(argv0)) {
79 std::stringstream msg;
80 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
81 throw std::runtime_error(msg.str());
84 // Initialize physfs (this is a slightly modified version of
85 // PHYSFS_setSaneConfig
86 const char* application = PACKAGE_NAME;
87 const char* userdir = PHYSFS_getUserDir();
88 const char* dirsep = PHYSFS_getDirSeparator();
89 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
91 // Set configuration directory
92 sprintf(writedir, "%s.%s", userdir, application);
93 if(!PHYSFS_setWriteDir(writedir)) {
94 // try to create the directory
95 char* mkdir = new char[strlen(application) + 2];
96 sprintf(mkdir, ".%s", application);
97 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
98 std::ostringstream msg;
99 msg << "Failed creating configuration directory '"
100 << writedir << "': " << PHYSFS_getLastError();
103 throw std::runtime_error(msg.str());
107 if(!PHYSFS_setWriteDir(writedir)) {
108 std::ostringstream msg;
109 msg << "Failed to use configuration directory '"
110 << writedir << "': " << PHYSFS_getLastError();
112 throw std::runtime_error(msg.str());
115 PHYSFS_addToSearchPath(writedir, 0);
118 // Search for archives and add them to the search path
119 const char* archiveExt = "zip";
120 char** rc = PHYSFS_enumerateFiles("/");
121 size_t extlen = strlen(archiveExt);
123 for(char** i = rc; *i != 0; ++i) {
124 size_t l = strlen(*i);
125 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
126 const char* ext = (*i) + (l - extlen);
127 if(strcasecmp(ext, archiveExt) == 0) {
128 const char* d = PHYSFS_getRealDir(*i);
129 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
130 sprintf(str, "%s%s%s", d, dirsep, *i);
131 PHYSFS_addToSearchPath(str, 1);
139 // when started from source dir...
140 std::string dir = PHYSFS_getBaseDir();
142 std::string testfname = dir;
143 testfname += "/credits.txt";
144 bool sourcedir = false;
145 FILE* f = fopen(testfname.c_str(), "r");
148 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
149 std::cout << "Warning: Couldn't add '" << dir
150 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
157 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
159 #ifdef ENABLE_BINRELOC
160 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
164 datadir = APPDATADIR;
166 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
167 std::cout << "Couldn't add '" << datadir
168 << "' to physfs searchpath: " << PHYSFS_getLastError() << "\n";
173 // allow symbolic links
174 PHYSFS_permitSymbolicLinks(1);
177 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
178 printf("[%s] is in the search path.\n", *i);
181 static void print_usage(const char* argv0)
183 fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
186 " -f, --fullscreen Run in fullscreen mode\n"
187 " -w, --window Run in window mode\n"
188 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
189 " --help Show this help message\n"
190 " --version Display SuperTux version and quit\n"
191 " --show-fps Display framerate in levels\n"
192 " --record-demo FILE LEVEL Record a demo to FILE\n"
193 " --play-demo FILE LEVEL Play a recorded demo\n"
197 static void parse_commandline(int argc, char** argv)
199 for(int i = 1; i < argc; ++i) {
200 std::string arg = argv[i];
202 if(arg == "--fullscreen" || arg == "-f") {
203 config->use_fullscreen = true;
204 } else if(arg == "--window" || arg == "-w") {
205 config->use_fullscreen = false;
206 } else if(arg == "--geometry" || arg == "-g") {
208 print_usage(argv[0]);
209 throw std::runtime_error("Need to specify a parameter for geometry switch");
211 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
213 print_usage(argv[0]);
214 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
216 } else if(arg == "--show-fps") {
217 config->show_fps = true;
218 } else if(arg == "--play-demo") {
220 print_usage(argv[0]);
221 throw std::runtime_error("Need to specify a demo filename");
223 config->start_demo = argv[++i];
224 } else if(arg == "--record-demo") {
226 print_usage(argv[0]);
227 throw std::runtime_error("Need to specify a demo filename");
229 config->record_demo = argv[++i];
230 } else if(arg == "--help") {
231 print_usage(argv[0]);
232 throw std::runtime_error("");
233 } else if(arg == "--version") {
234 std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
235 throw std::runtime_error("");
236 } else if(arg[0] != '-') {
237 config->start_level = arg;
239 std::cerr << "Unknown option '" << arg << "'.\n";
240 std::cerr << "Use --help to see a list of options.\n";
244 // TODO joystick switchyes...
247 static void init_sdl()
249 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
250 std::stringstream msg;
251 msg << "Couldn't initialize SDL: " << SDL_GetError();
252 throw std::runtime_error(msg.str());
255 SDL_EnableUNICODE(1);
257 // wait 100ms and clear SDL event queue because sometimes we have random
258 // joystick events in the queue on startup...
261 while(SDL_PollEvent(&dummy))
265 static void check_gl_error()
267 GLenum glerror = glGetError();
268 std::string errormsg;
270 if(glerror != GL_NO_ERROR) {
272 case GL_INVALID_ENUM:
273 errormsg = "Invalid enumeration value";
275 case GL_INVALID_VALUE:
276 errormsg = "Numeric argzment out of range";
278 case GL_INVALID_OPERATION:
279 errormsg = "Invalid operation";
281 case GL_STACK_OVERFLOW:
282 errormsg = "stack overflow";
284 case GL_STACK_UNDERFLOW:
285 errormsg = "stack underflow";
287 case GL_OUT_OF_MEMORY:
288 errormsg = "out of memory";
290 case GL_TABLE_TOO_LARGE:
291 errormsg = "table too large";
294 errormsg = "unknown error number";
297 std::stringstream msg;
298 msg << "OpenGL Error: " << errormsg;
299 throw std::runtime_error(msg.str());
305 if(texture_manager != NULL)
306 texture_manager->save_textures();
308 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
309 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
310 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
311 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
313 int flags = SDL_OPENGL;
314 if(config->use_fullscreen)
315 flags |= SDL_FULLSCREEN;
316 int width = config->screenwidth;
317 int height = config->screenheight;
320 screen = SDL_SetVideoMode(width, height, bpp, flags);
322 std::stringstream msg;
323 msg << "Couldn't set video mode (" << width << "x" << height
324 << "-" << bpp << "bpp): " << SDL_GetError();
325 throw std::runtime_error(msg.str());
328 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
331 SDL_Surface* icon = IMG_Load_RW(
332 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
334 SDL_WM_SetIcon(icon, 0);
335 SDL_FreeSurface(icon);
339 std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
343 // setup opengl state and transform
344 glDisable(GL_DEPTH_TEST);
345 glDisable(GL_CULL_FACE);
346 glEnable(GL_TEXTURE_2D);
348 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
350 glViewport(0, 0, screen->w, screen->h);
351 glMatrixMode(GL_PROJECTION);
353 // logical resolution here not real monitor resolution
354 glOrtho(0, 800, 600, 0, -1.0, 1.0);
355 glMatrixMode(GL_MODELVIEW);
357 glTranslatef(0, 0, 0);
361 if(texture_manager != NULL)
362 texture_manager->reload_textures();
364 texture_manager = new TextureManager();
367 static void init_audio()
369 sound_manager = new SoundManager();
371 sound_manager->enable_sound(config->sound_enabled);
372 sound_manager->enable_music(config->music_enabled);
375 static void quit_audio()
378 delete sound_manager;
383 void wait_for_event(float min_delay, float max_delay)
385 assert(min_delay <= max_delay);
387 Uint32 min = (Uint32) (min_delay * 1000);
388 Uint32 max = (Uint32) (max_delay * 1000);
390 Uint32 ticks = SDL_GetTicks();
391 while(SDL_GetTicks() - ticks < min) {
393 sound_manager->update();
398 while (SDL_PollEvent(&event))
402 bool running = false;
403 ticks = SDL_GetTicks();
405 while(SDL_PollEvent(&event)) {
408 throw std::runtime_error("received window close");
410 case SDL_JOYBUTTONDOWN:
411 case SDL_MOUSEBUTTONDOWN:
415 if(SDL_GetTicks() - ticks >= (max - min))
417 sound_manager->update();
422 int main(int argc, char** argv)
426 init_physfs(argv[0]);
428 main_controller = new JoystickKeyboardController();
431 parse_commandline(argc, argv);
437 if(config->start_level != "") {
438 // we have a normal path specified at commandline not physfs paths.
439 // So we simply mount that path here...
440 std::string dir = FileSystem::dirname(config->start_level);
441 PHYSFS_addToSearchPath(dir.c_str(), true);
443 FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
444 if(config->start_demo != "")
445 session.play_demo(config->start_demo);
446 if(config->record_demo != "")
447 session.record_demo(config->record_demo);
453 } catch(std::exception& e) {
454 std::cerr << "Unexpected exception: " << e.what() << std::endl;
457 std::cerr << "Unexpected exception." << std::endl;
468 delete main_controller;
469 delete texture_manager;