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
48 static bool load_image(const char * fname, TGAImageRec & tex);
49 static bool load_png(const char * fname, TGAImageRec & tex);
50 static bool load_jpg(const char * fname, TGAImageRec & tex);
51 static bool save_image(const char * fname);
52 static bool save_png(const char * fname);
55 #include "openal_wrapper.h"
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
64 extern bool buttons[3];
65 extern float multiplier;
67 extern float realmultiplier;
69 extern bool cellophane;
71 //extern int terraindetail;
72 //extern int texdetail;
73 extern float terraindetail;
74 extern float texdetail;
77 extern int numplayers;
79 extern Person player[maxplayers];
80 extern bool stillloading;
82 /*extern*/ bool gameFocused;
84 extern float slomospeed;
85 extern float slomofreq;
95 #include "MacCompatibility.h"
100 #include "win-res/resource.h"
107 SDL_Rect **resolutions = NULL;
108 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
109 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
110 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
111 static SDL_Rect *hardcoded_resolutions[] = {
120 unsigned int resolutionDepths[8][2] = {0};
122 int closestResolution(int width, int height);
123 int resolutionID(int width, int height);
125 void ReportError (char * strError);
127 void DrawGL(Game & game);
129 void CreateGLWindow (void);
130 Boolean SetUp (Game & game);
131 void DoKey (SInt8 theKey, SInt8 theCode);
132 void DoUpdate (Game & game);
138 // statics/globals (internal only) ------------------------------------------
140 typedef struct tagPOINT {
149 #pragma warning(push)
150 #pragma warning(disable: 4273)
153 #define GL_FUNC(ret,fn,params,call,rt) \
155 static ret (GLAPIENTRY *p##fn) params = NULL; \
156 ret GLAPIENTRY fn params { rt p##fn call; } \
165 static bool lookup_glsym(const char *funcname, void **func)
167 *func = SDL_GL_GetProcAddress(funcname);
170 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
176 static bool lookup_all_glsyms(void)
179 #define GL_FUNC(ret,fn,params,call,rt) \
180 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
186 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
193 void sdlGetCursorPos(POINT *pt)
195 SDL_GetMouseState(&(pt->x), &(pt->y));
197 #define GetCursorPos(x) sdlGetCursorPos(x)
198 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
199 #define ScreenToClient(x, pt)
200 #define ClientToScreen(x, pt)
204 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
209 static bool g_button, fullscreen = true;
220 kForegroundSleep = 10,
221 kBackgroundSleep = 10000
228 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
231 char gcstrMode [256] = "";
233 UInt32 gSleepTime = kForegroundSleep;
234 Boolean gDone = false, gfFrontProcess = true;
239 static int _argc = 0;
240 static char **_argv = NULL;
243 bool cmdline(const char *cmd)
245 for (int i = 1; i < _argc; i++)
247 char *arg = _argv[i];
250 if (strcasecmp(arg, cmd) == 0)
258 // --------------------------------------------------------------------------
260 void ReportError (char * strError)
262 #ifdef _MSC_VER // !!! FIXME. --ryan.
263 throw std::exception( strError);
266 /* char errMsgCStr [256];
269 sprintf (errMsgCStr, "%s", strError);
271 // out as debug string
272 CToPStr (strErr, errMsgCStr);
277 //-----------------------------------------------------------------------------------------------------------------------
281 void DrawGL (Game & game)
283 if ( stereomode == stereoNone ) {
284 game.DrawGLScene(stereoCenter);
286 game.DrawGLScene(stereoLeft);
287 game.DrawGLScene(stereoRight);
292 static KeyMap g_theKeys;
294 void SetKey( int key)
296 g_theKeys[ key >> 3] |= (1 << (key & 7));
299 void ClearKey( int key)
301 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
304 void GetKeys( unsigned char theKeys[16])
306 memcpy( theKeys, &g_theKeys, 16);
315 #define MAX_SDLKEYS SDLK_LAST
316 static unsigned short KeyTable[MAX_SDLKEYS];
318 static void initSDLKeyTable(void)
320 memset(KeyTable, 0xFF, sizeof (KeyTable));
321 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
322 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
323 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
324 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
325 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
326 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
327 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
328 KeyTable[SDLK_END] = MAC_END_KEY;
329 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
330 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
331 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
332 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
333 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
334 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
335 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
336 KeyTable[SDLK_0] = MAC_0_KEY;
337 KeyTable[SDLK_1] = MAC_1_KEY;
338 KeyTable[SDLK_2] = MAC_2_KEY;
339 KeyTable[SDLK_3] = MAC_3_KEY;
340 KeyTable[SDLK_4] = MAC_4_KEY;
341 KeyTable[SDLK_5] = MAC_5_KEY;
342 KeyTable[SDLK_6] = MAC_6_KEY;
343 KeyTable[SDLK_7] = MAC_7_KEY;
344 KeyTable[SDLK_8] = MAC_8_KEY;
345 KeyTable[SDLK_9] = MAC_9_KEY;
346 KeyTable[SDLK_a] = MAC_A_KEY;
347 KeyTable[SDLK_b] = MAC_B_KEY;
348 KeyTable[SDLK_c] = MAC_C_KEY;
349 KeyTable[SDLK_d] = MAC_D_KEY;
350 KeyTable[SDLK_e] = MAC_E_KEY;
351 KeyTable[SDLK_f] = MAC_F_KEY;
352 KeyTable[SDLK_g] = MAC_G_KEY;
353 KeyTable[SDLK_h] = MAC_H_KEY;
354 KeyTable[SDLK_i] = MAC_I_KEY;
355 KeyTable[SDLK_j] = MAC_J_KEY;
356 KeyTable[SDLK_k] = MAC_K_KEY;
357 KeyTable[SDLK_l] = MAC_L_KEY;
358 KeyTable[SDLK_m] = MAC_M_KEY;
359 KeyTable[SDLK_n] = MAC_N_KEY;
360 KeyTable[SDLK_o] = MAC_O_KEY;
361 KeyTable[SDLK_p] = MAC_P_KEY;
362 KeyTable[SDLK_q] = MAC_Q_KEY;
363 KeyTable[SDLK_r] = MAC_R_KEY;
364 KeyTable[SDLK_s] = MAC_S_KEY;
365 KeyTable[SDLK_t] = MAC_T_KEY;
366 KeyTable[SDLK_u] = MAC_U_KEY;
367 KeyTable[SDLK_v] = MAC_V_KEY;
368 KeyTable[SDLK_w] = MAC_W_KEY;
369 KeyTable[SDLK_x] = MAC_X_KEY;
370 KeyTable[SDLK_y] = MAC_Y_KEY;
371 KeyTable[SDLK_z] = MAC_Z_KEY;
372 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
373 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
374 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
375 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
376 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
377 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
378 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
379 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
380 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
381 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
382 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
383 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
384 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
385 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
386 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
387 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
388 KeyTable[SDLK_F1] = MAC_F1_KEY;
389 KeyTable[SDLK_F2] = MAC_F2_KEY;
390 KeyTable[SDLK_F3] = MAC_F3_KEY;
391 KeyTable[SDLK_F4] = MAC_F4_KEY;
392 KeyTable[SDLK_F5] = MAC_F5_KEY;
393 KeyTable[SDLK_F6] = MAC_F6_KEY;
394 KeyTable[SDLK_F7] = MAC_F7_KEY;
395 KeyTable[SDLK_F8] = MAC_F8_KEY;
396 KeyTable[SDLK_F9] = MAC_F9_KEY;
397 KeyTable[SDLK_F10] = MAC_F10_KEY;
398 KeyTable[SDLK_F11] = MAC_F11_KEY;
399 KeyTable[SDLK_F12] = MAC_F12_KEY;
400 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
401 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
402 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
403 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
404 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
405 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
406 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
407 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
408 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
409 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
410 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
413 static inline int clamp_sdl_mouse_button(Uint8 button)
415 if (button == 2) // right mouse button is button 3 in SDL.
417 else if (button == 3)
420 if ((button >= 1) && (button <= 3))
425 static void sdlEventProc(const SDL_Event &e, Game &game)
428 bool skipkey = false;
433 case SDL_MOUSEMOTION:
434 game.deltah += e.motion.xrel;
435 game.deltav += e.motion.yrel;
438 case SDL_MOUSEBUTTONDOWN:
440 val = clamp_sdl_mouse_button(e.button.button);
441 if ((val >= 0) && (val <= 2))
450 case SDL_MOUSEBUTTONUP:
452 val = clamp_sdl_mouse_button(e.button.button);
453 if ((val >= 0) && (val <= 2))
457 buttons[val] = false;
463 if (e.key.keysym.sym == SDLK_g)
465 if (e.key.keysym.mod & KMOD_CTRL)
468 SDL_GrabMode mode = SDL_GRAB_ON;
469 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
471 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
472 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
474 SDL_WM_GrabInput(mode);
478 else if (e.key.keysym.sym == SDLK_RETURN)
480 if (e.key.keysym.mod & KMOD_ALT)
483 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
487 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
489 if (KeyTable[e.key.keysym.sym] != 0xffff)
490 SetKey(KeyTable[e.key.keysym.sym]);
493 mod = SDL_GetModState();
495 SetKey(MAC_CONTROL_KEY);
497 SetKey(MAC_OPTION_KEY);
499 SetKey(MAC_COMMAND_KEY);
500 if (mod & KMOD_SHIFT)
501 SetKey(MAC_SHIFT_KEY);
503 SetKey(MAC_CAPS_LOCK_KEY);
508 if (e.key.keysym.sym < SDLK_LAST)
510 if (KeyTable[e.key.keysym.sym] != 0xffff)
511 ClearKey(KeyTable[e.key.keysym.sym]);
514 mod = SDL_GetModState();
515 if ((mod & KMOD_CTRL) == 0)
516 ClearKey(MAC_CONTROL_KEY);
517 if ((mod & KMOD_ALT) == 0)
518 ClearKey(MAC_OPTION_KEY);
519 if ((mod & KMOD_META) == 0)
520 ClearKey(MAC_COMMAND_KEY);
521 if ((mod & KMOD_SHIFT) == 0)
522 ClearKey(MAC_SHIFT_KEY);
523 if ((mod & KMOD_CAPS) == 0)
524 ClearKey(MAC_CAPS_LOCK_KEY);
530 // --------------------------------------------------------------------------
532 static Point gMidPoint;
534 Boolean SetUp (Game & game)
540 randSeed = UpTime().lo;
550 DefaultSettings(game);
552 if (!SDL_WasInit(SDL_INIT_VIDEO))
553 if (SDL_Init(SDL_INIT_VIDEO) == -1)
555 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
558 if(!LoadSettings(game)) {
559 fprintf(stderr, "Failed to load config, creating default\n");
562 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
566 if (SDL_GL_LoadLibrary(NULL) == -1)
568 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
573 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
574 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
575 res = hardcoded_resolutions;
577 // reverse list (it was sorted biggest to smallest by SDL)...
579 for (count = 0; res[count]; count++)
581 if ((res[count]->w < 640) || (res[count]->h < 480))
582 break; // sane lower limit.
585 static SDL_Rect *resolutions_block = NULL;
586 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
587 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
588 if ((resolutions_block == NULL) || (resolutions == NULL))
591 fprintf(stderr, "Out of memory!\n");
595 resolutions[count--] = NULL;
596 for (int i = 0; count >= 0; i++, count--)
598 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
599 resolutions[count] = &resolutions_block[count];
602 if (cmdline("showresolutions"))
604 printf("Resolutions we think are okay:\n");
605 for (int i = 0; resolutions[i]; i++)
606 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
609 Uint32 sdlflags = SDL_OPENGL;
610 if (!cmdline("windowed"))
611 sdlflags |= SDL_FULLSCREEN;
613 SDL_WM_SetCaption("Lugaru", "Lugaru");
617 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
618 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
620 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
622 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
623 fprintf(stderr, "forcing 640x480...\n");
625 kContextHeight = 480;
626 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
628 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
629 fprintf(stderr, "forcing 640x480 windowed mode...\n");
630 sdlflags &= ~SDL_FULLSCREEN;
631 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
633 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
640 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
642 fprintf(stderr, "Failed to get double buffered GL context!\n");
647 if (!lookup_all_glsyms())
653 if (!cmdline("nomousegrab"))
654 SDL_WM_GrabInput(SDL_GRAB_ON);
657 glClear( GL_COLOR_BUFFER_BIT );
661 glDisable( GL_ALPHA_TEST);
662 glDisable( GL_BLEND);
663 glDisable( GL_DEPTH_TEST);
664 // glDisable( GL_DITHER);
666 glDisable( GL_LIGHTING);
667 glDisable( GL_LOGIC_OP);
668 glDisable( GL_TEXTURE_1D);
669 glDisable( GL_TEXTURE_2D);
670 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
671 glPixelTransferi( GL_RED_SCALE, 1);
672 glPixelTransferi( GL_RED_BIAS, 0);
673 glPixelTransferi( GL_GREEN_SCALE, 1);
674 glPixelTransferi( GL_GREEN_BIAS, 0);
675 glPixelTransferi( GL_BLUE_SCALE, 1);
676 glPixelTransferi( GL_BLUE_BIAS, 0);
677 glPixelTransferi( GL_ALPHA_SCALE, 1);
678 glPixelTransferi( GL_ALPHA_BIAS, 0);
680 // set initial rendering states
681 glShadeModel( GL_SMOOTH);
683 glDepthFunc( GL_LEQUAL);
684 glDepthMask( GL_TRUE);
685 // glDepthRange( FRONT_CLIP, BACK_CLIP);
686 glEnable( GL_DEPTH_TEST);
687 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
688 glCullFace( GL_FRONT);
689 glEnable( GL_CULL_FACE);
690 glEnable( GL_LIGHTING);
691 // glEnable( GL_LIGHT_MODEL_AMBIENT);
692 glEnable( GL_DITHER);
693 glEnable( GL_COLOR_MATERIAL);
694 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
695 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
696 glAlphaFunc( GL_GREATER, 0.5f);
698 GLint width = kContextWidth;
699 GLint height = kContextHeight;
700 gMidPoint.h = width / 2;
701 gMidPoint.v = height / 2;
705 game.newdetail=detail;
706 game.newscreenwidth=screenwidth;
707 game.newscreenheight=screenheight;
709 if ( CanInitStereo(stereomode) ) {
710 InitStereo(stereomode);
712 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
713 stereomode = stereoNone;
722 static void DoMouse(Game & game)
725 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
727 game.deltah *= usermousesensitivity;
728 game.deltav *= usermousesensitivity;
729 game.mousecoordh += game.deltah;
730 game.mousecoordv += game.deltav;
731 if (game.mousecoordh < 0)
732 game.mousecoordh = 0;
733 else if (game.mousecoordh >= kContextWidth)
734 game.mousecoordh = kContextWidth - 1;
735 if (game.mousecoordv < 0)
736 game.mousecoordv = 0;
737 else if (game.mousecoordv >= kContextHeight)
738 game.mousecoordv = kContextHeight - 1;
745 // --------------------------------------------------------------------------
747 void DoKey (SInt8 theKey, SInt8 theCode)
752 // --------------------------------------------------------------------------
756 void DoFrameRate (int update)
758 static long frames = 0;
760 static AbsoluteTime time = {0,0};
761 static AbsoluteTime frametime = {0,0};
762 AbsoluteTime currTime = UpTime ();
763 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
765 if (0 > deltaTime) // if negative microseconds
766 deltaTime /= -1000000.0;
767 else // else milliseconds
770 multiplier=deltaTime;
771 if(multiplier<.001) multiplier=.001;
772 if(multiplier>10) multiplier=10;
773 if(update) frametime = currTime; // reset for next time interval
775 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
777 if (0 > deltaTime) // if negative microseconds
778 deltaTime /= -1000000.0;
779 else // else milliseconds
782 if (0.001 <= deltaTime) // has update interval passed
785 time = currTime; // reset for next time interval
792 void DoUpdate (Game & game)
794 static float sps=200;
796 static float oldmult;
799 if(multiplier>.6)multiplier=.6;
801 game.fps=1/multiplier;
803 count = multiplier*sps;
805 //if(count>10)count=10;
807 realmultiplier=multiplier;
808 multiplier*=gamespeed;
809 if(difficulty==1)multiplier*=.9;
810 if(difficulty==0)multiplier*=.8;
812 if(game.loading==4)multiplier*=.00001;
814 if(slomo&&!mainmenu)multiplier*=slomospeed;
815 //if(freeze)multiplier*=0.00001;
817 multiplier/=(float)count;
823 for(int i=0;i<count;i++)
829 game.TickOnceAfter();
830 /* - Debug code to test how many channels were active on average per frame
831 static long frames = 0;
833 static AbsoluteTime start = {0,0};
834 AbsoluteTime currTime = UpTime ();
835 static int num_channels = 0;
837 num_channels += OPENAL_GetChannelsPlaying();
838 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
840 if (0 > deltaTime) // if negative microseconds
841 deltaTime /= -1000000.0;
842 else // else milliseconds
850 float avg_channels = (float)num_channels / (float)frames;
852 ofstream opstream("log.txt",ios::app);
853 opstream << "Average frame count: ";
855 opstream << " frames - ";
856 opstream << avg_channels;
857 opstream << " per frame.\n";
867 // --------------------------------------------------------------------------
880 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
883 // cheat here...static destructors are calling glDeleteTexture() after
884 // the context is destroyed and libGL unloaded by SDL_Quit().
885 pglDeleteTextures = glDeleteTextures_doNothing;
889 // --------------------------------------------------------------------------
891 static bool IsFocused()
893 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
897 static void launch_web_browser(const char *url)
900 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
902 #elif (defined(__APPLE__) && defined(__MACH__))
903 const char *fmt = "open '%s'";
904 const size_t len = strlen(fmt) + strlen(url) + 16;
905 char *buf = new char[len];
906 snprintf(buf, len, fmt, url);
911 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
912 const size_t len = strlen(fmt) + strlen(url) + 16;
913 char *buf = new char[len];
914 snprintf(buf, len, fmt, url);
922 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
923 static char *findBinaryInPath(const char *bin, char *envr)
925 size_t alloc_size = 0;
933 ptr = strchr(start, ':'); /* find next $PATH separator. */
937 size = strlen(start) + strlen(bin) + 2;
938 if (size > alloc_size)
940 char *x = (char *) realloc(exe, size);
952 /* build full binary path... */
954 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
958 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
960 strcpy(exe, start); /* i'm lazy. piss off. */
964 start = ptr + 1; /* start points to beginning of next element. */
965 } while (ptr != NULL);
970 return(NULL); /* doesn't exist in path. */
971 } /* findBinaryInPath */
974 char *calcBaseDir(const char *argv0)
976 /* If there isn't a path on argv0, then look through the $PATH for it. */
980 const char *ptr = strrchr((char *)argv0, '/');
981 if (strchr(argv0, '/'))
983 retval = strdup(argv0);
985 *((char *) strrchr(retval, '/')) = '\0';
989 envr = getenv("PATH");
990 if (!envr) return NULL;
992 if (!envr) return NULL;
993 retval = findBinaryInPath(argv0, envr);
998 static inline void chdirToAppPath(const char *argv0)
1000 char *dir = calcBaseDir(argv0);
1003 #if (defined(__APPLE__) && defined(__MACH__))
1004 // Chop off /Contents/MacOS if it's at the end of the string, so we
1005 // land in the base of the app bundle.
1006 const size_t len = strlen(dir);
1007 const char *bundledirs = "/Contents/MacOS";
1008 const size_t bundledirslen = strlen(bundledirs);
1009 if (len > bundledirslen)
1011 char *ptr = (dir + len) - bundledirslen;
1012 if (strcasecmp(ptr, bundledirs) == 0)
1023 int main(int argc, char **argv)
1030 // !!! FIXME: we could use a Win32 API for this. --ryan.
1032 chdirToAppPath(argv[0]);
1037 memset( &g_theKeys, 0, sizeof( KeyMap));
1043 bool regnow = false;
1048 //ofstream os("error.txt");
1050 //ofstream os("log.txt");
1056 while (!gDone&&!game.quit&&(!game.tryquit))
1062 // check windows messages
1068 while( SDL_PollEvent( &e ) )
1070 if( e.type == SDL_QUIT )
1075 sdlEventProc(e, game);
1086 // allow game chance to pause
1087 gameFocused = false;
1091 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1092 SDL_ActiveEvent evt;
1093 SDL_WaitEvent((SDL_Event*)&evt);
1094 if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
1096 else if (evt.type == SDL_QUIT)
1101 regnow = game.registernow;
1106 // if(game.registernow){
1109 #if (defined(__APPLE__) && defined(__MACH__))
1110 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1111 #elif PLATFORM_LINUX
1112 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1114 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1118 #if PLATFORM_LINUX // (this may not be necessary any more.)
1119 _exit(0); // !!! FIXME: hack...crashes on exit!
1123 catch (const std::exception& error)
1127 std::string e = "Caught exception: ";
1132 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1142 // --------------------------------------------------------------------------
1144 extern int channels[100];
1145 extern OPENAL_SAMPLE * samp[100];
1146 extern OPENAL_STREAM * strm[20];
1148 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1150 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1151 if (currSample && currSample == samp[chan])
1153 if (OPENAL_GetPaused(channels[chan]))
1155 OPENAL_StopSound(channels[chan]);
1156 channels[chan] = OPENAL_FREE;
1158 else if (OPENAL_IsPlaying(channels[chan]))
1160 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1161 if (loop_mode & OPENAL_LOOP_OFF)
1163 channels[chan] = OPENAL_FREE;
1169 channels[chan] = OPENAL_FREE;
1172 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1173 if (channels[chan] < 0)
1175 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1179 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1181 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1182 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1184 OPENAL_StopSound(channels[chan]);
1185 OPENAL_Stream_Stop(sptr);
1189 OPENAL_Stream_Stop(sptr);
1190 channels[chan] = OPENAL_FREE;
1193 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1194 if (channels[chan] < 0)
1196 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1201 bool LoadImage(const char * fname, TGAImageRec & tex)
1203 if ( tex.data == NULL )
1206 return load_image(fname, tex);
1209 void ScreenShot(const char * fname)
1216 static bool load_image(const char *file_name, TGAImageRec &tex)
1218 const char *ptr = strrchr((char *)file_name, '.');
1221 if (strcasecmp(ptr+1, "png") == 0)
1222 return load_png(file_name, tex);
1223 else if (strcasecmp(ptr+1, "jpg") == 0)
1224 return load_jpg(file_name, tex);
1227 STUBBED("Unsupported image type");
1232 struct my_error_mgr {
1233 struct jpeg_error_mgr pub; /* "public" fields */
1234 jmp_buf setjmp_buffer; /* for return to caller */
1236 typedef struct my_error_mgr * my_error_ptr;
1239 static void my_error_exit(j_common_ptr cinfo)
1241 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1242 longjmp(err->setjmp_buffer, 1);
1245 /* stolen from public domain example.c code in libjpg distribution. */
1246 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1248 struct jpeg_decompress_struct cinfo;
1249 struct my_error_mgr jerr;
1250 JSAMPROW buffer[1]; /* Output row buffer */
1251 int row_stride; /* physical row width in output buffer */
1252 FILE *infile = fopen(file_name, "rb");
1257 cinfo.err = jpeg_std_error(&jerr.pub);
1258 jerr.pub.error_exit = my_error_exit;
1259 if (setjmp(jerr.setjmp_buffer)) {
1260 jpeg_destroy_decompress(&cinfo);
1265 jpeg_create_decompress(&cinfo);
1266 jpeg_stdio_src(&cinfo, infile);
1267 (void) jpeg_read_header(&cinfo, TRUE);
1269 cinfo.out_color_space = JCS_RGB;
1270 cinfo.quantize_colors = 0;
1271 (void) jpeg_calc_output_dimensions(&cinfo);
1272 (void) jpeg_start_decompress(&cinfo);
1274 row_stride = cinfo.output_width * cinfo.output_components;
1275 tex.sizeX = cinfo.output_width;
1276 tex.sizeY = cinfo.output_height;
1279 while (cinfo.output_scanline < cinfo.output_height) {
1280 buffer[0] = (JSAMPROW)(char *)tex.data +
1281 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1282 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1285 (void) jpeg_finish_decompress(&cinfo);
1286 jpeg_destroy_decompress(&cinfo);
1293 /* stolen from public domain example.c code in libpng distribution. */
1294 static bool load_png(const char *file_name, TGAImageRec &tex)
1296 bool hasalpha = false;
1297 png_structp png_ptr = NULL;
1298 png_infop info_ptr = NULL;
1299 png_uint_32 width, height;
1300 int bit_depth, color_type, interlace_type;
1301 png_byte **rows = NULL;
1302 bool retval = false;
1303 png_byte **row_pointers = NULL;
1304 FILE *fp = fopen(file_name, "rb");
1309 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1310 if (png_ptr == NULL)
1313 info_ptr = png_create_info_struct(png_ptr);
1314 if (info_ptr == NULL)
1317 if (setjmp(png_jmpbuf(png_ptr)))
1320 png_init_io(png_ptr, fp);
1321 png_read_png(png_ptr, info_ptr,
1322 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1324 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1325 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1327 if (bit_depth != 8) // transform SHOULD handle this...
1330 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1333 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1336 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1337 row_pointers = png_get_rows(png_ptr, info_ptr);
1343 png_byte *dst = tex.data;
1344 for (int i = height-1; i >= 0; i--)
1346 png_byte *src = row_pointers[i];
1347 for (int j = 0; j < width; j++)
1361 png_byte *dst = tex.data;
1362 int pitch = width * 4;
1363 for (int i = height-1; i >= 0; i--, dst += pitch)
1364 memcpy(dst, row_pointers[i], pitch);
1373 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1380 static bool save_image(const char *file_name)
1382 const char *ptr = strrchr((char *)file_name, '.');
1385 if (strcasecmp(ptr+1, "png") == 0)
1386 return save_png(file_name);
1389 STUBBED("Unsupported image type");
1394 static bool save_png(const char *file_name)
1397 png_structp png_ptr = NULL;
1398 png_infop info_ptr = NULL;
1399 bool retval = false;
1401 fp = fopen(file_name, "wb");
1405 png_bytep *row_pointers = new png_bytep[kContextHeight];
1406 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1407 if ((!screenshot) || (!row_pointers))
1411 glReadPixels(0, 0, kContextWidth, kContextHeight,
1412 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1413 if (glGetError() != GL_NO_ERROR)
1416 for (int i = 0; i < kContextHeight; i++)
1417 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1419 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1420 if (png_ptr == NULL)
1423 info_ptr = png_create_info_struct(png_ptr);
1424 if (info_ptr == NULL)
1427 if (setjmp(png_jmpbuf(png_ptr)))
1430 png_init_io(png_ptr, fp);
1432 if (setjmp(png_jmpbuf(png_ptr)))
1435 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1436 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1437 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1439 png_write_info(png_ptr, info_ptr);
1441 if (setjmp(png_jmpbuf(png_ptr)))
1444 png_write_image(png_ptr, row_pointers);
1446 if (setjmp(png_jmpbuf(png_ptr)))
1449 png_write_end(png_ptr, NULL);
1453 png_destroy_write_struct(&png_ptr, &info_ptr);
1454 delete[] screenshot;
1455 delete[] row_pointers;
1459 unlink(ConvertFileName(file_name));