2 Copyright (C) 2003, 2010 - Wolfire Games
4 This file is part of Lugaru.
6 Lugaru 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.
15 See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
40 #define INT32 INT32_jpeg
50 static bool load_image(const char * fname, TGAImageRec & tex);
51 static bool load_png(const char * fname, TGAImageRec & tex);
52 static bool load_jpg(const char * fname, TGAImageRec & tex);
53 bool save_image(const char * fname);
54 static bool save_png(const char * fname);
57 #include "openal_wrapper.h"
59 extern float multiplier;
61 extern float realmultiplier;
63 extern bool cellophane;
64 extern float texdetail;
68 extern bool stillloading;
73 extern float slomospeed;
74 extern float slomofreq;
84 #include "MacCompatibility.h"
89 #include "win-res/resource.h"
92 extern SDL_Window *sdlwindow;
96 SDL_Rect **resolutions = NULL;
103 // statics/globals (internal only) ------------------------------------------
106 #pragma warning(push)
107 #pragma warning(disable: 4273)
110 #define GL_FUNC(ret,fn,params,call,rt) \
112 static ret (GLAPIENTRY *p##fn) params = NULL; \
113 ret GLAPIENTRY fn params { rt p##fn call; } \
122 static bool lookup_glsym(const char *funcname, void **func)
124 *func = SDL_GL_GetProcAddress(funcname);
126 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
132 static bool lookup_all_glsyms(void)
135 #define GL_FUNC(ret,fn,params,call,rt) \
136 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
142 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
150 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
157 Boolean gDone = false;
159 static int _argc = 0;
160 static char **_argv = NULL;
162 bool cmdline(const char *cmd)
164 for (int i = 1; i < _argc; i++) {
165 char *arg = _argv[i];
168 if (strcasecmp(arg, cmd) == 0)
175 //-----------------------------------------------------------------------------------------------------------------------
181 glClear( GL_COLOR_BUFFER_BIT );
185 glDisable( GL_ALPHA_TEST);
186 glDisable( GL_BLEND);
187 glDisable( GL_DEPTH_TEST);
188 //glDisable( GL_DITHER);
190 glDisable( GL_LIGHTING);
191 glDisable( GL_LOGIC_OP);
192 glDisable( GL_TEXTURE_1D);
193 glDisable( GL_TEXTURE_2D);
194 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
195 glPixelTransferi( GL_RED_SCALE, 1);
196 glPixelTransferi( GL_RED_BIAS, 0);
197 glPixelTransferi( GL_GREEN_SCALE, 1);
198 glPixelTransferi( GL_GREEN_BIAS, 0);
199 glPixelTransferi( GL_BLUE_SCALE, 1);
200 glPixelTransferi( GL_BLUE_BIAS, 0);
201 glPixelTransferi( GL_ALPHA_SCALE, 1);
202 glPixelTransferi( GL_ALPHA_BIAS, 0);
204 // set initial rendering states
205 glShadeModel( GL_SMOOTH);
207 glDepthFunc( GL_LEQUAL);
208 glDepthMask( GL_TRUE);
209 //glDepthRange( FRONT_CLIP, BACK_CLIP);
210 glEnable( GL_DEPTH_TEST);
211 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
212 glCullFace( GL_FRONT);
213 glEnable( GL_CULL_FACE);
214 glEnable( GL_LIGHTING);
215 //glEnable( GL_LIGHT_MODEL_AMBIENT);
216 glEnable( GL_DITHER);
217 glEnable( GL_COLOR_MATERIAL);
218 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
219 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
220 glAlphaFunc( GL_GREATER, 0.5f);
222 if ( CanInitStereo(stereomode) ) {
223 InitStereo(stereomode);
225 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
226 stereomode = stereoNone;
230 static void toggleFullscreen()
232 Uint32 flags = SDL_GetWindowFlags(sdlwindow);
233 if (flags & SDL_WINDOW_FULLSCREEN) {
234 flags &= ~SDL_WINDOW_FULLSCREEN;
236 flags |= SDL_WINDOW_FULLSCREEN;
238 SDL_SetWindowFullscreen(sdlwindow, flags);
241 static SDL_bool sdlEventProc(const SDL_Event &e)
247 case SDL_WINDOWEVENT:
248 if (e.window.event == SDL_WINDOWEVENT_CLOSE) {
253 case SDL_MOUSEMOTION:
254 deltah += e.motion.xrel;
255 deltav += e.motion.yrel;
259 if ((e.key.keysym.scancode == SDL_SCANCODE_G) &&
260 (e.key.keysym.mod & KMOD_CTRL)) {
261 SDL_bool mode = SDL_TRUE;
262 if ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_FULLSCREEN) == 0)
263 mode = (SDL_GetWindowGrab(sdlwindow) ? SDL_FALSE : SDL_TRUE);
264 SDL_SetWindowGrab(sdlwindow, mode);
265 SDL_SetRelativeMouseMode(mode);
266 } else if ( (e.key.keysym.scancode == SDL_SCANCODE_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
276 // --------------------------------------------------------------------------
278 static Point gMidPoint;
294 const int displayIdx = 0; // !!! FIXME: other monitors?
296 if (!SDL_WasInit(SDL_INIT_VIDEO))
297 if (SDL_Init(SDL_INIT_VIDEO) == -1) {
298 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
301 if (!LoadSettings()) {
302 fprintf(stderr, "Failed to load config, creating default\n");
305 if (kBitsPerPixel != 32 && kBitsPerPixel != 16) {
309 if (SDL_GL_LoadLibrary(NULL) == -1) {
310 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
316 const int nummodes = SDL_GetNumDisplayModes(displayIdx);
317 for (int i = 0; i < nummodes; i++)
319 SDL_DisplayMode mode;
320 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
322 if ((mode.w < 640) || (mode.h < 480))
323 continue; // sane lower limit.
328 const std::string error = "No suitable video resolutions found.";
329 cerr << error << endl;
330 SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Lugaru init failed!", error.c_str(), NULL);
335 static SDL_Rect *resolutions_block = NULL;
336 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
337 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
338 if ((resolutions_block == NULL) || (resolutions == NULL)) {
340 fprintf(stderr, "Out of memory!\n");
344 resolutions[count--] = NULL;
345 for (int i = 0; count >= 0; i++, count--) {
346 /* FIXME - Pretty sure this should use nummodes and not count */
347 SDL_DisplayMode mode;
348 if (SDL_GetDisplayMode(displayIdx, i, &mode) == -1)
350 if ((mode.w < 640) || (mode.h < 480))
351 continue; // sane lower limit.
352 resolutions_block[count].x = resolutions_block[count].y = 0;
353 resolutions_block[count].w = mode.w;
354 resolutions_block[count].h = mode.h;
355 resolutions[count] = &resolutions_block[count];
358 if (cmdline("showresolutions")) {
359 printf("Resolutions we think are okay:\n");
360 for (int i = 0; resolutions[i]; i++)
361 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
364 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
365 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
367 Uint32 sdlflags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
368 if (!cmdline("windowed"))
369 sdlflags |= SDL_WINDOW_FULLSCREEN;
370 if (!cmdline("nomousegrab"))
371 sdlflags |= SDL_WINDOW_INPUT_GRABBED;
373 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
374 kContextWidth, kContextHeight, sdlflags);
377 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
378 fprintf(stderr, "forcing 640x480...\n");
380 kContextHeight = 480;
381 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
382 kContextWidth, kContextHeight, sdlflags);
384 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
385 fprintf(stderr, "forcing 640x480 windowed mode...\n");
386 sdlflags &= ~SDL_WINDOW_FULLSCREEN;
387 sdlwindow = SDL_CreateWindow("Lugaru", SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIdx),
388 kContextWidth, kContextHeight, sdlflags);
391 fprintf(stderr, "SDL_CreateWindow() failed: %s\n", SDL_GetError());
397 SDL_GLContext glctx = SDL_GL_CreateContext(sdlwindow);
399 fprintf(stderr, "SDL_GL_CreateContext() failed: %s\n", SDL_GetError());
404 SDL_GL_MakeCurrent(sdlwindow, glctx);
406 if (!lookup_all_glsyms()) {
407 fprintf(stderr, "Missing required OpenGL functions.\n");
413 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
415 fprintf(stderr, "Failed to get a double-buffered context.\n");
420 if (SDL_GL_SetSwapInterval(-1) == -1) // try swap_tear first.
421 SDL_GL_SetSwapInterval(1);
424 SDL_SetWindowGrab(sdlwindow, SDL_TRUE);
425 SDL_SetRelativeMouseMode(SDL_TRUE);
430 GLint width = kContextWidth;
431 GLint height = kContextHeight;
432 gMidPoint.h = width / 2;
433 gMidPoint.v = height / 2;
435 screenheight = height;
438 newscreenwidth = screenwidth;
439 newscreenheight = screenheight;
447 static void DoMouse()
450 if (mainmenu || ( (abs(deltah) < 10 * realmultiplier * 1000) && (abs(deltav) < 10 * realmultiplier * 1000) )) {
451 deltah *= usermousesensitivity;
452 deltav *= usermousesensitivity;
453 mousecoordh += deltah;
454 mousecoordv += deltav;
457 else if (mousecoordh >= kContextWidth)
458 mousecoordh = kContextWidth - 1;
461 else if (mousecoordv >= kContextHeight)
462 mousecoordv = kContextHeight - 1;
467 void DoFrameRate (int update)
469 static long frames = 0;
471 static AbsoluteTime time = {0, 0};
472 static AbsoluteTime frametime = {0, 0};
473 AbsoluteTime currTime = UpTime ();
474 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
476 if (0 > deltaTime) // if negative microseconds
477 deltaTime /= -1000000.0;
478 else // else milliseconds
481 multiplier = deltaTime;
482 if (multiplier < .001)
487 frametime = currTime; // reset for next time interval
489 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
491 if (0 > deltaTime) // if negative microseconds
492 deltaTime /= -1000000.0;
493 else // else milliseconds
496 if (0.001 <= deltaTime) { // has update interval passed
498 time = currTime; // reset for next time interval
507 static float sps = 200;
509 static float oldmult;
515 fps = 1 / multiplier;
517 count = multiplier * sps;
521 realmultiplier = multiplier;
522 multiplier *= gamespeed;
529 multiplier *= .00001;
530 if (slomo && !mainmenu)
531 multiplier *= slomospeed;
532 oldmult = multiplier;
533 multiplier /= (float)count;
539 for (int i = 0; i < count; i++) {
542 multiplier = oldmult;
545 /* - Debug code to test how many channels were active on average per frame
546 static long frames = 0;
548 static AbsoluteTime start = {0,0};
549 AbsoluteTime currTime = UpTime ();
550 static int num_channels = 0;
552 num_channels += OPENAL_GetChannelsPlaying();
553 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
555 if (0 > deltaTime) // if negative microseconds
556 deltaTime /= -1000000.0;
557 else // else milliseconds
565 float avg_channels = (float)num_channels / (float)frames;
567 ofstream opstream("log.txt",ios::app);
568 opstream << "Average frame count: ";
570 opstream << " frames - ";
571 opstream << avg_channels;
572 opstream << " per frame.\n";
579 if ( stereomode == stereoNone ) {
580 DrawGLScene(stereoCenter);
582 DrawGLScene(stereoLeft);
583 DrawGLScene(stereoRight);
587 // --------------------------------------------------------------------------
595 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
598 // cheat here...static destructors are calling glDeleteTexture() after
599 // the context is destroyed and libGL unloaded by SDL_Quit().
600 pglDeleteTextures = glDeleteTextures_doNothing;
604 // --------------------------------------------------------------------------
606 static bool IsFocused()
608 return ((SDL_GetWindowFlags(sdlwindow) & SDL_WINDOW_INPUT_FOCUS) != 0);
614 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
615 static char *findBinaryInPath(const char *bin, char *envr)
617 size_t alloc_size = 0;
624 ptr = strchr(start, ':'); /* find next $PATH separator. */
628 size = strlen(start) + strlen(bin) + 2;
629 if (size > alloc_size) {
630 char *x = (char *) realloc(exe, size);
641 /* build full binary path... */
643 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
647 if (access(exe, X_OK) == 0) { /* Exists as executable? We're done. */
648 strcpy(exe, start); /* i'm lazy. piss off. */
652 start = ptr + 1; /* start points to beginning of next element. */
653 } while (ptr != NULL);
658 return(NULL); /* doesn't exist in path. */
659 } /* findBinaryInPath */
662 char *calcBaseDir(const char *argv0)
664 /* If there isn't a path on argv0, then look through the $PATH for it. */
668 const char *ptr = strrchr((char *)argv0, '/');
669 if (strchr(argv0, '/')) {
670 retval = strdup(argv0);
672 *((char *) strrchr(retval, '/')) = '\0';
676 envr = getenv("PATH");
682 retval = findBinaryInPath(argv0, envr);
687 static inline void chdirToAppPath(const char *argv0)
689 char *dir = calcBaseDir(argv0);
691 #if (defined(__APPLE__) && defined(__MACH__))
692 // Chop off /Contents/MacOS if it's at the end of the string, so we
693 // land in the base of the app bundle.
694 const size_t len = strlen(dir);
695 const char *bundledirs = "/Contents/MacOS";
696 const size_t bundledirslen = strlen(bundledirs);
697 if (len > bundledirslen) {
698 char *ptr = (dir + len) - bundledirslen;
699 if (strcasecmp(ptr, bundledirs) == 0)
710 int main(int argc, char **argv)
715 // !!! FIXME: we could use a Win32 API for this. --ryan.
717 chdirToAppPath(argv[0]);
726 //ofstream os("error.txt");
728 //ofstream os("log.txt");
734 while (!gDone && !tryquit) {
738 // check windows messages
745 while ( SDL_PollEvent( &e ) ) {
746 if (!sdlEventProc(e)) {
757 // allow game chance to pause
762 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
773 } catch (const std::exception& error) {
776 std::string e = "Caught exception: ";
781 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
791 // --------------------------------------------------------------------------
794 bool LoadImage(const char * fname, TGAImageRec & tex)
796 if ( tex.data == NULL )
799 return load_image(fname, tex);
802 void ScreenShot(const char * fname)
809 static bool load_image(const char *file_name, TGAImageRec &tex)
811 const char *ptr = strrchr((char *)file_name, '.');
813 if (strcasecmp(ptr + 1, "png") == 0)
814 return load_png(file_name, tex);
815 else if (strcasecmp(ptr + 1, "jpg") == 0)
816 return load_jpg(file_name, tex);
819 STUBBED("Unsupported image type");
824 struct my_error_mgr {
825 struct jpeg_error_mgr pub; /* "public" fields */
826 jmp_buf setjmp_buffer; /* for return to caller */
828 typedef struct my_error_mgr * my_error_ptr;
831 static void my_error_exit(j_common_ptr cinfo)
833 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
834 longjmp(err->setjmp_buffer, 1);
837 /* stolen from public domain example.c code in libjpg distribution. */
838 static bool load_jpg(const char *file_name, TGAImageRec &tex)
840 struct jpeg_decompress_struct cinfo;
841 struct my_error_mgr jerr;
842 JSAMPROW buffer[1]; /* Output row buffer */
843 int row_stride; /* physical row width in output buffer */
844 FILE *infile = fopen(file_name, "rb");
849 cinfo.err = jpeg_std_error(&jerr.pub);
850 jerr.pub.error_exit = my_error_exit;
851 if (setjmp(jerr.setjmp_buffer)) {
852 jpeg_destroy_decompress(&cinfo);
857 jpeg_create_decompress(&cinfo);
858 jpeg_stdio_src(&cinfo, infile);
859 (void) jpeg_read_header(&cinfo, TRUE);
861 cinfo.out_color_space = JCS_RGB;
862 cinfo.quantize_colors = 0;
863 (void) jpeg_calc_output_dimensions(&cinfo);
864 (void) jpeg_start_decompress(&cinfo);
866 row_stride = cinfo.output_width * cinfo.output_components;
867 tex.sizeX = cinfo.output_width;
868 tex.sizeY = cinfo.output_height;
871 while (cinfo.output_scanline < cinfo.output_height) {
872 buffer[0] = (JSAMPROW)(char *)tex.data +
873 ((cinfo.output_height - 1) - cinfo.output_scanline) * row_stride;
874 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
877 (void) jpeg_finish_decompress(&cinfo);
878 jpeg_destroy_decompress(&cinfo);
885 /* stolen from public domain example.c code in libpng distribution. */
886 static bool load_png(const char *file_name, TGAImageRec &tex)
888 bool hasalpha = false;
889 png_structp png_ptr = NULL;
890 png_infop info_ptr = NULL;
891 png_uint_32 width, height;
892 int bit_depth, color_type, interlace_type;
893 png_byte **rows = NULL;
895 png_byte **row_pointers = NULL;
896 FILE *fp = fopen(file_name, "rb");
899 cerr << file_name << " not found" << endl;
903 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
907 info_ptr = png_create_info_struct(png_ptr);
908 if (info_ptr == NULL)
911 if (setjmp(png_jmpbuf(png_ptr)))
914 png_init_io(png_ptr, fp);
915 png_read_png(png_ptr, info_ptr,
916 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
918 png_get_IHDR(png_ptr, info_ptr, &width, &height,
919 &bit_depth, &color_type, &interlace_type, NULL, NULL);
921 if (bit_depth != 8) // transform SHOULD handle this...
924 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
927 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
930 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
931 row_pointers = png_get_rows(png_ptr, info_ptr);
936 png_byte *dst = tex.data;
937 for (int i = height - 1; i >= 0; i--) {
938 png_byte *src = row_pointers[i];
939 for (int j = 0; j < width; j++) {
951 png_byte *dst = tex.data;
952 int pitch = width * 4;
953 for (int i = height - 1; i >= 0; i--, dst += pitch)
954 memcpy(dst, row_pointers[i], pitch);
964 cerr << "There was a problem loading " << file_name << endl;
966 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
973 bool save_image(const char *file_name)
975 const char *ptr = strrchr((char *)file_name, '.');
977 if (strcasecmp(ptr + 1, "png") == 0)
978 return save_png(file_name);
981 STUBBED("Unsupported image type");
986 static bool save_png(const char *file_name)
989 png_structp png_ptr = NULL;
990 png_infop info_ptr = NULL;
993 fp = fopen(file_name, "wb");
997 png_bytep *row_pointers = new png_bytep[kContextHeight];
998 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
999 if ((!screenshot) || (!row_pointers))
1003 glReadPixels(0, 0, kContextWidth, kContextHeight,
1004 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1005 if (glGetError() != GL_NO_ERROR)
1008 for (int i = 0; i < kContextHeight; i++)
1009 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight - 1) - i)) * 3);
1011 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1012 if (png_ptr == NULL)
1015 info_ptr = png_create_info_struct(png_ptr);
1016 if (info_ptr == NULL)
1019 if (setjmp(png_jmpbuf(png_ptr)))
1022 png_init_io(png_ptr, fp);
1024 if (setjmp(png_jmpbuf(png_ptr)))
1027 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1028 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1029 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1031 png_write_info(png_ptr, info_ptr);
1033 if (setjmp(png_jmpbuf(png_ptr)))
1036 png_write_image(png_ptr, row_pointers);
1038 if (setjmp(png_jmpbuf(png_ptr)))
1041 png_write_end(png_ptr, NULL);
1045 png_destroy_write_struct(&png_ptr, &info_ptr);
1046 delete[] screenshot;
1047 delete[] row_pointers;
1051 unlink(ConvertFileName(file_name));