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;
66 extern float screenwidth,screenheight;
68 extern float realmultiplier;
70 extern bool ismotionblur;
71 extern float usermousesensitivity;
73 extern bool floatjump;
74 extern bool cellophane;
76 //extern int terraindetail;
77 //extern int texdetail;
78 extern float terraindetail;
79 extern float texdetail;
80 extern int bloodtoggle;
82 extern bool autoslomo;
84 extern bool musictoggle;
85 extern bool trilinear;
86 extern float gamespeed;
87 extern int difficulty;
88 extern bool damageeffects;
89 extern int numplayers;
91 extern bool invertmouse;
92 extern bool texttoggle;
93 extern bool ambientsound;
94 extern bool mousejump;
96 extern Person player[maxplayers];
98 extern bool stillloading;
99 extern bool showpoints;
100 extern bool alwaysblur;
101 extern bool immediate;
102 extern bool velocityblur;
103 extern bool debugmode;
105 /*extern*/ bool gameFocused;
106 extern int kBitsPerPixel;
107 extern float slomospeed;
108 extern float slomofreq;
109 extern float oldgamespeed;
118 #include "MacCompatibility.h"
122 #include <shellapi.h>
123 #include "win-res/resource.h"
130 SDL_Rect **resolutions = NULL;
131 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
132 static SDL_Rect rect_800_600 = { 0, 0, 800, 600 };
133 static SDL_Rect rect_640_480 = { 0, 0, 640, 480 };
134 static SDL_Rect *hardcoded_resolutions[] = {
143 unsigned int resolutionDepths[8][2] = {0};
145 bool selectDetail(int & width, int & height, int & bpp, int & detail);
146 int closestResolution(int width, int height);
147 int resolutionID(int width, int height);
149 void ReportError (char * strError);
151 void SetupDSpFullScreen();
154 void DrawGL(Game & game);
156 void CreateGLWindow (void);
157 Boolean SetUp (Game & game);
158 void DoKey (SInt8 theKey, SInt8 theCode);
159 void DoUpdate (Game & game);
165 // statics/globals (internal only) ------------------------------------------
167 typedef struct tagPOINT {
176 #pragma warning(push)
177 #pragma warning(disable: 4273)
180 #define GL_FUNC(ret,fn,params,call,rt) \
182 static ret (GLAPIENTRY *p##fn) params = NULL; \
183 ret GLAPIENTRY fn params { rt p##fn call; } \
192 static bool lookup_glsym(const char *funcname, void **func)
194 *func = SDL_GL_GetProcAddress(funcname);
197 fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
203 static bool lookup_all_glsyms(void)
206 #define GL_FUNC(ret,fn,params,call,rt) \
207 if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
213 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
220 void sdlGetCursorPos(POINT *pt)
223 SDL_GetMouseState(&x, &y);
227 #define GetCursorPos(x) sdlGetCursorPos(x)
228 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
229 #define ScreenToClient(x, pt)
230 #define ClientToScreen(x, pt)
234 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
239 static bool g_button, fullscreen = true;
250 kForegroundSleep = 10,
251 kBackgroundSleep = 10000
258 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
261 char gcstrMode [256] = "";
263 UInt32 gSleepTime = kForegroundSleep;
264 Boolean gDone = false, gfFrontProcess = true;
269 static int _argc = 0;
270 static char **_argv = NULL;
273 bool cmdline(const char *cmd)
275 for (int i = 1; i < _argc; i++)
277 char *arg = _argv[i];
280 if (strcasecmp(arg, cmd) == 0)
288 // --------------------------------------------------------------------------
290 void ReportError (char * strError)
292 #ifdef _MSC_VER // !!! FIXME. --ryan.
293 throw std::exception( strError);
296 /* char errMsgCStr [256];
299 sprintf (errMsgCStr, "%s", strError);
301 // out as debug string
302 CToPStr (strErr, errMsgCStr);
307 void SetupDSpFullScreen ()
317 //-----------------------------------------------------------------------------------------------------------------------
321 void DrawGL (Game & game)
327 static KeyMap g_theKeys;
329 void SetKey( int key)
331 g_theKeys[ key >> 3] |= (1 << (key & 7));
334 void ClearKey( int key)
336 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
339 void GetKeys( unsigned char theKeys[16])
341 memcpy( theKeys, &g_theKeys, 16);
350 #define MAX_SDLKEYS SDLK_LAST
351 static unsigned short KeyTable[MAX_SDLKEYS];
353 static void initSDLKeyTable(void)
355 memset(KeyTable, 0xFF, sizeof (KeyTable));
356 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
357 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
358 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
359 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
360 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
361 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
362 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
363 KeyTable[SDLK_END] = MAC_END_KEY;
364 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
365 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
366 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
367 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
368 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
369 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
370 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
371 KeyTable[SDLK_0] = MAC_0_KEY;
372 KeyTable[SDLK_1] = MAC_1_KEY;
373 KeyTable[SDLK_2] = MAC_2_KEY;
374 KeyTable[SDLK_3] = MAC_3_KEY;
375 KeyTable[SDLK_4] = MAC_4_KEY;
376 KeyTable[SDLK_5] = MAC_5_KEY;
377 KeyTable[SDLK_6] = MAC_6_KEY;
378 KeyTable[SDLK_7] = MAC_7_KEY;
379 KeyTable[SDLK_8] = MAC_8_KEY;
380 KeyTable[SDLK_9] = MAC_9_KEY;
381 KeyTable[SDLK_a] = MAC_A_KEY;
382 KeyTable[SDLK_b] = MAC_B_KEY;
383 KeyTable[SDLK_c] = MAC_C_KEY;
384 KeyTable[SDLK_d] = MAC_D_KEY;
385 KeyTable[SDLK_e] = MAC_E_KEY;
386 KeyTable[SDLK_f] = MAC_F_KEY;
387 KeyTable[SDLK_g] = MAC_G_KEY;
388 KeyTable[SDLK_h] = MAC_H_KEY;
389 KeyTable[SDLK_i] = MAC_I_KEY;
390 KeyTable[SDLK_j] = MAC_J_KEY;
391 KeyTable[SDLK_k] = MAC_K_KEY;
392 KeyTable[SDLK_l] = MAC_L_KEY;
393 KeyTable[SDLK_m] = MAC_M_KEY;
394 KeyTable[SDLK_n] = MAC_N_KEY;
395 KeyTable[SDLK_o] = MAC_O_KEY;
396 KeyTable[SDLK_p] = MAC_P_KEY;
397 KeyTable[SDLK_q] = MAC_Q_KEY;
398 KeyTable[SDLK_r] = MAC_R_KEY;
399 KeyTable[SDLK_s] = MAC_S_KEY;
400 KeyTable[SDLK_t] = MAC_T_KEY;
401 KeyTable[SDLK_u] = MAC_U_KEY;
402 KeyTable[SDLK_v] = MAC_V_KEY;
403 KeyTable[SDLK_w] = MAC_W_KEY;
404 KeyTable[SDLK_x] = MAC_X_KEY;
405 KeyTable[SDLK_y] = MAC_Y_KEY;
406 KeyTable[SDLK_z] = MAC_Z_KEY;
407 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
408 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
409 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
410 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
411 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
412 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
413 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
414 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
415 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
416 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
417 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
418 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
419 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
420 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
421 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
422 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
423 KeyTable[SDLK_F1] = MAC_F1_KEY;
424 KeyTable[SDLK_F2] = MAC_F2_KEY;
425 KeyTable[SDLK_F3] = MAC_F3_KEY;
426 KeyTable[SDLK_F4] = MAC_F4_KEY;
427 KeyTable[SDLK_F5] = MAC_F5_KEY;
428 KeyTable[SDLK_F6] = MAC_F6_KEY;
429 KeyTable[SDLK_F7] = MAC_F7_KEY;
430 KeyTable[SDLK_F8] = MAC_F8_KEY;
431 KeyTable[SDLK_F9] = MAC_F9_KEY;
432 KeyTable[SDLK_F10] = MAC_F10_KEY;
433 KeyTable[SDLK_F11] = MAC_F11_KEY;
434 KeyTable[SDLK_F12] = MAC_F12_KEY;
435 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
436 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
437 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
438 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
439 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
440 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
441 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
442 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
443 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
444 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
445 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
448 static inline int clamp_sdl_mouse_button(Uint8 button)
450 if (button == 2) // right mouse button is button 3 in SDL.
452 else if (button == 3)
455 if ((button >= 1) && (button <= 3))
460 static void sdlEventProc(const SDL_Event &e, Game &game)
463 bool skipkey = false;
468 case SDL_MOUSEMOTION:
469 game.deltah += e.motion.xrel;
470 game.deltav += e.motion.yrel;
473 case SDL_MOUSEBUTTONDOWN:
475 val = clamp_sdl_mouse_button(e.button.button);
476 if ((val >= 0) && (val <= 2))
485 case SDL_MOUSEBUTTONUP:
487 val = clamp_sdl_mouse_button(e.button.button);
488 if ((val >= 0) && (val <= 2))
492 buttons[val] = false;
498 if (e.key.keysym.sym == SDLK_g)
500 if (e.key.keysym.mod & KMOD_CTRL)
503 SDL_GrabMode mode = SDL_GRAB_ON;
504 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
506 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
507 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
509 SDL_WM_GrabInput(mode);
513 else if (e.key.keysym.sym == SDLK_RETURN)
515 if (e.key.keysym.mod & KMOD_ALT)
518 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
522 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
524 if (KeyTable[e.key.keysym.sym] != 0xffff)
525 SetKey(KeyTable[e.key.keysym.sym]);
528 mod = SDL_GetModState();
530 SetKey(MAC_CONTROL_KEY);
532 SetKey(MAC_OPTION_KEY);
534 SetKey(MAC_COMMAND_KEY);
535 if (mod & KMOD_SHIFT)
536 SetKey(MAC_SHIFT_KEY);
538 SetKey(MAC_CAPS_LOCK_KEY);
543 if (e.key.keysym.sym < SDLK_LAST)
545 if (KeyTable[e.key.keysym.sym] != 0xffff)
546 ClearKey(KeyTable[e.key.keysym.sym]);
549 mod = SDL_GetModState();
550 if ((mod & KMOD_CTRL) == 0)
551 ClearKey(MAC_CONTROL_KEY);
552 if ((mod & KMOD_ALT) == 0)
553 ClearKey(MAC_OPTION_KEY);
554 if ((mod & KMOD_META) == 0)
555 ClearKey(MAC_COMMAND_KEY);
556 if ((mod & KMOD_SHIFT) == 0)
557 ClearKey(MAC_SHIFT_KEY);
558 if ((mod & KMOD_CAPS) == 0)
559 ClearKey(MAC_CAPS_LOCK_KEY);
565 // --------------------------------------------------------------------------
567 static Point gMidPoint;
569 Boolean SetUp (Game & game)
575 randSeed = UpTime().lo;
578 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
581 usermousesensitivity=1;
610 game.crouchkey=MAC_SHIFT_KEY;
611 game.jumpkey=MAC_SPACE_KEY;
612 game.leftkey=MAC_A_KEY;
613 game.forwardkey=MAC_W_KEY;
614 game.backkey=MAC_S_KEY;
615 game.rightkey=MAC_D_KEY;
616 game.drawkey=MAC_E_KEY;
617 game.throwkey=MAC_Q_KEY;
618 game.attackkey=MAC_MOUSEBUTTON1;
619 game.chatkey=MAC_T_KEY;
625 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
628 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
629 opstream << "Screenwidth:\n";
630 opstream << kContextWidth;
631 opstream << "\nScreenheight:\n";
632 opstream << kContextHeight;
633 opstream << "\nMouse sensitivity:\n";
634 opstream << usermousesensitivity;
635 opstream << "\nBlur(0,1):\n";
636 opstream << ismotionblur;
637 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
639 opstream << "\nFloating jump:\n";
640 opstream << floatjump;
641 opstream << "\nMouse jump:\n";
642 opstream << mousejump;
643 opstream << "\nAmbient sound:\n";
644 opstream << ambientsound;
645 opstream << "\nBlood (0,1,2):\n";
646 opstream << bloodtoggle;
647 opstream << "\nAuto slomo:\n";
648 opstream << autoslomo;
649 opstream << "\nFoliage:\n";
651 opstream << "\nMusic:\n";
652 opstream << musictoggle;
653 opstream << "\nTrilinear:\n";
654 opstream << trilinear;
655 opstream << "\nDecals(shadows,blood puddles,etc):\n";
657 opstream << "\nInvert mouse:\n";
658 opstream << invertmouse;
659 opstream << "\nGamespeed:\n";
660 opstream << gamespeed;
661 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
662 opstream << difficulty;
663 opstream << "\nDamage effects(blackout, doublevision):\n";
664 opstream << damageeffects;
665 opstream << "\nText:\n";
666 opstream << texttoggle;
667 opstream << "\nDebug:\n";
668 opstream << debugmode;
669 opstream << "\nVBL Sync:\n";
671 opstream << "\nShow Points:\n";
672 opstream << showpoints;
673 opstream << "\nAlways Blur:\n";
674 opstream << alwaysblur;
675 opstream << "\nImmediate mode (turn on on G5):\n";
676 opstream << immediate;
677 opstream << "\nVelocity blur:\n";
678 opstream << velocityblur;
679 opstream << "\nVolume:\n";
681 opstream << "\nForward key:\n";
682 opstream << KeyToChar(game.forwardkey);
683 opstream << "\nBack key:\n";
684 opstream << KeyToChar(game.backkey);
685 opstream << "\nLeft key:\n";
686 opstream << KeyToChar(game.leftkey);
687 opstream << "\nRight key:\n";
688 opstream << KeyToChar(game.rightkey);
689 opstream << "\nJump key:\n";
690 opstream << KeyToChar(game.jumpkey);
691 opstream << "\nCrouch key:\n";
692 opstream << KeyToChar(game.crouchkey);
693 opstream << "\nDraw key:\n";
694 opstream << KeyToChar(game.drawkey);
695 opstream << "\nThrow key:\n";
696 opstream << KeyToChar(game.throwkey);
697 opstream << "\nAttack key:\n";
698 opstream << KeyToChar(game.attackkey);
699 opstream << "\nChat key:\n";
700 opstream << KeyToChar(game.chatkey);
705 ipstream.ignore(256,'\n');
706 ipstream >> kContextWidth;
707 ipstream.ignore(256,'\n');
708 ipstream.ignore(256,'\n');
709 ipstream >> kContextHeight;
710 ipstream.ignore(256,'\n');
711 ipstream.ignore(256,'\n');
712 ipstream >> usermousesensitivity;
713 ipstream.ignore(256,'\n');
714 ipstream.ignore(256,'\n');
716 ismotionblur = (i != 0);
717 ipstream.ignore(256,'\n');
718 ipstream.ignore(256,'\n');
720 if(detail!=0)kBitsPerPixel=32;
721 else kBitsPerPixel=16;
722 ipstream.ignore(256,'\n');
723 ipstream.ignore(256,'\n');
725 floatjump = (i != 0);
726 ipstream.ignore(256,'\n');
727 ipstream.ignore(256,'\n');
729 mousejump = (i != 0);
730 ipstream.ignore(256,'\n');
731 ipstream.ignore(256,'\n');
733 ambientsound = (i != 0);
734 ipstream.ignore(256,'\n');
735 ipstream.ignore(256,'\n');
736 ipstream >> bloodtoggle;
737 ipstream.ignore(256,'\n');
738 ipstream.ignore(256,'\n');
740 autoslomo = (i != 0);
741 ipstream.ignore(256,'\n');
742 ipstream.ignore(256,'\n');
745 ipstream.ignore(256,'\n');
746 ipstream.ignore(256,'\n');
748 musictoggle = (i != 0);
749 ipstream.ignore(256,'\n');
750 ipstream.ignore(256,'\n');
752 trilinear = (i != 0);
753 ipstream.ignore(256,'\n');
754 ipstream.ignore(256,'\n');
757 ipstream.ignore(256,'\n');
758 ipstream.ignore(256,'\n');
760 invertmouse = (i != 0);
761 ipstream.ignore(256,'\n');
762 ipstream.ignore(256,'\n');
763 ipstream >> gamespeed;
764 oldgamespeed=gamespeed;
769 ipstream.ignore(256,'\n');
770 ipstream.ignore(256,'\n');
771 ipstream >> difficulty;
772 ipstream.ignore(256,'\n');
773 ipstream.ignore(256,'\n');
775 damageeffects = (i != 0);
776 ipstream.ignore(256,'\n');
777 ipstream.ignore(256,'\n');
779 texttoggle = (i != 0);
780 ipstream.ignore(256,'\n');
781 ipstream.ignore(256,'\n');
783 debugmode = (i != 0);
784 ipstream.ignore(256,'\n');
785 ipstream.ignore(256,'\n');
788 ipstream.ignore(256,'\n');
789 ipstream.ignore(256,'\n');
791 showpoints = (i != 0);
792 ipstream.ignore(256,'\n');
793 ipstream.ignore(256,'\n');
795 alwaysblur = (i != 0);
796 ipstream.ignore(256,'\n');
797 ipstream.ignore(256,'\n');
799 immediate = (i != 0);
800 ipstream.ignore(256,'\n');
801 ipstream.ignore(256,'\n');
803 velocityblur = (i != 0);
804 ipstream.ignore(256,'\n');
805 ipstream.ignore(256,'\n');
807 ipstream.ignore(256,'\n');
808 ipstream.ignore(256,'\n');
810 game.forwardkey=CharToKey(string);
811 ipstream.ignore(256,'\n');
812 ipstream.ignore(256,'\n');
814 game.backkey=CharToKey(string);
815 ipstream.ignore(256,'\n');
816 ipstream.ignore(256,'\n');
818 game.leftkey=CharToKey(string);
819 ipstream.ignore(256,'\n');
820 ipstream.ignore(256,'\n');
822 game.rightkey=CharToKey(string);
823 ipstream.ignore(256,'\n');
824 ipstream.ignore(256,'\n');
826 game.jumpkey=CharToKey(string);
827 ipstream.ignore(256,'\n');
828 ipstream.ignore(256,'\n');
830 game.crouchkey=CharToKey(string);
831 ipstream.ignore(256,'\n');
832 ipstream.ignore(256,'\n');
834 game.drawkey=CharToKey(string);
835 ipstream.ignore(256,'\n');
836 ipstream.ignore(256,'\n');
838 game.throwkey=CharToKey(string);
839 ipstream.ignore(256,'\n');
840 ipstream.ignore(256,'\n');
842 game.attackkey=CharToKey(string);
843 ipstream.ignore(256,'\n');
844 ipstream.ignore(256,'\n');
846 game.chatkey=CharToKey(string);
849 if(detail>2)detail=2;
850 if(detail<0)detail=0;
851 if(screenwidth<0)screenwidth=640;
852 if(screenheight<0)screenheight=480;
855 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
860 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
862 SetupDSpFullScreen();
865 if (!SDL_WasInit(SDL_INIT_VIDEO))
867 if (SDL_Init(SDL_INIT_VIDEO) == -1)
869 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
873 if (SDL_GL_LoadLibrary(NULL) == -1)
875 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
880 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
881 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
882 res = hardcoded_resolutions;
884 // reverse list (it was sorted biggest to smallest by SDL)...
886 for (count = 0; res[count]; count++)
888 if ((res[count]->w < 640) || (res[count]->h < 480))
889 break; // sane lower limit.
892 static SDL_Rect *resolutions_block = NULL;
893 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
894 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
895 if ((resolutions_block == NULL) || (resolutions == NULL))
898 fprintf(stderr, "Out of memory!\n");
902 resolutions[count--] = NULL;
903 for (int i = 0; count >= 0; i++, count--)
905 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
906 resolutions[count] = &resolutions_block[count];
909 if (cmdline("showresolutions"))
911 printf("Resolutions we think are okay:\n");
912 for (int i = 0; resolutions[i]; i++)
913 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
917 Uint32 sdlflags = SDL_OPENGL;
918 if (!cmdline("windowed"))
919 sdlflags |= SDL_FULLSCREEN;
921 SDL_WM_SetCaption("Lugaru", "Lugaru");
925 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
927 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
929 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
930 fprintf(stderr, "forcing 640x480...\n");
932 kContextHeight = 480;
933 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
935 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
936 fprintf(stderr, "forcing 640x480 windowed mode...\n");
937 sdlflags &= ~SDL_FULLSCREEN;
938 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
940 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
947 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
949 fprintf(stderr, "Failed to get double buffered GL context!\n");
954 if (!lookup_all_glsyms())
960 if (!cmdline("nomousegrab"))
961 SDL_WM_GrabInput(SDL_GRAB_ON);
964 glClear( GL_COLOR_BUFFER_BIT );
968 glDisable( GL_ALPHA_TEST);
969 glDisable( GL_BLEND);
970 glDisable( GL_DEPTH_TEST);
971 // glDisable( GL_DITHER);
973 glDisable( GL_LIGHTING);
974 glDisable( GL_LOGIC_OP);
975 glDisable( GL_STENCIL_TEST);
976 glDisable( GL_TEXTURE_1D);
977 glDisable( GL_TEXTURE_2D);
978 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
979 glPixelTransferi( GL_RED_SCALE, 1);
980 glPixelTransferi( GL_RED_BIAS, 0);
981 glPixelTransferi( GL_GREEN_SCALE, 1);
982 glPixelTransferi( GL_GREEN_BIAS, 0);
983 glPixelTransferi( GL_BLUE_SCALE, 1);
984 glPixelTransferi( GL_BLUE_BIAS, 0);
985 glPixelTransferi( GL_ALPHA_SCALE, 1);
986 glPixelTransferi( GL_ALPHA_BIAS, 0);
988 // set initial rendering states
989 glShadeModel( GL_SMOOTH);
991 glDepthFunc( GL_LEQUAL);
992 glDepthMask( GL_TRUE);
993 // glDepthRange( FRONT_CLIP, BACK_CLIP);
994 glEnable( GL_DEPTH_TEST);
995 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
996 glCullFace( GL_FRONT);
997 glEnable( GL_CULL_FACE);
998 glEnable( GL_LIGHTING);
999 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1000 glEnable( GL_DITHER);
1001 glEnable( GL_COLOR_MATERIAL);
1002 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1003 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1004 glAlphaFunc( GL_GREATER, 0.5f);
1006 GLint width = kContextWidth;
1007 GLint height = kContextHeight;
1008 gMidPoint.h = width / 2;
1009 gMidPoint.v = height / 2;
1011 screenheight=height;
1013 game.newdetail=detail;
1014 game.newscreenwidth=screenwidth;
1015 game.newscreenheight=screenheight;
1023 static void DoMouse(Game & game)
1026 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1028 game.deltah *= usermousesensitivity;
1029 game.deltav *= usermousesensitivity;
1030 game.mousecoordh += game.deltah;
1031 game.mousecoordv += game.deltav;
1032 if (game.mousecoordh < 0)
1033 game.mousecoordh = 0;
1034 else if (game.mousecoordh >= kContextWidth)
1035 game.mousecoordh = kContextWidth - 1;
1036 if (game.mousecoordv < 0)
1037 game.mousecoordv = 0;
1038 else if (game.mousecoordv >= kContextHeight)
1039 game.mousecoordv = kContextHeight - 1;
1046 // --------------------------------------------------------------------------
1048 void DoKey (SInt8 theKey, SInt8 theCode)
1053 // --------------------------------------------------------------------------
1057 void DoFrameRate (int update)
1059 static long frames = 0;
1061 static AbsoluteTime time = {0,0};
1062 static AbsoluteTime frametime = {0,0};
1063 AbsoluteTime currTime = UpTime ();
1064 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1066 if (0 > deltaTime) // if negative microseconds
1067 deltaTime /= -1000000.0;
1068 else // else milliseconds
1069 deltaTime /= 1000.0;
1071 multiplier=deltaTime;
1072 if(multiplier<.001)multiplier=.001;
1073 if(multiplier>10)multiplier=10;
1074 if(update)frametime = currTime; // reset for next time interval
1076 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1078 if (0 > deltaTime) // if negative microseconds
1079 deltaTime /= -1000000.0;
1080 else // else milliseconds
1081 deltaTime /= 1000.0;
1083 if (0.001 <= deltaTime) // has update interval passed
1086 time = currTime; // reset for next time interval
1093 void DoUpdate (Game & game)
1095 static float sps=200;
1097 static float oldmult;
1100 if(multiplier>.6)multiplier=.6;
1102 game.fps=1/multiplier;
1104 count = multiplier*sps;
1106 //if(count>10)count=10;
1108 realmultiplier=multiplier;
1109 multiplier*=gamespeed;
1110 if(difficulty==1)multiplier*=.9;
1111 if(difficulty==0)multiplier*=.8;
1113 if(game.loading==4)multiplier*=.00001;
1115 if(slomo&&!mainmenu)multiplier*=slomospeed;
1116 //if(freeze)multiplier*=0.00001;
1118 multiplier/=(float)count;
1124 for(int i=0;i<count;i++)
1130 game.TickOnceAfter();
1131 /* - Debug code to test how many channels were active on average per frame
1132 static long frames = 0;
1134 static AbsoluteTime start = {0,0};
1135 AbsoluteTime currTime = UpTime ();
1136 static int num_channels = 0;
1138 num_channels += OPENAL_GetChannelsPlaying();
1139 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1141 if (0 > deltaTime) // if negative microseconds
1142 deltaTime /= -1000000.0;
1143 else // else milliseconds
1144 deltaTime /= 1000.0;
1151 float avg_channels = (float)num_channels / (float)frames;
1153 ofstream opstream("log.txt",ios::app);
1154 opstream << "Average frame count: ";
1156 opstream << " frames - ";
1157 opstream << avg_channels;
1158 opstream << " per frame.\n";
1168 // --------------------------------------------------------------------------
1181 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1182 #include "glstubs.h"
1184 // cheat here...static destructors are calling glDeleteTexture() after
1185 // the context is destroyed and libGL unloaded by SDL_Quit().
1186 pglDeleteTextures = glDeleteTextures_doNothing;
1190 // --------------------------------------------------------------------------
1192 static bool IsFocused()
1194 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
1198 static void launch_web_browser(const char *url)
1201 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1203 #elif (defined(__APPLE__) && defined(__MACH__))
1204 const char *fmt = "open '%s'";
1205 const size_t len = strlen(fmt) + strlen(url) + 16;
1206 char *buf = new char[len];
1207 snprintf(buf, len, fmt, url);
1211 #elif PLATFORM_LINUX
1212 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1213 const size_t len = strlen(fmt) + strlen(url) + 16;
1214 char *buf = new char[len];
1215 snprintf(buf, len, fmt, url);
1223 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1224 static char *findBinaryInPath(const char *bin, char *envr)
1226 size_t alloc_size = 0;
1234 ptr = strchr(start, ':'); /* find next $PATH separator. */
1238 size = strlen(start) + strlen(bin) + 2;
1239 if (size > alloc_size)
1241 char *x = (char *) realloc(exe, size);
1253 /* build full binary path... */
1255 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1259 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1261 strcpy(exe, start); /* i'm lazy. piss off. */
1265 start = ptr + 1; /* start points to beginning of next element. */
1266 } while (ptr != NULL);
1271 return(NULL); /* doesn't exist in path. */
1272 } /* findBinaryInPath */
1275 char *calcBaseDir(const char *argv0)
1277 /* If there isn't a path on argv0, then look through the $PATH for it. */
1281 const char *ptr = strrchr((char *)argv0, '/');
1282 if (strchr(argv0, '/'))
1284 retval = strdup(argv0);
1286 *((char *) strrchr(retval, '/')) = '\0';
1290 envr = getenv("PATH");
1291 if (!envr) return NULL;
1292 envr = strdup(envr);
1293 if (!envr) return NULL;
1294 retval = findBinaryInPath(argv0, envr);
1299 static inline void chdirToAppPath(const char *argv0)
1301 char *dir = calcBaseDir(argv0);
1304 #if (defined(__APPLE__) && defined(__MACH__))
1305 // Chop off /Contents/MacOS if it's at the end of the string, so we
1306 // land in the base of the app bundle.
1307 const size_t len = strlen(dir);
1308 const char *bundledirs = "/Contents/MacOS";
1309 const size_t bundledirslen = strlen(bundledirs);
1310 if (len > bundledirslen)
1312 char *ptr = (dir + len) - bundledirslen;
1313 if (strcasecmp(ptr, bundledirs) == 0)
1324 int main(int argc, char **argv)
1331 // !!! FIXME: we could use a Win32 API for this. --ryan.
1333 chdirToAppPath(argv[0]);
1338 memset( &g_theKeys, 0, sizeof( KeyMap));
1344 bool regnow = false;
1349 //ofstream os("error.txt");
1351 //ofstream os("log.txt");
1357 while (!gDone&&!game.quit&&(!game.tryquit))
1363 // check windows messages
1369 while( SDL_PollEvent( &e ) )
1371 if( e.type == SDL_QUIT )
1376 sdlEventProc(e, game);
1387 // allow game chance to pause
1388 gameFocused = false;
1392 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1393 STUBBED("give up CPU but sniff the event queue");
1397 regnow = game.registernow;
1402 // if(game.registernow){
1405 #if (defined(__APPLE__) && defined(__MACH__))
1406 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1407 #elif PLATFORM_LINUX
1408 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1410 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1414 #if PLATFORM_LINUX // (this may not be necessary any more.)
1415 _exit(0); // !!! FIXME: hack...crashes on exit!
1419 catch (const std::exception& error)
1423 std::string e = "Caught exception: ";
1428 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1438 // --------------------------------------------------------------------------
1442 bool selectDetail(int & width, int & height, int & bpp, int & detail)
1446 // currently with SDL, we just use whatever is requested
1447 // and don't care. --ryan.
1453 extern int channels[100];
1454 extern OPENAL_SAMPLE * samp[100];
1455 extern OPENAL_STREAM * strm[20];
1457 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1459 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1460 if (currSample && currSample == samp[chan])
1462 if (OPENAL_GetPaused(channels[chan]))
1464 OPENAL_StopSound(channels[chan]);
1465 channels[chan] = OPENAL_FREE;
1467 else if (OPENAL_IsPlaying(channels[chan]))
1469 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1470 if (loop_mode & OPENAL_LOOP_OFF)
1472 channels[chan] = OPENAL_FREE;
1478 channels[chan] = OPENAL_FREE;
1481 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1482 if (channels[chan] < 0)
1484 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1488 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1490 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1491 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1493 OPENAL_StopSound(channels[chan]);
1494 OPENAL_Stream_Stop(sptr);
1498 OPENAL_Stream_Stop(sptr);
1499 channels[chan] = OPENAL_FREE;
1502 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1503 if (channels[chan] < 0)
1505 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1510 bool LoadImage(const char * fname, TGAImageRec & tex)
1514 if ( tex.data == NULL )
1520 res = load_image(fname, tex);
1526 void ScreenShot(const char * fname)
1535 static bool load_image(const char *file_name, TGAImageRec &tex)
1537 const char *ptr = strrchr((char *)file_name, '.');
1540 if (strcasecmp(ptr+1, "png") == 0)
1541 return load_png(file_name, tex);
1542 else if (strcasecmp(ptr+1, "jpg") == 0)
1543 return load_jpg(file_name, tex);
1546 STUBBED("Unsupported image type");
1551 struct my_error_mgr {
1552 struct jpeg_error_mgr pub; /* "public" fields */
1553 jmp_buf setjmp_buffer; /* for return to caller */
1555 typedef struct my_error_mgr * my_error_ptr;
1558 static void my_error_exit(j_common_ptr cinfo)
1560 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1561 longjmp(err->setjmp_buffer, 1);
1564 /* stolen from public domain example.c code in libjpg distribution. */
1565 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1567 struct jpeg_decompress_struct cinfo;
1568 struct my_error_mgr jerr;
1569 JSAMPROW buffer[1]; /* Output row buffer */
1570 int row_stride; /* physical row width in output buffer */
1571 FILE *infile = fopen(file_name, "rb");
1576 cinfo.err = jpeg_std_error(&jerr.pub);
1577 jerr.pub.error_exit = my_error_exit;
1578 if (setjmp(jerr.setjmp_buffer)) {
1579 jpeg_destroy_decompress(&cinfo);
1584 jpeg_create_decompress(&cinfo);
1585 jpeg_stdio_src(&cinfo, infile);
1586 (void) jpeg_read_header(&cinfo, TRUE);
1588 cinfo.out_color_space = JCS_RGB;
1589 cinfo.quantize_colors = 0;
1590 (void) jpeg_calc_output_dimensions(&cinfo);
1591 (void) jpeg_start_decompress(&cinfo);
1593 row_stride = cinfo.output_width * cinfo.output_components;
1594 tex.sizeX = cinfo.output_width;
1595 tex.sizeY = cinfo.output_height;
1598 while (cinfo.output_scanline < cinfo.output_height) {
1599 buffer[0] = (JSAMPROW)(char *)tex.data +
1600 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1601 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1604 (void) jpeg_finish_decompress(&cinfo);
1605 jpeg_destroy_decompress(&cinfo);
1612 /* stolen from public domain example.c code in libpng distribution. */
1613 static bool load_png(const char *file_name, TGAImageRec &tex)
1615 bool hasalpha = false;
1616 png_structp png_ptr = NULL;
1617 png_infop info_ptr = NULL;
1618 png_uint_32 width, height;
1619 int bit_depth, color_type, interlace_type;
1620 png_byte **rows = NULL;
1621 bool retval = false;
1622 png_byte **row_pointers = NULL;
1623 FILE *fp = fopen(file_name, "rb");
1628 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1629 if (png_ptr == NULL)
1632 info_ptr = png_create_info_struct(png_ptr);
1633 if (info_ptr == NULL)
1636 if (setjmp(png_jmpbuf(png_ptr)))
1639 png_init_io(png_ptr, fp);
1640 png_read_png(png_ptr, info_ptr,
1641 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1643 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1644 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1646 if (bit_depth != 8) // transform SHOULD handle this...
1649 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1652 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1655 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1656 row_pointers = png_get_rows(png_ptr, info_ptr);
1662 png_byte *dst = tex.data;
1663 for (int i = height-1; i >= 0; i--)
1665 png_byte *src = row_pointers[i];
1666 for (int j = 0; j < width; j++)
1680 png_byte *dst = tex.data;
1681 int pitch = width * 4;
1682 for (int i = height-1; i >= 0; i--, dst += pitch)
1683 memcpy(dst, row_pointers[i], pitch);
1692 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1699 static bool save_image(const char *file_name)
1701 const char *ptr = strrchr((char *)file_name, '.');
1704 if (strcasecmp(ptr+1, "png") == 0)
1705 return save_png(file_name);
1708 STUBBED("Unsupported image type");
1713 static bool save_png(const char *file_name)
1716 png_structp png_ptr = NULL;
1717 png_infop info_ptr = NULL;
1718 bool retval = false;
1720 fp = fopen(file_name, "wb");
1724 png_bytep *row_pointers = new png_bytep[kContextHeight];
1725 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1726 if ((!screenshot) || (!row_pointers))
1730 glReadPixels(0, 0, kContextWidth, kContextHeight,
1731 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1732 if (glGetError() != GL_NO_ERROR)
1735 for (int i = 0; i < kContextHeight; i++)
1736 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1738 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1739 if (png_ptr == NULL)
1742 info_ptr = png_create_info_struct(png_ptr);
1743 if (info_ptr == NULL)
1746 if (setjmp(png_jmpbuf(png_ptr)))
1749 png_init_io(png_ptr, fp);
1751 if (setjmp(png_jmpbuf(png_ptr)))
1754 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1755 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1756 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1758 png_write_info(png_ptr, info_ptr);
1760 if (setjmp(png_jmpbuf(png_ptr)))
1763 png_write_image(png_ptr, row_pointers);
1765 if (setjmp(png_jmpbuf(png_ptr)))
1768 png_write_end(png_ptr, NULL);
1772 png_destroy_write_struct(&png_ptr, &info_ptr);
1773 delete[] screenshot;
1774 delete[] row_pointers;
1778 unlink(ConvertFileName(file_name));