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 bool selectDetail(int & width, int & height, int & bpp, int & detail);
123 int closestResolution(int width, int height);
124 int resolutionID(int width, int height);
126 void ReportError (char * strError);
128 void SetupDSpFullScreen();
131 void DrawGL(Game & game);
133 void CreateGLWindow (void);
134 Boolean SetUp (Game & game);
135 void DoKey (SInt8 theKey, SInt8 theCode);
136 void DoUpdate (Game & game);
142 // statics/globals (internal only) ------------------------------------------
144 typedef struct tagPOINT {
153 #pragma warning(push)
154 #pragma warning(disable: 4273)
157 #define GL_FUNC(ret,fn,params,call,rt) \
159 static ret (GLAPIENTRY *p##fn) params = NULL; \
160 ret GLAPIENTRY fn params { rt p##fn call; } \
169 static bool lookup_glsym(const char *funcname, void **func)
171 *func = SDL_GL_GetProcAddress(funcname);
174 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
180 static bool lookup_all_glsyms(void)
183 #define GL_FUNC(ret,fn,params,call,rt) \
184 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
190 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
197 void sdlGetCursorPos(POINT *pt)
200 SDL_GetMouseState(&x, &y);
204 #define GetCursorPos(x) sdlGetCursorPos(x)
205 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
206 #define ScreenToClient(x, pt)
207 #define ClientToScreen(x, pt)
211 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
216 static bool g_button, fullscreen = true;
227 kForegroundSleep = 10,
228 kBackgroundSleep = 10000
235 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
238 char gcstrMode [256] = "";
240 UInt32 gSleepTime = kForegroundSleep;
241 Boolean gDone = false, gfFrontProcess = true;
246 static int _argc = 0;
247 static char **_argv = NULL;
250 bool cmdline(const char *cmd)
252 for (int i = 1; i < _argc; i++)
254 char *arg = _argv[i];
257 if (strcasecmp(arg, cmd) == 0)
265 // --------------------------------------------------------------------------
267 void ReportError (char * strError)
269 #ifdef _MSC_VER // !!! FIXME. --ryan.
270 throw std::exception( strError);
273 /* char errMsgCStr [256];
276 sprintf (errMsgCStr, "%s", strError);
278 // out as debug string
279 CToPStr (strErr, errMsgCStr);
284 void SetupDSpFullScreen ()
294 //-----------------------------------------------------------------------------------------------------------------------
298 void DrawGL (Game & game)
300 if ( stereomode == stereoNone ) {
301 game.DrawGLScene(stereoCenter);
303 game.DrawGLScene(stereoLeft);
304 game.DrawGLScene(stereoRight);
309 static KeyMap g_theKeys;
311 void SetKey( int key)
313 g_theKeys[ key >> 3] |= (1 << (key & 7));
316 void ClearKey( int key)
318 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
321 void GetKeys( unsigned char theKeys[16])
323 memcpy( theKeys, &g_theKeys, 16);
332 #define MAX_SDLKEYS SDLK_LAST
333 static unsigned short KeyTable[MAX_SDLKEYS];
335 static void initSDLKeyTable(void)
337 memset(KeyTable, 0xFF, sizeof (KeyTable));
338 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
339 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
340 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
341 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
342 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
343 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
344 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
345 KeyTable[SDLK_END] = MAC_END_KEY;
346 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
347 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
348 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
349 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
350 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
351 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
352 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
353 KeyTable[SDLK_0] = MAC_0_KEY;
354 KeyTable[SDLK_1] = MAC_1_KEY;
355 KeyTable[SDLK_2] = MAC_2_KEY;
356 KeyTable[SDLK_3] = MAC_3_KEY;
357 KeyTable[SDLK_4] = MAC_4_KEY;
358 KeyTable[SDLK_5] = MAC_5_KEY;
359 KeyTable[SDLK_6] = MAC_6_KEY;
360 KeyTable[SDLK_7] = MAC_7_KEY;
361 KeyTable[SDLK_8] = MAC_8_KEY;
362 KeyTable[SDLK_9] = MAC_9_KEY;
363 KeyTable[SDLK_a] = MAC_A_KEY;
364 KeyTable[SDLK_b] = MAC_B_KEY;
365 KeyTable[SDLK_c] = MAC_C_KEY;
366 KeyTable[SDLK_d] = MAC_D_KEY;
367 KeyTable[SDLK_e] = MAC_E_KEY;
368 KeyTable[SDLK_f] = MAC_F_KEY;
369 KeyTable[SDLK_g] = MAC_G_KEY;
370 KeyTable[SDLK_h] = MAC_H_KEY;
371 KeyTable[SDLK_i] = MAC_I_KEY;
372 KeyTable[SDLK_j] = MAC_J_KEY;
373 KeyTable[SDLK_k] = MAC_K_KEY;
374 KeyTable[SDLK_l] = MAC_L_KEY;
375 KeyTable[SDLK_m] = MAC_M_KEY;
376 KeyTable[SDLK_n] = MAC_N_KEY;
377 KeyTable[SDLK_o] = MAC_O_KEY;
378 KeyTable[SDLK_p] = MAC_P_KEY;
379 KeyTable[SDLK_q] = MAC_Q_KEY;
380 KeyTable[SDLK_r] = MAC_R_KEY;
381 KeyTable[SDLK_s] = MAC_S_KEY;
382 KeyTable[SDLK_t] = MAC_T_KEY;
383 KeyTable[SDLK_u] = MAC_U_KEY;
384 KeyTable[SDLK_v] = MAC_V_KEY;
385 KeyTable[SDLK_w] = MAC_W_KEY;
386 KeyTable[SDLK_x] = MAC_X_KEY;
387 KeyTable[SDLK_y] = MAC_Y_KEY;
388 KeyTable[SDLK_z] = MAC_Z_KEY;
389 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
390 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
391 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
392 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
393 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
394 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
395 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
396 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
397 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
398 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
399 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
400 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
401 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
402 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
403 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
404 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
405 KeyTable[SDLK_F1] = MAC_F1_KEY;
406 KeyTable[SDLK_F2] = MAC_F2_KEY;
407 KeyTable[SDLK_F3] = MAC_F3_KEY;
408 KeyTable[SDLK_F4] = MAC_F4_KEY;
409 KeyTable[SDLK_F5] = MAC_F5_KEY;
410 KeyTable[SDLK_F6] = MAC_F6_KEY;
411 KeyTable[SDLK_F7] = MAC_F7_KEY;
412 KeyTable[SDLK_F8] = MAC_F8_KEY;
413 KeyTable[SDLK_F9] = MAC_F9_KEY;
414 KeyTable[SDLK_F10] = MAC_F10_KEY;
415 KeyTable[SDLK_F11] = MAC_F11_KEY;
416 KeyTable[SDLK_F12] = MAC_F12_KEY;
417 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
418 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
419 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
420 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
421 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
422 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
423 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
424 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
425 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
426 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
427 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
430 static inline int clamp_sdl_mouse_button(Uint8 button)
432 if (button == 2) // right mouse button is button 3 in SDL.
434 else if (button == 3)
437 if ((button >= 1) && (button <= 3))
442 static void sdlEventProc(const SDL_Event &e, Game &game)
445 bool skipkey = false;
450 case SDL_MOUSEMOTION:
451 game.deltah += e.motion.xrel;
452 game.deltav += e.motion.yrel;
455 case SDL_MOUSEBUTTONDOWN:
457 val = clamp_sdl_mouse_button(e.button.button);
458 if ((val >= 0) && (val <= 2))
467 case SDL_MOUSEBUTTONUP:
469 val = clamp_sdl_mouse_button(e.button.button);
470 if ((val >= 0) && (val <= 2))
474 buttons[val] = false;
480 if (e.key.keysym.sym == SDLK_g)
482 if (e.key.keysym.mod & KMOD_CTRL)
485 SDL_GrabMode mode = SDL_GRAB_ON;
486 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
488 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
489 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
491 SDL_WM_GrabInput(mode);
495 else if (e.key.keysym.sym == SDLK_RETURN)
497 if (e.key.keysym.mod & KMOD_ALT)
500 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
504 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
506 if (KeyTable[e.key.keysym.sym] != 0xffff)
507 SetKey(KeyTable[e.key.keysym.sym]);
510 mod = SDL_GetModState();
512 SetKey(MAC_CONTROL_KEY);
514 SetKey(MAC_OPTION_KEY);
516 SetKey(MAC_COMMAND_KEY);
517 if (mod & KMOD_SHIFT)
518 SetKey(MAC_SHIFT_KEY);
520 SetKey(MAC_CAPS_LOCK_KEY);
525 if (e.key.keysym.sym < SDLK_LAST)
527 if (KeyTable[e.key.keysym.sym] != 0xffff)
528 ClearKey(KeyTable[e.key.keysym.sym]);
531 mod = SDL_GetModState();
532 if ((mod & KMOD_CTRL) == 0)
533 ClearKey(MAC_CONTROL_KEY);
534 if ((mod & KMOD_ALT) == 0)
535 ClearKey(MAC_OPTION_KEY);
536 if ((mod & KMOD_META) == 0)
537 ClearKey(MAC_COMMAND_KEY);
538 if ((mod & KMOD_SHIFT) == 0)
539 ClearKey(MAC_SHIFT_KEY);
540 if ((mod & KMOD_CAPS) == 0)
541 ClearKey(MAC_CAPS_LOCK_KEY);
547 // --------------------------------------------------------------------------
549 static Point gMidPoint;
551 Boolean SetUp (Game & game)
557 randSeed = UpTime().lo;
567 DefaultSettings(game);
569 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
571 if(!LoadSettings(game)) {
572 fprintf(stderr, "Failed to load config, creating default\n");
576 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
581 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
583 SetupDSpFullScreen();
586 if (!SDL_WasInit(SDL_INIT_VIDEO))
588 if (SDL_Init(SDL_INIT_VIDEO) == -1)
590 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
594 if (SDL_GL_LoadLibrary(NULL) == -1)
596 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
601 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
602 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
603 res = hardcoded_resolutions;
605 // reverse list (it was sorted biggest to smallest by SDL)...
607 for (count = 0; res[count]; count++)
609 if ((res[count]->w < 640) || (res[count]->h < 480))
610 break; // sane lower limit.
613 static SDL_Rect *resolutions_block = NULL;
614 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
615 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
616 if ((resolutions_block == NULL) || (resolutions == NULL))
619 fprintf(stderr, "Out of memory!\n");
623 resolutions[count--] = NULL;
624 for (int i = 0; count >= 0; i++, count--)
626 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
627 resolutions[count] = &resolutions_block[count];
630 if (cmdline("showresolutions"))
632 printf("Resolutions we think are okay:\n");
633 for (int i = 0; resolutions[i]; i++)
634 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
638 Uint32 sdlflags = SDL_OPENGL;
639 if (!cmdline("windowed"))
640 sdlflags |= SDL_FULLSCREEN;
642 SDL_WM_SetCaption("Lugaru", "Lugaru");
646 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
647 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
649 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
651 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
652 fprintf(stderr, "forcing 640x480...\n");
654 kContextHeight = 480;
655 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
657 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
658 fprintf(stderr, "forcing 640x480 windowed mode...\n");
659 sdlflags &= ~SDL_FULLSCREEN;
660 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
662 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
669 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
671 fprintf(stderr, "Failed to get double buffered GL context!\n");
676 if (!lookup_all_glsyms())
682 if (!cmdline("nomousegrab"))
683 SDL_WM_GrabInput(SDL_GRAB_ON);
686 glClear( GL_COLOR_BUFFER_BIT );
690 glDisable( GL_ALPHA_TEST);
691 glDisable( GL_BLEND);
692 glDisable( GL_DEPTH_TEST);
693 // glDisable( GL_DITHER);
695 glDisable( GL_LIGHTING);
696 glDisable( GL_LOGIC_OP);
697 glDisable( GL_TEXTURE_1D);
698 glDisable( GL_TEXTURE_2D);
699 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
700 glPixelTransferi( GL_RED_SCALE, 1);
701 glPixelTransferi( GL_RED_BIAS, 0);
702 glPixelTransferi( GL_GREEN_SCALE, 1);
703 glPixelTransferi( GL_GREEN_BIAS, 0);
704 glPixelTransferi( GL_BLUE_SCALE, 1);
705 glPixelTransferi( GL_BLUE_BIAS, 0);
706 glPixelTransferi( GL_ALPHA_SCALE, 1);
707 glPixelTransferi( GL_ALPHA_BIAS, 0);
709 // set initial rendering states
710 glShadeModel( GL_SMOOTH);
712 glDepthFunc( GL_LEQUAL);
713 glDepthMask( GL_TRUE);
714 // glDepthRange( FRONT_CLIP, BACK_CLIP);
715 glEnable( GL_DEPTH_TEST);
716 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
717 glCullFace( GL_FRONT);
718 glEnable( GL_CULL_FACE);
719 glEnable( GL_LIGHTING);
720 // glEnable( GL_LIGHT_MODEL_AMBIENT);
721 glEnable( GL_DITHER);
722 glEnable( GL_COLOR_MATERIAL);
723 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
724 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
725 glAlphaFunc( GL_GREATER, 0.5f);
727 GLint width = kContextWidth;
728 GLint height = kContextHeight;
729 gMidPoint.h = width / 2;
730 gMidPoint.v = height / 2;
734 game.newdetail=detail;
735 game.newscreenwidth=screenwidth;
736 game.newscreenheight=screenheight;
738 if ( CanInitStereo(stereomode) ) {
739 InitStereo(stereomode);
741 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
742 stereomode = stereoNone;
751 static void DoMouse(Game & game)
754 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
756 game.deltah *= usermousesensitivity;
757 game.deltav *= usermousesensitivity;
758 game.mousecoordh += game.deltah;
759 game.mousecoordv += game.deltav;
760 if (game.mousecoordh < 0)
761 game.mousecoordh = 0;
762 else if (game.mousecoordh >= kContextWidth)
763 game.mousecoordh = kContextWidth - 1;
764 if (game.mousecoordv < 0)
765 game.mousecoordv = 0;
766 else if (game.mousecoordv >= kContextHeight)
767 game.mousecoordv = kContextHeight - 1;
774 // --------------------------------------------------------------------------
776 void DoKey (SInt8 theKey, SInt8 theCode)
781 // --------------------------------------------------------------------------
785 void DoFrameRate (int update)
787 static long frames = 0;
789 static AbsoluteTime time = {0,0};
790 static AbsoluteTime frametime = {0,0};
791 AbsoluteTime currTime = UpTime ();
792 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
794 if (0 > deltaTime) // if negative microseconds
795 deltaTime /= -1000000.0;
796 else // else milliseconds
799 multiplier=deltaTime;
800 if(multiplier<.001)multiplier=.001;
801 if(multiplier>10)multiplier=10;
802 if(update)frametime = currTime; // reset for next time interval
804 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
806 if (0 > deltaTime) // if negative microseconds
807 deltaTime /= -1000000.0;
808 else // else milliseconds
811 if (0.001 <= deltaTime) // has update interval passed
814 time = currTime; // reset for next time interval
821 void DoUpdate (Game & game)
823 static float sps=200;
825 static float oldmult;
828 if(multiplier>.6)multiplier=.6;
830 game.fps=1/multiplier;
832 count = multiplier*sps;
834 //if(count>10)count=10;
836 realmultiplier=multiplier;
837 multiplier*=gamespeed;
838 if(difficulty==1)multiplier*=.9;
839 if(difficulty==0)multiplier*=.8;
841 if(game.loading==4)multiplier*=.00001;
843 if(slomo&&!mainmenu)multiplier*=slomospeed;
844 //if(freeze)multiplier*=0.00001;
846 multiplier/=(float)count;
852 for(int i=0;i<count;i++)
858 game.TickOnceAfter();
859 /* - Debug code to test how many channels were active on average per frame
860 static long frames = 0;
862 static AbsoluteTime start = {0,0};
863 AbsoluteTime currTime = UpTime ();
864 static int num_channels = 0;
866 num_channels += OPENAL_GetChannelsPlaying();
867 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
869 if (0 > deltaTime) // if negative microseconds
870 deltaTime /= -1000000.0;
871 else // else milliseconds
879 float avg_channels = (float)num_channels / (float)frames;
881 ofstream opstream("log.txt",ios::app);
882 opstream << "Average frame count: ";
884 opstream << " frames - ";
885 opstream << avg_channels;
886 opstream << " per frame.\n";
896 // --------------------------------------------------------------------------
909 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
912 // cheat here...static destructors are calling glDeleteTexture() after
913 // the context is destroyed and libGL unloaded by SDL_Quit().
914 pglDeleteTextures = glDeleteTextures_doNothing;
918 // --------------------------------------------------------------------------
920 static bool IsFocused()
922 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
926 static void launch_web_browser(const char *url)
929 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
931 #elif (defined(__APPLE__) && defined(__MACH__))
932 const char *fmt = "open '%s'";
933 const size_t len = strlen(fmt) + strlen(url) + 16;
934 char *buf = new char[len];
935 snprintf(buf, len, fmt, url);
940 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
941 const size_t len = strlen(fmt) + strlen(url) + 16;
942 char *buf = new char[len];
943 snprintf(buf, len, fmt, url);
951 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
952 static char *findBinaryInPath(const char *bin, char *envr)
954 size_t alloc_size = 0;
962 ptr = strchr(start, ':'); /* find next $PATH separator. */
966 size = strlen(start) + strlen(bin) + 2;
967 if (size > alloc_size)
969 char *x = (char *) realloc(exe, size);
981 /* build full binary path... */
983 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
987 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
989 strcpy(exe, start); /* i'm lazy. piss off. */
993 start = ptr + 1; /* start points to beginning of next element. */
994 } while (ptr != NULL);
999 return(NULL); /* doesn't exist in path. */
1000 } /* findBinaryInPath */
1003 char *calcBaseDir(const char *argv0)
1005 /* If there isn't a path on argv0, then look through the $PATH for it. */
1009 const char *ptr = strrchr((char *)argv0, '/');
1010 if (strchr(argv0, '/'))
1012 retval = strdup(argv0);
1014 *((char *) strrchr(retval, '/')) = '\0';
1018 envr = getenv("PATH");
1019 if (!envr) return NULL;
1020 envr = strdup(envr);
1021 if (!envr) return NULL;
1022 retval = findBinaryInPath(argv0, envr);
1027 static inline void chdirToAppPath(const char *argv0)
1029 char *dir = calcBaseDir(argv0);
1032 #if (defined(__APPLE__) && defined(__MACH__))
1033 // Chop off /Contents/MacOS if it's at the end of the string, so we
1034 // land in the base of the app bundle.
1035 const size_t len = strlen(dir);
1036 const char *bundledirs = "/Contents/MacOS";
1037 const size_t bundledirslen = strlen(bundledirs);
1038 if (len > bundledirslen)
1040 char *ptr = (dir + len) - bundledirslen;
1041 if (strcasecmp(ptr, bundledirs) == 0)
1052 int main(int argc, char **argv)
1059 // !!! FIXME: we could use a Win32 API for this. --ryan.
1061 chdirToAppPath(argv[0]);
1066 memset( &g_theKeys, 0, sizeof( KeyMap));
1072 bool regnow = false;
1077 //ofstream os("error.txt");
1079 //ofstream os("log.txt");
1085 while (!gDone&&!game.quit&&(!game.tryquit))
1091 // check windows messages
1097 while( SDL_PollEvent( &e ) )
1099 if( e.type == SDL_QUIT )
1104 sdlEventProc(e, game);
1115 // allow game chance to pause
1116 gameFocused = false;
1120 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1121 STUBBED("give up CPU but sniff the event queue");
1125 regnow = game.registernow;
1130 // if(game.registernow){
1133 #if (defined(__APPLE__) && defined(__MACH__))
1134 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1135 #elif PLATFORM_LINUX
1136 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1138 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1142 #if PLATFORM_LINUX // (this may not be necessary any more.)
1143 _exit(0); // !!! FIXME: hack...crashes on exit!
1147 catch (const std::exception& error)
1151 std::string e = "Caught exception: ";
1156 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1166 // --------------------------------------------------------------------------
1170 bool selectDetail(int & width, int & height, int & bpp, int & detail)
1174 // currently with SDL, we just use whatever is requested
1175 // and don't care. --ryan.
1181 extern int channels[100];
1182 extern OPENAL_SAMPLE * samp[100];
1183 extern OPENAL_STREAM * strm[20];
1185 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1187 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1188 if (currSample && currSample == samp[chan])
1190 if (OPENAL_GetPaused(channels[chan]))
1192 OPENAL_StopSound(channels[chan]);
1193 channels[chan] = OPENAL_FREE;
1195 else if (OPENAL_IsPlaying(channels[chan]))
1197 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1198 if (loop_mode & OPENAL_LOOP_OFF)
1200 channels[chan] = OPENAL_FREE;
1206 channels[chan] = OPENAL_FREE;
1209 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1210 if (channels[chan] < 0)
1212 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1216 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1218 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1219 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1221 OPENAL_StopSound(channels[chan]);
1222 OPENAL_Stream_Stop(sptr);
1226 OPENAL_Stream_Stop(sptr);
1227 channels[chan] = OPENAL_FREE;
1230 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1231 if (channels[chan] < 0)
1233 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1238 bool LoadImage(const char * fname, TGAImageRec & tex)
1242 if ( tex.data == NULL )
1248 res = load_image(fname, tex);
1254 void ScreenShot(const char * fname)
1263 static bool load_image(const char *file_name, TGAImageRec &tex)
1265 const char *ptr = strrchr((char *)file_name, '.');
1268 if (strcasecmp(ptr+1, "png") == 0)
1269 return load_png(file_name, tex);
1270 else if (strcasecmp(ptr+1, "jpg") == 0)
1271 return load_jpg(file_name, tex);
1274 STUBBED("Unsupported image type");
1279 struct my_error_mgr {
1280 struct jpeg_error_mgr pub; /* "public" fields */
1281 jmp_buf setjmp_buffer; /* for return to caller */
1283 typedef struct my_error_mgr * my_error_ptr;
1286 static void my_error_exit(j_common_ptr cinfo)
1288 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1289 longjmp(err->setjmp_buffer, 1);
1292 /* stolen from public domain example.c code in libjpg distribution. */
1293 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1295 struct jpeg_decompress_struct cinfo;
1296 struct my_error_mgr jerr;
1297 JSAMPROW buffer[1]; /* Output row buffer */
1298 int row_stride; /* physical row width in output buffer */
1299 FILE *infile = fopen(file_name, "rb");
1304 cinfo.err = jpeg_std_error(&jerr.pub);
1305 jerr.pub.error_exit = my_error_exit;
1306 if (setjmp(jerr.setjmp_buffer)) {
1307 jpeg_destroy_decompress(&cinfo);
1312 jpeg_create_decompress(&cinfo);
1313 jpeg_stdio_src(&cinfo, infile);
1314 (void) jpeg_read_header(&cinfo, TRUE);
1316 cinfo.out_color_space = JCS_RGB;
1317 cinfo.quantize_colors = 0;
1318 (void) jpeg_calc_output_dimensions(&cinfo);
1319 (void) jpeg_start_decompress(&cinfo);
1321 row_stride = cinfo.output_width * cinfo.output_components;
1322 tex.sizeX = cinfo.output_width;
1323 tex.sizeY = cinfo.output_height;
1326 while (cinfo.output_scanline < cinfo.output_height) {
1327 buffer[0] = (JSAMPROW)(char *)tex.data +
1328 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1329 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1332 (void) jpeg_finish_decompress(&cinfo);
1333 jpeg_destroy_decompress(&cinfo);
1340 /* stolen from public domain example.c code in libpng distribution. */
1341 static bool load_png(const char *file_name, TGAImageRec &tex)
1343 bool hasalpha = false;
1344 png_structp png_ptr = NULL;
1345 png_infop info_ptr = NULL;
1346 png_uint_32 width, height;
1347 int bit_depth, color_type, interlace_type;
1348 png_byte **rows = NULL;
1349 bool retval = false;
1350 png_byte **row_pointers = NULL;
1351 FILE *fp = fopen(file_name, "rb");
1356 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1357 if (png_ptr == NULL)
1360 info_ptr = png_create_info_struct(png_ptr);
1361 if (info_ptr == NULL)
1364 if (setjmp(png_jmpbuf(png_ptr)))
1367 png_init_io(png_ptr, fp);
1368 png_read_png(png_ptr, info_ptr,
1369 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1371 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1372 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1374 if (bit_depth != 8) // transform SHOULD handle this...
1377 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1380 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1383 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1384 row_pointers = png_get_rows(png_ptr, info_ptr);
1390 png_byte *dst = tex.data;
1391 for (int i = height-1; i >= 0; i--)
1393 png_byte *src = row_pointers[i];
1394 for (int j = 0; j < width; j++)
1408 png_byte *dst = tex.data;
1409 int pitch = width * 4;
1410 for (int i = height-1; i >= 0; i--, dst += pitch)
1411 memcpy(dst, row_pointers[i], pitch);
1420 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1427 static bool save_image(const char *file_name)
1429 const char *ptr = strrchr((char *)file_name, '.');
1432 if (strcasecmp(ptr+1, "png") == 0)
1433 return save_png(file_name);
1436 STUBBED("Unsupported image type");
1441 static bool save_png(const char *file_name)
1444 png_structp png_ptr = NULL;
1445 png_infop info_ptr = NULL;
1446 bool retval = false;
1448 fp = fopen(file_name, "wb");
1452 png_bytep *row_pointers = new png_bytep[kContextHeight];
1453 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1454 if ((!screenshot) || (!row_pointers))
1458 glReadPixels(0, 0, kContextWidth, kContextHeight,
1459 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1460 if (glGetError() != GL_NO_ERROR)
1463 for (int i = 0; i < kContextHeight; i++)
1464 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1466 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1467 if (png_ptr == NULL)
1470 info_ptr = png_create_info_struct(png_ptr);
1471 if (info_ptr == NULL)
1474 if (setjmp(png_jmpbuf(png_ptr)))
1477 png_init_io(png_ptr, fp);
1479 if (setjmp(png_jmpbuf(png_ptr)))
1482 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1483 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1484 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1486 png_write_info(png_ptr, info_ptr);
1488 if (setjmp(png_jmpbuf(png_ptr)))
1491 png_write_image(png_ptr, row_pointers);
1493 if (setjmp(png_jmpbuf(png_ptr)))
1496 png_write_end(png_ptr, NULL);
1500 png_destroy_write_struct(&png_ptr, &info_ptr);
1501 delete[] screenshot;
1502 delete[] row_pointers;
1506 unlink(ConvertFileName(file_name));