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.
46 static bool load_image(const char * fname, TGAImageRec & tex);
47 static bool load_png(const char * fname, TGAImageRec & tex);
48 static bool load_jpg(const char * fname, TGAImageRec & tex);
49 static bool save_image(const char * fname);
50 static bool save_png(const char * fname);
55 #pragma comment(lib, "opengl32.lib")
56 #pragma comment(lib, "glu32.lib")
57 #pragma comment(lib, "glaux.lib")
60 extern bool buttons[3];
61 extern float multiplier;
62 extern float screenwidth,screenheight;
64 extern float realmultiplier;
66 extern bool ismotionblur;
67 extern float usermousesensitivity;
69 extern bool floatjump;
70 extern bool cellophane;
72 //extern int terraindetail;
73 //extern int texdetail;
74 extern float terraindetail;
75 extern float texdetail;
76 extern int bloodtoggle;
78 extern bool autoslomo;
80 extern bool musictoggle;
81 extern bool trilinear;
82 extern float gamespeed;
83 extern int difficulty;
84 extern bool damageeffects;
85 extern int numplayers;
87 extern bool invertmouse;
88 extern bool texttoggle;
89 extern bool ambientsound;
90 extern bool mousejump;
92 extern Person player[maxplayers];
94 extern bool stillloading;
95 extern bool showpoints;
96 extern bool alwaysblur;
97 extern bool immediate;
98 extern bool velocityblur;
99 extern bool debugmode;
101 /*extern*/ bool gameFocused;
102 extern int kBitsPerPixel;
103 extern float slomospeed;
104 extern float slomofreq;
105 extern float oldgamespeed;
114 #include "MacCompatibility.h"
117 #include <shellapi.h>
122 #include "res/resource.h"
128 SDL_Rect **resolutions = NULL;
129 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
130 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
131 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
132 static SDL_Rect *hardcoded_resolutions[] = {
141 unsigned int resolutionDepths[8][2] = {0};
143 bool selectDetail(int & width, int & height, int & bpp, int & detail);
144 int closestResolution(int width, int height);
145 int resolutionID(int width, int height);
147 void ReportError (char * strError);
149 void SetupDSpFullScreen();
152 void DrawGL(Game & game);
154 void CreateGLWindow (void);
155 Boolean SetUp (Game & game);
156 void DoKey (SInt8 theKey, SInt8 theCode);
157 void DoUpdate (Game & game);
163 // statics/globals (internal only) ------------------------------------------
165 typedef struct tagPOINT {
172 #define GL_FUNC(ret,fn,params,call,rt) \
174 static ret GLAPIENTRY (*p##fn) params = NULL; \
175 ret GLAPIENTRY fn params { rt p##fn call; } \
180 static bool lookup_glsym(const char *funcname, void **func)
182 *func = SDL_GL_GetProcAddress(funcname);
185 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
191 static bool lookup_all_glsyms(void)
194 #define GL_FUNC(ret,fn,params,call,rt) \
195 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
201 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
208 void sdlGetCursorPos(POINT *pt)
211 SDL_GetMouseState(&x, &y);
215 #define GetCursorPos(x) sdlGetCursorPos(x)
216 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
217 #define ScreenToClient(x, pt)
218 #define ClientToScreen(x, pt)
219 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
225 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
226 static HINSTANCE g_appInstance;
227 static HWND g_windowHandle;
231 static bool g_button, fullscreen = true;
242 kForegroundSleep = 10,
243 kBackgroundSleep = 10000
250 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
253 char gcstrMode [256] = "";
255 UInt32 gSleepTime = kForegroundSleep;
256 Boolean gDone = false, gfFrontProcess = true;
261 static int _argc = 0;
262 static char **_argv = NULL;
264 bool cmdline(const char *cmd)
266 for (int i = 1; i < _argc; i++)
268 char *arg = _argv[i];
271 if (strcasecmp(arg, cmd) == 0)
279 // --------------------------------------------------------------------------
281 void ReportError (char * strError)
283 #ifdef WIN32 // !!! FIXME. --ryan.
284 throw std::exception( strError);
287 /* char errMsgCStr [256];
290 sprintf (errMsgCStr, "%s", strError);
292 // out as debug string
293 CToPStr (strErr, errMsgCStr);
298 void SetupDSpFullScreen ()
305 DEVMODE dmScreenSettings;
306 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
307 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
308 dmScreenSettings.dmPelsWidth = kContextWidth;
309 dmScreenSettings.dmPelsHeight = kContextHeight;
310 dmScreenSettings.dmBitsPerPel = kBitsPerPixel;
311 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
314 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
316 ReportError( "Could not set display mode");
333 ChangeDisplaySettings( NULL, 0);
341 //-----------------------------------------------------------------------------------------------------------------------
345 void DrawGL (Game & game)
356 static KeyMap g_theKeys;
358 void SetKey( int key)
360 g_theKeys[ key >> 3] |= (1 << (key & 7));
363 void ClearKey( int key)
365 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
368 void GetKeys( unsigned char theKeys[16])
370 memcpy( theKeys, &g_theKeys, 16);
379 static void initSDLKeyTable(void) {}
381 #define MAX_SDLKEYS SDLK_LAST
382 static unsigned short KeyTable[MAX_SDLKEYS];
384 static void initSDLKeyTable(void)
386 memset(KeyTable, 0xFF, sizeof (KeyTable));
387 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
388 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
389 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
390 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
391 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
392 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
393 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
394 KeyTable[SDLK_END] = MAC_END_KEY;
395 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
396 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
397 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
398 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
399 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
400 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
401 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
402 KeyTable[SDLK_0] = MAC_0_KEY;
403 KeyTable[SDLK_1] = MAC_1_KEY;
404 KeyTable[SDLK_2] = MAC_2_KEY;
405 KeyTable[SDLK_3] = MAC_3_KEY;
406 KeyTable[SDLK_4] = MAC_4_KEY;
407 KeyTable[SDLK_5] = MAC_5_KEY;
408 KeyTable[SDLK_6] = MAC_6_KEY;
409 KeyTable[SDLK_7] = MAC_7_KEY;
410 KeyTable[SDLK_8] = MAC_8_KEY;
411 KeyTable[SDLK_9] = MAC_9_KEY;
412 KeyTable[SDLK_a] = MAC_A_KEY;
413 KeyTable[SDLK_b] = MAC_B_KEY;
414 KeyTable[SDLK_c] = MAC_C_KEY;
415 KeyTable[SDLK_d] = MAC_D_KEY;
416 KeyTable[SDLK_e] = MAC_E_KEY;
417 KeyTable[SDLK_f] = MAC_F_KEY;
418 KeyTable[SDLK_g] = MAC_G_KEY;
419 KeyTable[SDLK_h] = MAC_H_KEY;
420 KeyTable[SDLK_i] = MAC_I_KEY;
421 KeyTable[SDLK_j] = MAC_J_KEY;
422 KeyTable[SDLK_k] = MAC_K_KEY;
423 KeyTable[SDLK_l] = MAC_L_KEY;
424 KeyTable[SDLK_m] = MAC_M_KEY;
425 KeyTable[SDLK_n] = MAC_N_KEY;
426 KeyTable[SDLK_o] = MAC_O_KEY;
427 KeyTable[SDLK_p] = MAC_P_KEY;
428 KeyTable[SDLK_q] = MAC_Q_KEY;
429 KeyTable[SDLK_r] = MAC_R_KEY;
430 KeyTable[SDLK_s] = MAC_S_KEY;
431 KeyTable[SDLK_t] = MAC_T_KEY;
432 KeyTable[SDLK_u] = MAC_U_KEY;
433 KeyTable[SDLK_v] = MAC_V_KEY;
434 KeyTable[SDLK_w] = MAC_W_KEY;
435 KeyTable[SDLK_x] = MAC_X_KEY;
436 KeyTable[SDLK_y] = MAC_Y_KEY;
437 KeyTable[SDLK_z] = MAC_Z_KEY;
438 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
439 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
440 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
441 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
442 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
443 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
444 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
445 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
446 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
447 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
448 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
449 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
450 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
451 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
452 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
453 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
454 KeyTable[SDLK_F1] = MAC_F1_KEY;
455 KeyTable[SDLK_F2] = MAC_F2_KEY;
456 KeyTable[SDLK_F3] = MAC_F3_KEY;
457 KeyTable[SDLK_F4] = MAC_F4_KEY;
458 KeyTable[SDLK_F5] = MAC_F5_KEY;
459 KeyTable[SDLK_F6] = MAC_F6_KEY;
460 KeyTable[SDLK_F7] = MAC_F7_KEY;
461 KeyTable[SDLK_F8] = MAC_F8_KEY;
462 KeyTable[SDLK_F9] = MAC_F9_KEY;
463 KeyTable[SDLK_F10] = MAC_F10_KEY;
464 KeyTable[SDLK_F11] = MAC_F11_KEY;
465 KeyTable[SDLK_F12] = MAC_F12_KEY;
466 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
467 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
468 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
469 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
470 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
471 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
472 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
473 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
474 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
475 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
476 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
479 static inline int clamp_sdl_mouse_button(Uint8 button)
481 if (button == 2) // right mouse button is button 3 in SDL.
483 else if (button == 3)
486 if ((button >= 1) && (button <= 3))
491 static void sdlEventProc(const SDL_Event &e, Game &game)
494 bool skipkey = false;
499 case SDL_MOUSEMOTION:
500 game.deltah += e.motion.xrel;
501 game.deltav += e.motion.yrel;
504 case SDL_MOUSEBUTTONDOWN:
506 val = clamp_sdl_mouse_button(e.button.button);
507 if ((val >= 0) && (val <= 2))
516 case SDL_MOUSEBUTTONUP:
518 val = clamp_sdl_mouse_button(e.button.button);
519 if ((val >= 0) && (val <= 2))
523 buttons[val] = false;
529 if (e.key.keysym.sym == SDLK_g)
531 if (e.key.keysym.mod & KMOD_CTRL)
534 SDL_GrabMode mode = SDL_GRAB_ON;
535 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
537 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
538 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
540 SDL_WM_GrabInput(mode);
544 else if (e.key.keysym.sym == SDLK_RETURN)
546 if (e.key.keysym.mod & KMOD_ALT)
549 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
553 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
555 if (KeyTable[e.key.keysym.sym] != 0xffff)
556 SetKey(KeyTable[e.key.keysym.sym]);
559 mod = SDL_GetModState();
561 SetKey(MAC_CONTROL_KEY);
563 SetKey(MAC_OPTION_KEY);
565 SetKey(MAC_COMMAND_KEY);
566 if (mod & KMOD_SHIFT)
567 SetKey(MAC_SHIFT_KEY);
569 SetKey(MAC_CAPS_LOCK_KEY);
574 if (e.key.keysym.sym < SDLK_LAST)
576 if (KeyTable[e.key.keysym.sym] != 0xffff)
577 ClearKey(KeyTable[e.key.keysym.sym]);
580 mod = SDL_GetModState();
581 if ((mod & KMOD_CTRL) == 0)
582 ClearKey(MAC_CONTROL_KEY);
583 if ((mod & KMOD_ALT) == 0)
584 ClearKey(MAC_OPTION_KEY);
585 if ((mod & KMOD_SHIFT) == 0)
586 ClearKey(MAC_SHIFT_KEY);
587 if ((mod & KMOD_CAPS) == 0)
588 ClearKey(MAC_CAPS_LOCK_KEY);
594 // --------------------------------------------------------------------------
596 static Point gMidPoint;
598 Boolean SetUp (Game & game)
604 randSeed = UpTime().lo;
607 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
610 usermousesensitivity=1;
639 game.crouchkey=MAC_SHIFT_KEY;
640 game.jumpkey=MAC_SPACE_KEY;
641 game.leftkey=MAC_A_KEY;
642 game.forwardkey=MAC_W_KEY;
643 game.backkey=MAC_S_KEY;
644 game.rightkey=MAC_D_KEY;
645 game.drawkey=MAC_E_KEY;
646 game.throwkey=MAC_Q_KEY;
647 game.attackkey=MAC_MOUSEBUTTON1;
648 game.chatkey=MAC_T_KEY;
654 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
657 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
658 opstream << "Screenwidth:\n";
659 opstream << kContextWidth;
660 opstream << "\nScreenheight:\n";
661 opstream << kContextHeight;
662 opstream << "\nMouse sensitivity:\n";
663 opstream << usermousesensitivity;
664 opstream << "\nBlur(0,1):\n";
665 opstream << ismotionblur;
666 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
668 opstream << "\nFloating jump:\n";
669 opstream << floatjump;
670 opstream << "\nMouse jump:\n";
671 opstream << mousejump;
672 opstream << "\nAmbient sound:\n";
673 opstream << ambientsound;
674 opstream << "\nBlood (0,1,2):\n";
675 opstream << bloodtoggle;
676 opstream << "\nAuto slomo:\n";
677 opstream << autoslomo;
678 opstream << "\nFoliage:\n";
680 opstream << "\nMusic:\n";
681 opstream << musictoggle;
682 opstream << "\nTrilinear:\n";
683 opstream << trilinear;
684 opstream << "\nDecals(shadows,blood puddles,etc):\n";
686 opstream << "\nInvert mouse:\n";
687 opstream << invertmouse;
688 opstream << "\nGamespeed:\n";
689 opstream << gamespeed;
690 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
691 opstream << difficulty;
692 opstream << "\nDamage effects(blackout, doublevision):\n";
693 opstream << damageeffects;
694 opstream << "\nText:\n";
695 opstream << texttoggle;
696 opstream << "\nDebug:\n";
697 opstream << debugmode;
698 opstream << "\nVBL Sync:\n";
700 opstream << "\nShow Points:\n";
701 opstream << showpoints;
702 opstream << "\nAlways Blur:\n";
703 opstream << alwaysblur;
704 opstream << "\nImmediate mode (turn on on G5):\n";
705 opstream << immediate;
706 opstream << "\nVelocity blur:\n";
707 opstream << velocityblur;
708 opstream << "\nVolume:\n";
710 opstream << "\nForward key:\n";
711 opstream << KeyToChar(game.forwardkey);
712 opstream << "\nBack key:\n";
713 opstream << KeyToChar(game.backkey);
714 opstream << "\nLeft key:\n";
715 opstream << KeyToChar(game.leftkey);
716 opstream << "\nRight key:\n";
717 opstream << KeyToChar(game.rightkey);
718 opstream << "\nJump key:\n";
719 opstream << KeyToChar(game.jumpkey);
720 opstream << "\nCrouch key:\n";
721 opstream << KeyToChar(game.crouchkey);
722 opstream << "\nDraw key:\n";
723 opstream << KeyToChar(game.drawkey);
724 opstream << "\nThrow key:\n";
725 opstream << KeyToChar(game.throwkey);
726 opstream << "\nAttack key:\n";
727 opstream << KeyToChar(game.attackkey);
728 opstream << "\nChat key:\n";
729 opstream << KeyToChar(game.chatkey);
734 ipstream.ignore(256,'\n');
735 ipstream >> kContextWidth;
736 ipstream.ignore(256,'\n');
737 ipstream.ignore(256,'\n');
738 ipstream >> kContextHeight;
739 ipstream.ignore(256,'\n');
740 ipstream.ignore(256,'\n');
741 ipstream >> usermousesensitivity;
742 ipstream.ignore(256,'\n');
743 ipstream.ignore(256,'\n');
745 ismotionblur = (i != 0);
746 ipstream.ignore(256,'\n');
747 ipstream.ignore(256,'\n');
749 if(detail!=0)kBitsPerPixel=32;
750 else kBitsPerPixel=16;
751 ipstream.ignore(256,'\n');
752 ipstream.ignore(256,'\n');
754 floatjump = (i != 0);
755 ipstream.ignore(256,'\n');
756 ipstream.ignore(256,'\n');
758 mousejump = (i != 0);
759 ipstream.ignore(256,'\n');
760 ipstream.ignore(256,'\n');
762 ambientsound = (i != 0);
763 ipstream.ignore(256,'\n');
764 ipstream.ignore(256,'\n');
765 ipstream >> bloodtoggle;
766 ipstream.ignore(256,'\n');
767 ipstream.ignore(256,'\n');
769 autoslomo = (i != 0);
770 ipstream.ignore(256,'\n');
771 ipstream.ignore(256,'\n');
774 ipstream.ignore(256,'\n');
775 ipstream.ignore(256,'\n');
777 musictoggle = (i != 0);
778 ipstream.ignore(256,'\n');
779 ipstream.ignore(256,'\n');
781 trilinear = (i != 0);
782 ipstream.ignore(256,'\n');
783 ipstream.ignore(256,'\n');
786 ipstream.ignore(256,'\n');
787 ipstream.ignore(256,'\n');
789 invertmouse = (i != 0);
790 ipstream.ignore(256,'\n');
791 ipstream.ignore(256,'\n');
792 ipstream >> gamespeed;
793 oldgamespeed=gamespeed;
798 ipstream.ignore(256,'\n');
799 ipstream.ignore(256,'\n');
800 ipstream >> difficulty;
801 ipstream.ignore(256,'\n');
802 ipstream.ignore(256,'\n');
804 damageeffects = (i != 0);
805 ipstream.ignore(256,'\n');
806 ipstream.ignore(256,'\n');
808 texttoggle = (i != 0);
809 ipstream.ignore(256,'\n');
810 ipstream.ignore(256,'\n');
812 debugmode = (i != 0);
813 ipstream.ignore(256,'\n');
814 ipstream.ignore(256,'\n');
817 ipstream.ignore(256,'\n');
818 ipstream.ignore(256,'\n');
820 showpoints = (i != 0);
821 ipstream.ignore(256,'\n');
822 ipstream.ignore(256,'\n');
824 alwaysblur = (i != 0);
825 ipstream.ignore(256,'\n');
826 ipstream.ignore(256,'\n');
828 immediate = (i != 0);
829 ipstream.ignore(256,'\n');
830 ipstream.ignore(256,'\n');
832 velocityblur = (i != 0);
833 ipstream.ignore(256,'\n');
834 ipstream.ignore(256,'\n');
836 ipstream.ignore(256,'\n');
837 ipstream.ignore(256,'\n');
839 game.forwardkey=CharToKey(string);
840 ipstream.ignore(256,'\n');
841 ipstream.ignore(256,'\n');
843 game.backkey=CharToKey(string);
844 ipstream.ignore(256,'\n');
845 ipstream.ignore(256,'\n');
847 game.leftkey=CharToKey(string);
848 ipstream.ignore(256,'\n');
849 ipstream.ignore(256,'\n');
851 game.rightkey=CharToKey(string);
852 ipstream.ignore(256,'\n');
853 ipstream.ignore(256,'\n');
855 game.jumpkey=CharToKey(string);
856 ipstream.ignore(256,'\n');
857 ipstream.ignore(256,'\n');
859 game.crouchkey=CharToKey(string);
860 ipstream.ignore(256,'\n');
861 ipstream.ignore(256,'\n');
863 game.drawkey=CharToKey(string);
864 ipstream.ignore(256,'\n');
865 ipstream.ignore(256,'\n');
867 game.throwkey=CharToKey(string);
868 ipstream.ignore(256,'\n');
869 ipstream.ignore(256,'\n');
871 game.attackkey=CharToKey(string);
872 ipstream.ignore(256,'\n');
873 ipstream.ignore(256,'\n');
875 game.chatkey=CharToKey(string);
878 if(detail>2)detail=2;
879 if(detail<0)detail=0;
880 if(screenwidth<0)screenwidth=640;
881 if(screenheight<0)screenheight=480;
882 #if !USE_SDL // we'll take anything that works.
883 if(screenwidth>3000)screenwidth=640;
884 if(screenheight>3000)screenheight=480;
887 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
892 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
894 SetupDSpFullScreen();
897 if (!SDL_WasInit(SDL_INIT_VIDEO))
899 if (SDL_Init(SDL_INIT_VIDEO) == -1)
901 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
905 if (SDL_GL_LoadLibrary(NULL) == -1)
907 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
912 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
913 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
914 res = hardcoded_resolutions;
916 // reverse list (it was sorted biggest to smallest by SDL)...
918 for (count = 0; res[count]; count++)
920 if ((res[count]->w < 640) || (res[count]->h < 480))
921 break; // sane lower limit.
924 static SDL_Rect *resolutions_block = NULL;
925 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
926 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
927 if ((resolutions_block == NULL) || (resolutions == NULL))
930 fprintf(stderr, "Out of memory!\n");
934 resolutions[count--] = NULL;
935 for (int i = 0; count >= 0; i++, count--)
937 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
938 resolutions[count] = &resolutions_block[count];
941 if (cmdline("showresolutions"))
943 printf("Resolutions we think are okay:\n");
944 for (int i = 0; resolutions[i]; i++)
945 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
949 Uint32 sdlflags = SDL_OPENGL;
950 if (!cmdline("windowed"))
951 sdlflags |= SDL_FULLSCREEN;
953 SDL_WM_SetCaption("Lugaru", "Lugaru");
957 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
959 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
961 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
962 fprintf(stderr, "forcing 640x480...\n");
964 kContextHeight = 480;
965 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
967 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
968 fprintf(stderr, "forcing 640x480 windowed mode...\n");
969 sdlflags &= ~SDL_FULLSCREEN;
970 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
972 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
979 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
981 fprintf(stderr, "Failed to get double buffered GL context!\n");
986 if (!lookup_all_glsyms())
992 if (!cmdline("nomousegrab"))
993 SDL_WM_GrabInput(SDL_GRAB_ON);
995 #elif (defined WIN32)
996 //------------------------------------------------------------------
999 RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
1000 DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
1001 DWORD dwExStyle = WS_EX_APPWINDOW;
1005 dwStyle |= WS_POPUP;
1010 dwStyle |= WS_OVERLAPPEDWINDOW;
1011 dwExStyle |= WS_EX_WINDOWEDGE;
1014 AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
1018 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
1019 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
1022 g_windowHandle=CreateWindowEx(
1024 g_wndClassName, "Lugaru", dwStyle,
1026 // kContextWidth, kContextHeight,
1027 r.right - r.left + 1, r.bottom - r.top + 1,
1028 NULL,NULL,g_appInstance,NULL );
1029 if (!g_windowHandle)
1031 ReportError("Could not create window");
1035 //------------------------------------------------------------------
1038 static PIXELFORMATDESCRIPTOR pfd =
1040 sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1041 1, // Version Number
1042 PFD_DRAW_TO_WINDOW | // Format Must Support Window
1043 PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
1044 PFD_DOUBLEBUFFER, // Must Support Double Buffering
1045 PFD_TYPE_RGBA, // Request An RGBA Format
1046 kBitsPerPixel, // Select Our Color Depth
1047 0, 0, 0, 0, 0, 0, // Color Bits Ignored
1048 0, // No Alpha Buffer
1049 0, // Shift Bit Ignored
1050 0, // No Accumulation Buffer
1051 0, 0, 0, 0, // Accumulation Bits Ignored
1052 16, // 16Bit Z-Buffer (Depth Buffer)
1053 0, // No Stencil Buffer
1054 0, // No Auxiliary Buffer
1055 PFD_MAIN_PLANE, // Main Drawing Layer
1057 0, 0, 0 // Layer Masks Ignored
1060 if (!(hDC = GetDC( g_windowHandle)))
1061 ReportError( "Could not get device context");
1064 if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
1066 ReportError( "Could not find appropriate pixel format");
1070 if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
1072 ReportError( "Could not retrieve pixel format");
1076 if (!SetPixelFormat( hDC, PixelFormat, &pfd))
1078 ReportError( "Could not set pixel format");
1082 if (!(hRC = wglCreateContext(hDC)))
1084 ReportError( "Could not create rendering context");
1088 if (!wglMakeCurrent(hDC, hRC))
1090 ReportError( "Could not activate rendering context");
1096 // Place the window above all topmost windows
1097 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1098 SWP_NOMOVE | SWP_NOSIZE );
1101 SetForegroundWindow(g_windowHandle);
1102 SetFocus(g_windowHandle);
1105 glClear( GL_COLOR_BUFFER_BIT );
1109 glDisable( GL_ALPHA_TEST);
1110 glDisable( GL_BLEND);
1111 glDisable( GL_DEPTH_TEST);
1112 // glDisable( GL_DITHER);
1114 glDisable( GL_LIGHTING);
1115 glDisable( GL_LOGIC_OP);
1116 glDisable( GL_STENCIL_TEST);
1117 glDisable( GL_TEXTURE_1D);
1118 glDisable( GL_TEXTURE_2D);
1119 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1120 glPixelTransferi( GL_RED_SCALE, 1);
1121 glPixelTransferi( GL_RED_BIAS, 0);
1122 glPixelTransferi( GL_GREEN_SCALE, 1);
1123 glPixelTransferi( GL_GREEN_BIAS, 0);
1124 glPixelTransferi( GL_BLUE_SCALE, 1);
1125 glPixelTransferi( GL_BLUE_BIAS, 0);
1126 glPixelTransferi( GL_ALPHA_SCALE, 1);
1127 glPixelTransferi( GL_ALPHA_BIAS, 0);
1129 // set initial rendering states
1130 glShadeModel( GL_SMOOTH);
1131 glClearDepth( 1.0f);
1132 glDepthFunc( GL_LEQUAL);
1133 glDepthMask( GL_TRUE);
1134 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1135 glEnable( GL_DEPTH_TEST);
1136 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1137 glCullFace( GL_FRONT);
1138 glEnable( GL_CULL_FACE);
1139 glEnable( GL_LIGHTING);
1140 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1141 glEnable( GL_DITHER);
1142 glEnable( GL_COLOR_MATERIAL);
1143 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1144 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1145 glAlphaFunc( GL_GREATER, 0.5f);
1148 if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1149 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1150 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1152 ReportError("DevIL version is different...exiting!\n");
1160 ilutRenderer(ILUT_OPENGL);
1162 ilEnable(IL_ORIGIN_SET);
1163 ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1166 GLint width = kContextWidth;
1167 GLint height = kContextHeight;
1168 gMidPoint.h = width / 2;
1169 gMidPoint.v = height / 2;
1171 screenheight=height;
1173 game.newdetail=detail;
1174 game.newscreenwidth=screenwidth;
1175 game.newscreenheight=screenheight;
1183 static void DoMouse(Game & game)
1186 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1188 game.deltah *= usermousesensitivity;
1189 game.deltav *= usermousesensitivity;
1190 game.mousecoordh += game.deltah;
1191 game.mousecoordv += game.deltav;
1192 if (game.mousecoordh < 0)
1193 game.mousecoordh = 0;
1194 else if (game.mousecoordh >= kContextWidth)
1195 game.mousecoordh = kContextWidth - 1;
1196 if (game.mousecoordv < 0)
1197 game.mousecoordv = 0;
1198 else if (game.mousecoordv >= kContextHeight)
1199 game.mousecoordv = kContextHeight - 1;
1202 static Point lastMouse = {-1,-1};
1207 ScreenToClient(g_windowHandle, &pos);
1208 globalMouse.h = pos.x;
1209 globalMouse.v = pos.y;
1211 if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1218 static Point virtualMouse = {0,0};
1219 delta = globalMouse;
1221 delta.h -= lastMouse.h;
1222 delta.v -= lastMouse.v;
1223 lastMouse.h = pos.x;
1224 lastMouse.v = pos.y;
1226 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1227 game.deltah=delta.h*usermousesensitivity;
1228 game.deltav=delta.v*usermousesensitivity;
1229 game.mousecoordh=globalMouse.h;
1230 game.mousecoordv=globalMouse.v;
1235 if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1236 pos.x = gMidPoint.h;
1237 pos.y = gMidPoint.v;
1238 ClientToScreen(g_windowHandle, &pos);
1239 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1240 SetCursorPos(pos.x, pos.y);
1241 lastMouse = gMidPoint;
1250 // --------------------------------------------------------------------------
1252 void DoKey (SInt8 theKey, SInt8 theCode)
1257 // --------------------------------------------------------------------------
1261 void DoFrameRate (int update)
1263 static long frames = 0;
1265 static AbsoluteTime time = {0,0};
1266 static AbsoluteTime frametime = {0,0};
1267 AbsoluteTime currTime = UpTime ();
1268 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1270 if (0 > deltaTime) // if negative microseconds
1271 deltaTime /= -1000000.0;
1272 else // else milliseconds
1273 deltaTime /= 1000.0;
1275 multiplier=deltaTime;
1276 if(multiplier<.001)multiplier=.001;
1277 if(multiplier>10)multiplier=10;
1278 if(update)frametime = currTime; // reset for next time interval
1280 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1282 if (0 > deltaTime) // if negative microseconds
1283 deltaTime /= -1000000.0;
1284 else // else milliseconds
1285 deltaTime /= 1000.0;
1287 if (0.001 <= deltaTime) // has update interval passed
1290 time = currTime; // reset for next time interval
1297 void DoUpdate (Game & game)
1299 static float sps=200;
1301 static float oldmult;
1304 if(multiplier>.6)multiplier=.6;
1306 game.fps=1/multiplier;
1308 count = multiplier*sps;
1310 //if(count>10)count=10;
1312 realmultiplier=multiplier;
1313 multiplier*=gamespeed;
1314 if(difficulty==1)multiplier*=.9;
1315 if(difficulty==0)multiplier*=.8;
1317 if(game.loading==4)multiplier*=.00001;
1319 if(slomo&&!mainmenu)multiplier*=slomospeed;
1320 //if(freeze)multiplier*=0.00001;
1322 multiplier/=(float)count;
1328 for(int i=0;i<count;i++)
1334 game.TickOnceAfter();
1335 /* - Debug code to test how many channels were active on average per frame
1336 static long frames = 0;
1338 static AbsoluteTime start = {0,0};
1339 AbsoluteTime currTime = UpTime ();
1340 static int num_channels = 0;
1342 num_channels += FSOUND_GetChannelsPlaying();
1343 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1345 if (0 > deltaTime) // if negative microseconds
1346 deltaTime /= -1000000.0;
1347 else // else milliseconds
1348 deltaTime /= 1000.0;
1355 float avg_channels = (float)num_channels / (float)frames;
1357 ofstream opstream("log.txt",ios::app);
1358 opstream << "Average frame count: ";
1360 opstream << " frames - ";
1361 opstream << avg_channels;
1362 opstream << " per frame.\n";
1372 // --------------------------------------------------------------------------
1387 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1388 #include "glstubs.h"
1390 // cheat here...static destructors are calling glDeleteTexture() after
1391 // the context is destroyed and libGL unloaded by SDL_Quit().
1392 pglDeleteTextures = glDeleteTextures_doNothing;
1394 #elif (defined WIN32)
1397 wglMakeCurrent( NULL, NULL);
1398 wglDeleteContext( hRC);
1404 ReleaseDC( g_windowHandle, hDC);
1410 ShowWindow( g_windowHandle, SW_HIDE );
1411 DestroyWindow( g_windowHandle);
1412 g_windowHandle = NULL;
1420 // --------------------------------------------------------------------------
1422 static bool g_focused = true;
1425 static bool IsFocused()
1431 if (GetActiveWindow() != g_windowHandle)
1434 if (IsIconic( g_windowHandle))
1442 static void launch_web_browser(const char *url)
1445 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1447 #elif (defined(__APPLE__) && defined(__MACH__))
1448 const char *fmt = "open '%s'";
1449 const size_t len = strlen(fmt) + strlen(url) + 16;
1450 char *buf = new char[len];
1451 snprintf(buf, len, fmt, url);
1455 #elif PLATFORM_LINUX
1456 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1457 const size_t len = strlen(fmt) + strlen(url) + 16;
1458 char *buf = new char[len];
1459 snprintf(buf, len, fmt, url);
1467 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1468 static char *findBinaryInPath(const char *bin, char *envr)
1470 size_t alloc_size = 0;
1478 ptr = strchr(start, ':'); /* find next $PATH separator. */
1482 size = strlen(start) + strlen(bin) + 2;
1483 if (size > alloc_size)
1485 char *x = (char *) realloc(exe, size);
1497 /* build full binary path... */
1499 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1503 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1505 strcpy(exe, start); /* i'm lazy. piss off. */
1509 start = ptr + 1; /* start points to beginning of next element. */
1510 } while (ptr != NULL);
1515 return(NULL); /* doesn't exist in path. */
1516 } /* findBinaryInPath */
1519 char *calcBaseDir(const char *argv0)
1521 /* If there isn't a path on argv0, then look through the $PATH for it. */
1525 char *ptr = strrchr((char *)argv0, '/');
1526 if (strchr(argv0, '/'))
1528 retval = strdup(argv0);
1530 *(strrchr(retval, '/')) = '\0';
1534 envr = getenv("PATH");
1535 if (!envr) return NULL;
1536 envr = strdup(envr);
1537 if (!envr) return NULL;
1538 retval = findBinaryInPath(argv0, envr);
1543 static inline void chdirToAppPath(const char *argv0)
1545 char *dir = calcBaseDir(argv0);
1548 #if (defined(__APPLE__) && defined(__MACH__))
1549 // Chop off /Contents/MacOS if it's at the end of the string, so we
1550 // land in the base of the app bundle.
1551 const size_t len = strlen(dir);
1552 const char *bundledirs = "/Contents/MacOS";
1553 const size_t bundledirslen = strlen(bundledirs);
1554 if (len > bundledirslen)
1556 char *ptr = (dir + len) - bundledirslen;
1557 if (strcasecmp(ptr, bundledirs) == 0)
1568 int main(int argc, char **argv)
1573 chdirToAppPath(argv[0]);
1578 #ifndef WIN32 // this is in WinMain, too.
1579 memset( &g_theKeys, 0, sizeof( KeyMap));
1586 bool regnow = false;
1591 //ofstream os("error.txt");
1593 //ofstream os("log.txt");
1599 while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1605 // check windows messages
1611 while( SDL_PollEvent( &e ) )
1613 if( e.type == SDL_QUIT )
1618 sdlEventProc(e, game);
1621 #elif (defined WIN32)
1624 while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1626 if( msg.message == WM_QUIT )
1633 TranslateMessage( &msg );
1634 DispatchMessage( &msg );
1646 // allow game chance to pause
1647 gameFocused = false;
1651 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1655 //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1656 /*if (GetMessage( &msg, NULL, 0, 0 ))
1658 TranslateMessage(&msg);
1659 DispatchMessage(&msg);
1661 if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1665 // handle the error and possibly exit
1670 TranslateMessage(&msg);
1671 DispatchMessage(&msg);
1675 STUBBED("give up CPU but sniff the event queue");
1680 regnow = game.registernow;
1685 // if(game.registernow){
1688 #if (defined(__APPLE__) && defined(__MACH__))
1689 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1690 #elif PLATFORM_LINUX
1691 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1693 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1697 #if PLATFORM_LINUX // (this may not be necessary any more.)
1698 _exit(0); // !!! FIXME: hack...crashes on exit!
1702 catch (const std::exception& error)
1706 std::string e = "Caught exception: ";
1711 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1721 // --------------------------------------------------------------------------
1724 #define MAX_WINKEYS 256
1725 static unsigned short KeyTable[MAX_WINKEYS]=
1728 MAC_MOUSEBUTTON1, // VK_LBUTTON (1)
1729 MAC_MOUSEBUTTON2, // VK_RBUTTON (2)
1730 0xffff, // VK_CANCEL (3)
1731 0xffff, // VK_MBUTTON (4)
1735 MAC_DELETE_KEY, // VK_BACK (8)
1736 MAC_TAB_KEY, // VK_TAB (9)
1739 0xffff, // VK_CLEAR (12)
1740 MAC_RETURN_KEY, // VK_RETURN (13)
1743 MAC_SHIFT_KEY, // VK_SHIFT (16)
1744 MAC_CONTROL_KEY, // VK_CONTROL (17)
1745 MAC_OPTION_KEY, // VK_MENU (18)
1746 0xffff, // VK_PAUSE (19)
1747 MAC_CAPS_LOCK_KEY, // #define VK_CAPITAL (20)
1754 MAC_ESCAPE_KEY, // VK_ESCAPE (27)
1759 MAC_SPACE_KEY, // VK_SPACE (32)
1760 MAC_PAGE_UP_KEY, // VK_PRIOR (33)
1761 MAC_PAGE_DOWN_KEY, // VK_NEXT (34)
1762 MAC_END_KEY, // VK_END (35)
1763 MAC_HOME_KEY, // VK_HOME (36)
1764 MAC_ARROW_LEFT_KEY, // VK_LEFT (37)
1765 MAC_ARROW_UP_KEY, // VK_UP (38)
1766 MAC_ARROW_RIGHT_KEY, // VK_RIGHT (39)
1767 MAC_ARROW_DOWN_KEY, // VK_DOWN (40)
1768 0xffff, // VK_SELECT (41)
1769 0xffff, // VK_PRINT (42)
1770 0xffff, // VK_EXECUTE (43)
1771 0xffff, // VK_SNAPSHOT (44)
1772 MAC_INSERT_KEY, // VK_INSERT (45)
1773 MAC_DEL_KEY, // VK_DELETE (46)
1774 0xffff, // VK_HELP (47)
1775 MAC_0_KEY, // VK_0 (48)
1776 MAC_1_KEY, // VK_1 (49)
1777 MAC_2_KEY, // VK_2 (50)
1778 MAC_3_KEY, // VK_3 (51)
1779 MAC_4_KEY, // VK_4 (52)
1780 MAC_5_KEY, // VK_5 (53)
1781 MAC_6_KEY, // VK_6 (54)
1782 MAC_7_KEY, // VK_7 (55)
1783 MAC_8_KEY, // VK_8 (56)
1784 MAC_9_KEY, // VK_9 (57)
1792 MAC_A_KEY, // VK_A (65)
1793 MAC_B_KEY, // VK_B (66)
1794 MAC_C_KEY, // VK_C (67)
1795 MAC_D_KEY, // VK_D (68)
1796 MAC_E_KEY, // VK_E (69)
1797 MAC_F_KEY, // VK_F (70)
1798 MAC_G_KEY, // VK_G (71)
1799 MAC_H_KEY, // VK_H (72)
1800 MAC_I_KEY, // VK_I (73)
1801 MAC_J_KEY, // VK_J (74)
1802 MAC_K_KEY, // VK_K (75)
1803 MAC_L_KEY, // VK_L (76)
1804 MAC_M_KEY, // VK_M (77)
1805 MAC_N_KEY, // VK_N (78)
1806 MAC_O_KEY, // VK_O (79)
1807 MAC_P_KEY, // VK_P (80)
1808 MAC_Q_KEY, // VK_Q (81)
1809 MAC_R_KEY, // VK_R (82)
1810 MAC_S_KEY, // VK_S (83)
1811 MAC_T_KEY, // VK_T (84)
1812 MAC_U_KEY, // VK_U (85)
1813 MAC_V_KEY, // VK_V (86)
1814 MAC_W_KEY, // VK_W (87)
1815 MAC_X_KEY, // VK_X (88)
1816 MAC_Y_KEY, // VK_Y (89)
1817 MAC_Z_KEY, // VK_Z (90)
1823 MAC_NUMPAD_0_KEY, // VK_NUMPAD0 (96)
1824 MAC_NUMPAD_1_KEY, // VK_NUMPAD1 (97)
1825 MAC_NUMPAD_2_KEY, // VK_NUMPAD2 (98)
1826 MAC_NUMPAD_3_KEY, // VK_NUMPAD3 (99)
1827 MAC_NUMPAD_4_KEY, // VK_NUMPAD4 (100)
1828 MAC_NUMPAD_5_KEY, // VK_NUMPAD5 (101)
1829 MAC_NUMPAD_6_KEY, // VK_NUMPAD6 (102)
1830 MAC_NUMPAD_7_KEY, // VK_NUMPAD7 (103)
1831 MAC_NUMPAD_8_KEY, // VK_NUMPAD8 (104)
1832 MAC_NUMPAD_9_KEY, // VK_NUMPAD9 (105)
1833 MAC_NUMPAD_ASTERISK_KEY, // VK_MULTIPLY (106)
1834 MAC_NUMPAD_PLUS_KEY, // VK_ADD (107)
1835 MAC_NUMPAD_ENTER_KEY, // VK_SEPARATOR (108)
1836 MAC_NUMPAD_MINUS_KEY, // VK_SUBTRACT (109)
1837 MAC_NUMPAD_PERIOD_KEY, // VK_DECIMAL (110)
1838 MAC_NUMPAD_SLASH_KEY, // VK_DIVIDE (111)
1839 MAC_F1_KEY, // VK_F1 (112)
1840 MAC_F2_KEY, // VK_F2 (113)
1841 MAC_F3_KEY, // VK_F3 (114)
1842 MAC_F4_KEY, // VK_F4 (115)
1843 MAC_F5_KEY, // VK_F5 (116)
1844 MAC_F6_KEY, // VK_F6 (117)
1845 MAC_F7_KEY, // VK_F7 (118)
1846 MAC_F8_KEY, // VK_F8 (119)
1847 MAC_F9_KEY, // VK_F9 (120)
1848 MAC_F10_KEY, // VK_F10 (121)
1849 MAC_F11_KEY, // VK_F11 (122)
1850 MAC_F12_KEY, // VK_F12 (123)
1871 0xffff, // VK_NUMLOCK (144)
1872 0xffff, // VK_SCROLL (145)
1887 MAC_SHIFT_KEY, // VK_LSHIFT (160)
1888 MAC_SHIFT_KEY, // VK_RSHIFT (161)
1889 MAC_CONTROL_KEY, // VK_LCONTROL (162)
1890 MAC_CONTROL_KEY, // VK_RCONTROL (163)
1891 MAC_OPTION_KEY, // VK_LMENU (164)
1892 MAC_OPTION_KEY, // VK_RMENU (165)
1913 MAC_SEMICOLON_KEY, // (186)
1914 MAC_PLUS_KEY, // (187)
1915 MAC_COMMA_KEY, // (188)
1916 MAC_MINUS_KEY, // (189)
1917 MAC_PERIOD_KEY, // (190)
1918 MAC_SLASH_KEY, // (191)
1919 MAC_TILDE_KEY, // (192)
1946 MAC_LEFTBRACKET_KEY, // (219)
1947 MAC_BACKSLASH_KEY, // (220)
1948 MAC_RIGHTBRACKET_KEY, // (221)
1949 MAC_APOSTROPHE_KEY, // (222)
1985 void ClipMouseToWindow(HWND window)
1989 GetClientRect(window, &wRect);
1991 ClientToScreen(window, (LPPOINT)&wRect.left);
1992 ClientToScreen(window, (LPPOINT)&wRect.right);
1999 LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
2001 /* this is where we receive all messages concerning this window
2002 * we can either process a message or pass it on to the default
2003 * message handler of windows */
2005 static PAINTSTRUCT ps;
2009 case WM_ACTIVATE: // Watch For Window Activate Message
2011 // Check Minimization State
2012 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
2014 if (LOWORD(wParam) == WA_INACTIVE)
2023 CloseWindow( hWnd );
2025 // The window is now iconified
2026 iconified = GL_TRUE;
2032 g_focused=false; // Program Is Active
2036 SetupDSpFullScreen();
2043 // The window is now iconified
2044 iconified = GL_FALSE;
2047 ShowWindow( hWnd, SW_SHOW );
2048 SetForegroundWindow( hWnd );
2052 ClipMouseToWindow(hWnd);
2053 g_focused=true; // Program Is No Longer Active
2056 return 0; // Return To The Message Loop
2062 // check for Alt-F4 (exit hotkey)
2063 if (wParam == VK_F4)
2065 if (GetKeyState( VK_MENU) & 0x8080)
2071 if (wParam < MAX_WINKEYS)
2073 if (KeyTable[wParam] != 0xffff)
2074 SetKey( KeyTable[wParam]);
2082 if (wParam < MAX_WINKEYS)
2083 if (KeyTable[wParam] != 0xffff)
2084 ClearKey( KeyTable[wParam]);
2091 case WM_SYSDEADCHAR:
2094 case WM_NCLBUTTONDOWN:
2095 case WM_LBUTTONDOWN:
2102 case WM_NCRBUTTONDOWN:
2103 case WM_RBUTTONDOWN:
2109 case WM_NCMBUTTONDOWN:
2110 case WM_MBUTTONDOWN:
2116 case WM_NCLBUTTONUP:
2120 buttons[ 0] = false;
2124 case WM_NCRBUTTONUP:
2127 buttons[ 1] = false;
2131 case WM_NCMBUTTONUP:
2134 buttons[ 2] = false;
2138 case WM_NCLBUTTONDBLCLK:
2139 case WM_NCRBUTTONDBLCLK:
2140 case WM_NCMBUTTONDBLCLK:
2141 case WM_LBUTTONDBLCLK:
2143 case WM_RBUTTONDBLCLK:
2144 case WM_MBUTTONDBLCLK:
2147 case WM_NCMOUSEMOVE:
2149 /* ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2150 ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2151 if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2152 */// goto winmessage;
2155 case WM_SYSCOMMAND: // Intercept System Commands
2157 switch (wParam) // Check System Calls
2159 case SC_SCREENSAVE: // Screensaver Trying To Start?
2160 case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
2161 return 0; // Prevent From Happening
2163 // User trying to access application menu using ALT?
2172 // ReleaseCapture();
2173 // ClipMouseToWindow(hWnd);
2190 PostQuitMessage(0); /* Terminate Application */
2198 // BeginPaint( g_windowHandle,&ps);
2199 // EndPaint( g_windowHandle,&ps);
2206 /* We processed the message and there
2207 * is no processing by Windows necessary */
2209 /* We didn't process the message so let Windows do it */
2210 return DefWindowProc(hWnd,msg,wParam,lParam);
2214 static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2217 memset( &wc, 0, sizeof( wc));
2219 /* Register the window class. */
2220 wc.cbSize = sizeof(wc);
2222 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC); /* Combination of Class Styles */
2223 wc.lpfnWndProc = AppWndProc; /* Adress of Window Procedure */
2224 wc.cbClsExtra = 0; /* Extra Bytes allocated for this Class */
2225 wc.cbWndExtra = 0; /* Extra Bytes allocated for each Window */
2226 wc.hInstance = hFirstInstance; /* Handle of program instance */
2227 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2228 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2229 wc.hbrBackground = NULL;
2230 wc.lpszMenuName = NULL;
2231 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2232 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2234 if (!RegisterClassEx(&wc)) return FALSE; /* Register Class failed */
2241 int resolutionID(int width, int height)
2245 if(width==640 && height==480)whichres=0;
2246 if(width==800 && height==600)whichres=1;
2247 if(width==1024 && height==768)whichres=2;
2248 if(width==1280 && height==1024)whichres=3;
2249 if(width==1600 && height==1200)whichres=4;
2250 if(width==840 && height==524)whichres=5;
2251 if(width==1024 && height==640)whichres=6;
2252 if(width==1344 && height==840)whichres=7;
2253 if(width==1920 && height==1200)whichres=8;
2258 int closestResolution(int width, int height)
2262 if(width>=640 && height>=480)whichres=0;
2263 if(width>=800 && height>=600)whichres=1;
2264 if(width>=1024 && height>=768)whichres=2;
2265 if(width>=1280 && height>=1024)whichres=3;
2266 if(width>=1600 && height>=1200)whichres=4;
2267 if(width==840 && height==524)whichres=5;
2268 if(width==1024 && height==640)whichres=6;
2269 if(width==1344 && height==840)whichres=7;
2270 if(width>=1920 && height>=1200)whichres=8;
2276 bool selectDetail(int & width, int & height, int & bpp, int & detail)
2280 // currently with SDL, we just use whatever is requested
2281 // and don't care. --ryan.
2283 int whichres = closestResolution(width, height);
2287 if(whichres<=0 || whichres>8){
2325 if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2329 else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2333 else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2349 bpp = resolutionDepths[whichres][(detail != 0)];
2356 int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2359 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2362 if (0 == _wcsicmp(cl[1], L"-windowed"))
2368 memset( &g_theKeys, 0, sizeof( KeyMap));
2372 memset(&mode, 0, sizeof(mode));
2373 mode.dmSize = sizeof(mode);
2374 while (EnumDisplaySettings(NULL, i++, &mode))
2376 if (mode.dmBitsPerPel < 16)
2381 int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2383 if (res > -1 && res < 8)
2385 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2390 switch(mode.dmBitsPerPel)
2394 resolutionDepths[res][1] = mode.dmBitsPerPel;
2397 resolutionDepths[res][0] = mode.dmBitsPerPel;
2403 /* if there is no Instance of our program in memory then register the window class */
2404 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2405 return FALSE; /* registration failed! */
2407 g_appInstance=hInstance;
2411 UnregisterClass( g_wndClassName, hInstance);
2418 extern int channels[100];
2419 extern FSOUND_SAMPLE * samp[100];
2420 extern FSOUND_STREAM * strm[20];
2422 extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2424 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2425 if (currSample && currSample == samp[chan])
2427 if (FSOUND_GetPaused(channels[chan]))
2429 FSOUND_StopSound(channels[chan]);
2430 channels[chan] = FSOUND_FREE;
2432 else if (FSOUND_IsPlaying(channels[chan]))
2434 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2435 if (loop_mode & FSOUND_LOOP_OFF)
2437 channels[chan] = FSOUND_FREE;
2443 channels[chan] = FSOUND_FREE;
2446 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2447 if (channels[chan] < 0)
2449 channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2453 extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2455 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2456 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2458 FSOUND_StopSound(channels[chan]);
2459 FSOUND_Stream_Stop(sptr);
2463 FSOUND_Stream_Stop(sptr);
2464 channels[chan] = FSOUND_FREE;
2467 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2468 if (channels[chan] < 0)
2470 channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2474 bool LoadImage(const char * fname, TGAImageRec & tex)
2478 if ( tex.data == NULL )
2484 ILstring f = strdup(ConvertFileName(fname));
2491 ilGenImages(1, &iid);
2496 tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2497 tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2498 tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2499 ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2500 imageSize = tex.sizeX * tex.sizeY * Bpp;
2501 ILubyte *Data = ilGetData();
2502 memcpy(tex.data, Data, imageSize);
2504 // Truvision Targa files are stored as BGR colors
2505 // We want RGB so Blue and Red bytes are switched
2506 if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2508 // Loop Through The Image Data
2509 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2511 // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2512 GLbyte temp; // Temporary Variable
2513 temp = tex.data[i]; // Temporarily Store The Value At Image Data 'i'
2514 tex.data[i] = tex.data[i + 2]; // Set The 1st Byte To The Value Of The 3rd Byte
2515 tex.data[i + 2] = temp; // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2523 ilDeleteImages(1, &iid);
2527 GLuint texid = ilutGLLoadImage(f);
2532 ilutGLBuildMipmaps()
2541 res = load_image(fname, tex);
2542 //if (!res) printf("failed to load %s\n", fname);
2548 void ScreenShot(const char * fname)
2551 ILstring f = strdup(fname);
2558 ilGenImages(1, &iid);
2564 ilDeleteImages(1, &iid);
2574 static bool load_image(const char *file_name, TGAImageRec &tex)
2576 char *ptr = strrchr((char *)file_name, '.');
2579 if (strcasecmp(ptr+1, "png") == 0)
2580 return load_png(file_name, tex);
2581 else if (strcasecmp(ptr+1, "jpg") == 0)
2582 return load_jpg(file_name, tex);
2585 STUBBED("Unsupported image type");
2590 struct my_error_mgr {
2591 struct jpeg_error_mgr pub; /* "public" fields */
2592 jmp_buf setjmp_buffer; /* for return to caller */
2594 typedef struct my_error_mgr * my_error_ptr;
2597 static void my_error_exit(j_common_ptr cinfo)
2599 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2600 longjmp(err->setjmp_buffer, 1);
2603 /* stolen from public domain example.c code in libjpg distribution. */
2604 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2606 struct jpeg_decompress_struct cinfo;
2607 struct my_error_mgr jerr;
2608 JSAMPROW buffer[1]; /* Output row buffer */
2609 int row_stride; /* physical row width in output buffer */
2610 FILE *infile = fopen(file_name, "rb");
2615 cinfo.err = jpeg_std_error(&jerr.pub);
2616 jerr.pub.error_exit = my_error_exit;
2617 if (setjmp(jerr.setjmp_buffer)) {
2618 jpeg_destroy_decompress(&cinfo);
2623 jpeg_create_decompress(&cinfo);
2624 jpeg_stdio_src(&cinfo, infile);
2625 (void) jpeg_read_header(&cinfo, TRUE);
2627 cinfo.out_color_space = JCS_RGB;
2628 cinfo.quantize_colors = 0;
2629 (void) jpeg_calc_output_dimensions(&cinfo);
2630 (void) jpeg_start_decompress(&cinfo);
2632 row_stride = cinfo.output_width * cinfo.output_components;
2633 tex.sizeX = cinfo.output_width;
2634 tex.sizeY = cinfo.output_height;
2637 while (cinfo.output_scanline < cinfo.output_height) {
2638 buffer[0] = (JSAMPROW)(char *)tex.data +
2639 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2640 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2643 (void) jpeg_finish_decompress(&cinfo);
2644 jpeg_destroy_decompress(&cinfo);
2651 /* stolen from public domain example.c code in libpng distribution. */
2652 static bool load_png(const char *file_name, TGAImageRec &tex)
2654 bool hasalpha = false;
2655 png_structp png_ptr = NULL;
2656 png_infop info_ptr = NULL;
2657 png_uint_32 width, height;
2658 int bit_depth, color_type, interlace_type;
2659 png_byte **rows = NULL;
2660 bool retval = false;
2661 png_byte **row_pointers = NULL;
2662 FILE *fp = fopen(file_name, "rb");
2667 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2668 if (png_ptr == NULL)
2671 info_ptr = png_create_info_struct(png_ptr);
2672 if (info_ptr == NULL)
2675 if (setjmp(png_jmpbuf(png_ptr)))
2678 png_init_io(png_ptr, fp);
2679 png_read_png(png_ptr, info_ptr,
2680 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2682 png_get_IHDR(png_ptr, info_ptr, &width, &height,
2683 &bit_depth, &color_type, &interlace_type, NULL, NULL);
2685 if (bit_depth != 8) // transform SHOULD handle this...
2688 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
2691 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
2694 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2695 row_pointers = png_get_rows(png_ptr, info_ptr);
2701 png_byte *dst = tex.data;
2702 for (int i = height-1; i >= 0; i--)
2704 png_byte *src = row_pointers[i];
2705 for (int j = 0; j < width; j++)
2719 png_byte *dst = tex.data;
2720 int pitch = width * 4;
2721 for (int i = height-1; i >= 0; i--, dst += pitch)
2722 memcpy(dst, row_pointers[i], pitch);
2731 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
2738 static bool save_image(const char *file_name)
2740 char *ptr = strrchr((char *)file_name, '.');
2743 if (strcasecmp(ptr+1, "png") == 0)
2744 return save_png(file_name);
2747 STUBBED("Unsupported image type");
2752 static bool save_png(const char *file_name)
2755 png_structp png_ptr = NULL;
2756 png_infop info_ptr = NULL;
2757 bool retval = false;
2759 fp = fopen(file_name, "wb");
2763 png_bytep *row_pointers = new png_bytep[kContextHeight];
2764 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2765 if ((!screenshot) || (!row_pointers))
2769 glReadPixels(0, 0, kContextWidth, kContextHeight,
2770 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2771 if (glGetError() != GL_NO_ERROR)
2774 for (int i = 0; i < kContextHeight; i++)
2775 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2777 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2778 if (png_ptr == NULL)
2781 info_ptr = png_create_info_struct(png_ptr);
2782 if (info_ptr == NULL)
2785 if (setjmp(png_jmpbuf(png_ptr)))
2788 png_init_io(png_ptr, fp);
2790 if (setjmp(png_jmpbuf(png_ptr)))
2793 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2794 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2795 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2797 png_write_info(png_ptr, info_ptr);
2799 if (setjmp(png_jmpbuf(png_ptr)))
2802 png_write_image(png_ptr, row_pointers);
2804 if (setjmp(png_jmpbuf(png_ptr)))
2807 png_write_end(png_ptr, NULL);
2811 png_destroy_write_struct(&png_ptr, &info_ptr);
2812 delete[] screenshot;
2813 delete[] row_pointers;
2817 unlink(ConvertFileName(file_name));