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)
323 if ( stereomode == stereoNone ) {
324 game.DrawGLScene(stereoCenter);
326 game.DrawGLScene(stereoLeft);
327 game.DrawGLScene(stereoRight);
332 static KeyMap g_theKeys;
334 void SetKey( int key)
336 g_theKeys[ key >> 3] |= (1 << (key & 7));
339 void ClearKey( int key)
341 g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
344 void GetKeys( unsigned char theKeys[16])
346 memcpy( theKeys, &g_theKeys, 16);
355 #define MAX_SDLKEYS SDLK_LAST
356 static unsigned short KeyTable[MAX_SDLKEYS];
358 static void initSDLKeyTable(void)
360 memset(KeyTable, 0xFF, sizeof (KeyTable));
361 KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
362 KeyTable[SDLK_TAB] = MAC_TAB_KEY;
363 KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
364 KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
365 KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
366 KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
367 KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
368 KeyTable[SDLK_END] = MAC_END_KEY;
369 KeyTable[SDLK_HOME] = MAC_HOME_KEY;
370 KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
371 KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
372 KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
373 KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
374 KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
375 KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
376 KeyTable[SDLK_0] = MAC_0_KEY;
377 KeyTable[SDLK_1] = MAC_1_KEY;
378 KeyTable[SDLK_2] = MAC_2_KEY;
379 KeyTable[SDLK_3] = MAC_3_KEY;
380 KeyTable[SDLK_4] = MAC_4_KEY;
381 KeyTable[SDLK_5] = MAC_5_KEY;
382 KeyTable[SDLK_6] = MAC_6_KEY;
383 KeyTable[SDLK_7] = MAC_7_KEY;
384 KeyTable[SDLK_8] = MAC_8_KEY;
385 KeyTable[SDLK_9] = MAC_9_KEY;
386 KeyTable[SDLK_a] = MAC_A_KEY;
387 KeyTable[SDLK_b] = MAC_B_KEY;
388 KeyTable[SDLK_c] = MAC_C_KEY;
389 KeyTable[SDLK_d] = MAC_D_KEY;
390 KeyTable[SDLK_e] = MAC_E_KEY;
391 KeyTable[SDLK_f] = MAC_F_KEY;
392 KeyTable[SDLK_g] = MAC_G_KEY;
393 KeyTable[SDLK_h] = MAC_H_KEY;
394 KeyTable[SDLK_i] = MAC_I_KEY;
395 KeyTable[SDLK_j] = MAC_J_KEY;
396 KeyTable[SDLK_k] = MAC_K_KEY;
397 KeyTable[SDLK_l] = MAC_L_KEY;
398 KeyTable[SDLK_m] = MAC_M_KEY;
399 KeyTable[SDLK_n] = MAC_N_KEY;
400 KeyTable[SDLK_o] = MAC_O_KEY;
401 KeyTable[SDLK_p] = MAC_P_KEY;
402 KeyTable[SDLK_q] = MAC_Q_KEY;
403 KeyTable[SDLK_r] = MAC_R_KEY;
404 KeyTable[SDLK_s] = MAC_S_KEY;
405 KeyTable[SDLK_t] = MAC_T_KEY;
406 KeyTable[SDLK_u] = MAC_U_KEY;
407 KeyTable[SDLK_v] = MAC_V_KEY;
408 KeyTable[SDLK_w] = MAC_W_KEY;
409 KeyTable[SDLK_x] = MAC_X_KEY;
410 KeyTable[SDLK_y] = MAC_Y_KEY;
411 KeyTable[SDLK_z] = MAC_Z_KEY;
412 KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
413 KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
414 KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
415 KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
416 KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
417 KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
418 KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
419 KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
420 KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
421 KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
422 KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
423 KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
424 KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
425 KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
426 KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
427 KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
428 KeyTable[SDLK_F1] = MAC_F1_KEY;
429 KeyTable[SDLK_F2] = MAC_F2_KEY;
430 KeyTable[SDLK_F3] = MAC_F3_KEY;
431 KeyTable[SDLK_F4] = MAC_F4_KEY;
432 KeyTable[SDLK_F5] = MAC_F5_KEY;
433 KeyTable[SDLK_F6] = MAC_F6_KEY;
434 KeyTable[SDLK_F7] = MAC_F7_KEY;
435 KeyTable[SDLK_F8] = MAC_F8_KEY;
436 KeyTable[SDLK_F9] = MAC_F9_KEY;
437 KeyTable[SDLK_F10] = MAC_F10_KEY;
438 KeyTable[SDLK_F11] = MAC_F11_KEY;
439 KeyTable[SDLK_F12] = MAC_F12_KEY;
440 KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
441 KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
442 KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
443 KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
444 KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
445 KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
446 KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
447 KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
448 KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
449 KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
450 KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
453 static inline int clamp_sdl_mouse_button(Uint8 button)
455 if (button == 2) // right mouse button is button 3 in SDL.
457 else if (button == 3)
460 if ((button >= 1) && (button <= 3))
465 static void sdlEventProc(const SDL_Event &e, Game &game)
468 bool skipkey = false;
473 case SDL_MOUSEMOTION:
474 game.deltah += e.motion.xrel;
475 game.deltav += e.motion.yrel;
478 case SDL_MOUSEBUTTONDOWN:
480 val = clamp_sdl_mouse_button(e.button.button);
481 if ((val >= 0) && (val <= 2))
490 case SDL_MOUSEBUTTONUP:
492 val = clamp_sdl_mouse_button(e.button.button);
493 if ((val >= 0) && (val <= 2))
497 buttons[val] = false;
503 if (e.key.keysym.sym == SDLK_g)
505 if (e.key.keysym.mod & KMOD_CTRL)
508 SDL_GrabMode mode = SDL_GRAB_ON;
509 if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
511 mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
512 mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
514 SDL_WM_GrabInput(mode);
518 else if (e.key.keysym.sym == SDLK_RETURN)
520 if (e.key.keysym.mod & KMOD_ALT)
523 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
527 if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
529 if (KeyTable[e.key.keysym.sym] != 0xffff)
530 SetKey(KeyTable[e.key.keysym.sym]);
533 mod = SDL_GetModState();
535 SetKey(MAC_CONTROL_KEY);
537 SetKey(MAC_OPTION_KEY);
539 SetKey(MAC_COMMAND_KEY);
540 if (mod & KMOD_SHIFT)
541 SetKey(MAC_SHIFT_KEY);
543 SetKey(MAC_CAPS_LOCK_KEY);
548 if (e.key.keysym.sym < SDLK_LAST)
550 if (KeyTable[e.key.keysym.sym] != 0xffff)
551 ClearKey(KeyTable[e.key.keysym.sym]);
554 mod = SDL_GetModState();
555 if ((mod & KMOD_CTRL) == 0)
556 ClearKey(MAC_CONTROL_KEY);
557 if ((mod & KMOD_ALT) == 0)
558 ClearKey(MAC_OPTION_KEY);
559 if ((mod & KMOD_META) == 0)
560 ClearKey(MAC_COMMAND_KEY);
561 if ((mod & KMOD_SHIFT) == 0)
562 ClearKey(MAC_SHIFT_KEY);
563 if ((mod & KMOD_CAPS) == 0)
564 ClearKey(MAC_CAPS_LOCK_KEY);
570 // --------------------------------------------------------------------------
572 static Point gMidPoint;
574 Boolean SetUp (Game & game)
580 randSeed = UpTime().lo;
583 ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
586 usermousesensitivity=1;
615 game.crouchkey=MAC_SHIFT_KEY;
616 game.jumpkey=MAC_SPACE_KEY;
617 game.leftkey=MAC_A_KEY;
618 game.forwardkey=MAC_W_KEY;
619 game.backkey=MAC_S_KEY;
620 game.rightkey=MAC_D_KEY;
621 game.drawkey=MAC_E_KEY;
622 game.throwkey=MAC_Q_KEY;
623 game.attackkey=MAC_MOUSEBUTTON1;
624 game.chatkey=MAC_T_KEY;
630 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
633 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
634 opstream << "Screenwidth:\n";
635 opstream << kContextWidth;
636 opstream << "\nScreenheight:\n";
637 opstream << kContextHeight;
638 opstream << "\nMouse sensitivity:\n";
639 opstream << usermousesensitivity;
640 opstream << "\nBlur(0,1):\n";
641 opstream << ismotionblur;
642 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
644 opstream << "\nFloating jump:\n";
645 opstream << floatjump;
646 opstream << "\nMouse jump:\n";
647 opstream << mousejump;
648 opstream << "\nAmbient sound:\n";
649 opstream << ambientsound;
650 opstream << "\nBlood (0,1,2):\n";
651 opstream << bloodtoggle;
652 opstream << "\nAuto slomo:\n";
653 opstream << autoslomo;
654 opstream << "\nFoliage:\n";
656 opstream << "\nMusic:\n";
657 opstream << musictoggle;
658 opstream << "\nTrilinear:\n";
659 opstream << trilinear;
660 opstream << "\nDecals(shadows,blood puddles,etc):\n";
662 opstream << "\nInvert mouse:\n";
663 opstream << invertmouse;
664 opstream << "\nGamespeed:\n";
665 opstream << gamespeed;
666 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
667 opstream << difficulty;
668 opstream << "\nDamage effects(blackout, doublevision):\n";
669 opstream << damageeffects;
670 opstream << "\nText:\n";
671 opstream << texttoggle;
672 opstream << "\nDebug:\n";
673 opstream << debugmode;
674 opstream << "\nVBL Sync:\n";
676 opstream << "\nShow Points:\n";
677 opstream << showpoints;
678 opstream << "\nAlways Blur:\n";
679 opstream << alwaysblur;
680 opstream << "\nImmediate mode (turn on on G5):\n";
681 opstream << immediate;
682 opstream << "\nVelocity blur:\n";
683 opstream << velocityblur;
684 opstream << "\nVolume:\n";
686 opstream << "\nForward key:\n";
687 opstream << KeyToChar(game.forwardkey);
688 opstream << "\nBack key:\n";
689 opstream << KeyToChar(game.backkey);
690 opstream << "\nLeft key:\n";
691 opstream << KeyToChar(game.leftkey);
692 opstream << "\nRight key:\n";
693 opstream << KeyToChar(game.rightkey);
694 opstream << "\nJump key:\n";
695 opstream << KeyToChar(game.jumpkey);
696 opstream << "\nCrouch key:\n";
697 opstream << KeyToChar(game.crouchkey);
698 opstream << "\nDraw key:\n";
699 opstream << KeyToChar(game.drawkey);
700 opstream << "\nThrow key:\n";
701 opstream << KeyToChar(game.throwkey);
702 opstream << "\nAttack key:\n";
703 opstream << KeyToChar(game.attackkey);
704 opstream << "\nChat key:\n";
705 opstream << KeyToChar(game.chatkey);
706 opstream << "\nStereoMode:\n";
707 opstream << stereomode;
708 opstream << "\nStereoSeparation:\n";
709 opstream << stereoseparation;
710 opstream << "\nStereoReverse:\n";
711 opstream << stereoreverse;
716 ipstream.ignore(256,'\n');
717 ipstream >> kContextWidth;
718 ipstream.ignore(256,'\n');
719 ipstream.ignore(256,'\n');
720 ipstream >> kContextHeight;
721 ipstream.ignore(256,'\n');
722 ipstream.ignore(256,'\n');
723 ipstream >> usermousesensitivity;
724 ipstream.ignore(256,'\n');
725 ipstream.ignore(256,'\n');
727 ismotionblur = (i != 0);
728 ipstream.ignore(256,'\n');
729 ipstream.ignore(256,'\n');
731 if(detail!=0)kBitsPerPixel=32;
732 else kBitsPerPixel=16;
733 ipstream.ignore(256,'\n');
734 ipstream.ignore(256,'\n');
736 floatjump = (i != 0);
737 ipstream.ignore(256,'\n');
738 ipstream.ignore(256,'\n');
740 mousejump = (i != 0);
741 ipstream.ignore(256,'\n');
742 ipstream.ignore(256,'\n');
744 ambientsound = (i != 0);
745 ipstream.ignore(256,'\n');
746 ipstream.ignore(256,'\n');
747 ipstream >> bloodtoggle;
748 ipstream.ignore(256,'\n');
749 ipstream.ignore(256,'\n');
751 autoslomo = (i != 0);
752 ipstream.ignore(256,'\n');
753 ipstream.ignore(256,'\n');
756 ipstream.ignore(256,'\n');
757 ipstream.ignore(256,'\n');
759 musictoggle = (i != 0);
760 ipstream.ignore(256,'\n');
761 ipstream.ignore(256,'\n');
763 trilinear = (i != 0);
764 ipstream.ignore(256,'\n');
765 ipstream.ignore(256,'\n');
768 ipstream.ignore(256,'\n');
769 ipstream.ignore(256,'\n');
771 invertmouse = (i != 0);
772 ipstream.ignore(256,'\n');
773 ipstream.ignore(256,'\n');
774 ipstream >> gamespeed;
775 oldgamespeed=gamespeed;
780 ipstream.ignore(256,'\n');
781 ipstream.ignore(256,'\n');
782 ipstream >> difficulty;
783 ipstream.ignore(256,'\n');
784 ipstream.ignore(256,'\n');
786 damageeffects = (i != 0);
787 ipstream.ignore(256,'\n');
788 ipstream.ignore(256,'\n');
790 texttoggle = (i != 0);
791 ipstream.ignore(256,'\n');
792 ipstream.ignore(256,'\n');
794 debugmode = (i != 0);
795 ipstream.ignore(256,'\n');
796 ipstream.ignore(256,'\n');
799 ipstream.ignore(256,'\n');
800 ipstream.ignore(256,'\n');
802 showpoints = (i != 0);
803 ipstream.ignore(256,'\n');
804 ipstream.ignore(256,'\n');
806 alwaysblur = (i != 0);
807 ipstream.ignore(256,'\n');
808 ipstream.ignore(256,'\n');
810 immediate = (i != 0);
811 ipstream.ignore(256,'\n');
812 ipstream.ignore(256,'\n');
814 velocityblur = (i != 0);
815 ipstream.ignore(256,'\n');
816 ipstream.ignore(256,'\n');
818 ipstream.ignore(256,'\n');
819 ipstream.ignore(256,'\n');
821 game.forwardkey=CharToKey(string);
822 ipstream.ignore(256,'\n');
823 ipstream.ignore(256,'\n');
825 game.backkey=CharToKey(string);
826 ipstream.ignore(256,'\n');
827 ipstream.ignore(256,'\n');
829 game.leftkey=CharToKey(string);
830 ipstream.ignore(256,'\n');
831 ipstream.ignore(256,'\n');
833 game.rightkey=CharToKey(string);
834 ipstream.ignore(256,'\n');
835 ipstream.ignore(256,'\n');
837 game.jumpkey=CharToKey(string);
838 ipstream.ignore(256,'\n');
839 ipstream.ignore(256,'\n');
841 game.crouchkey=CharToKey(string);
842 ipstream.ignore(256,'\n');
843 ipstream.ignore(256,'\n');
845 game.drawkey=CharToKey(string);
846 ipstream.ignore(256,'\n');
847 ipstream.ignore(256,'\n');
849 game.throwkey=CharToKey(string);
850 ipstream.ignore(256,'\n');
851 ipstream.ignore(256,'\n');
853 game.attackkey=CharToKey(string);
854 ipstream.ignore(256,'\n');
855 ipstream.ignore(256,'\n');
857 game.chatkey=CharToKey(string);
858 ipstream.ignore(256,'\n');
859 ipstream.ignore(256,'\n');
861 stereomode = (StereoMode)i;
862 ipstream.ignore(256,'\n');
863 ipstream.ignore(256,'\n');
864 ipstream >> stereoseparation;
865 ipstream.ignore(256,'\n');
866 ipstream.ignore(256,'\n');
867 ipstream >> stereoreverse;
871 if(detail>2)detail=2;
872 if(detail<0)detail=0;
873 if(screenwidth<0)screenwidth=640;
874 if(screenheight<0)screenheight=480;
877 if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
882 selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
884 SetupDSpFullScreen();
887 if (!SDL_WasInit(SDL_INIT_VIDEO))
889 if (SDL_Init(SDL_INIT_VIDEO) == -1)
891 fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
895 if (SDL_GL_LoadLibrary(NULL) == -1)
897 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
902 SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
903 if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
904 res = hardcoded_resolutions;
906 // reverse list (it was sorted biggest to smallest by SDL)...
908 for (count = 0; res[count]; count++)
910 if ((res[count]->w < 640) || (res[count]->h < 480))
911 break; // sane lower limit.
914 static SDL_Rect *resolutions_block = NULL;
915 resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
916 resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
917 if ((resolutions_block == NULL) || (resolutions == NULL))
920 fprintf(stderr, "Out of memory!\n");
924 resolutions[count--] = NULL;
925 for (int i = 0; count >= 0; i++, count--)
927 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
928 resolutions[count] = &resolutions_block[count];
931 if (cmdline("showresolutions"))
933 printf("Resolutions we think are okay:\n");
934 for (int i = 0; resolutions[i]; i++)
935 printf(" %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
939 Uint32 sdlflags = SDL_OPENGL;
940 if (!cmdline("windowed"))
941 sdlflags |= SDL_FULLSCREEN;
943 SDL_WM_SetCaption("Lugaru", "Lugaru");
947 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
948 SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
950 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
952 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
953 fprintf(stderr, "forcing 640x480...\n");
955 kContextHeight = 480;
956 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
958 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
959 fprintf(stderr, "forcing 640x480 windowed mode...\n");
960 sdlflags &= ~SDL_FULLSCREEN;
961 if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
963 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
970 if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
972 fprintf(stderr, "Failed to get double buffered GL context!\n");
977 if (!lookup_all_glsyms())
983 if (!cmdline("nomousegrab"))
984 SDL_WM_GrabInput(SDL_GRAB_ON);
987 glClear( GL_COLOR_BUFFER_BIT );
991 glDisable( GL_ALPHA_TEST);
992 glDisable( GL_BLEND);
993 glDisable( GL_DEPTH_TEST);
994 // glDisable( GL_DITHER);
996 glDisable( GL_LIGHTING);
997 glDisable( GL_LOGIC_OP);
998 glDisable( GL_TEXTURE_1D);
999 glDisable( GL_TEXTURE_2D);
1000 glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1001 glPixelTransferi( GL_RED_SCALE, 1);
1002 glPixelTransferi( GL_RED_BIAS, 0);
1003 glPixelTransferi( GL_GREEN_SCALE, 1);
1004 glPixelTransferi( GL_GREEN_BIAS, 0);
1005 glPixelTransferi( GL_BLUE_SCALE, 1);
1006 glPixelTransferi( GL_BLUE_BIAS, 0);
1007 glPixelTransferi( GL_ALPHA_SCALE, 1);
1008 glPixelTransferi( GL_ALPHA_BIAS, 0);
1010 // set initial rendering states
1011 glShadeModel( GL_SMOOTH);
1012 glClearDepth( 1.0f);
1013 glDepthFunc( GL_LEQUAL);
1014 glDepthMask( GL_TRUE);
1015 // glDepthRange( FRONT_CLIP, BACK_CLIP);
1016 glEnable( GL_DEPTH_TEST);
1017 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1018 glCullFace( GL_FRONT);
1019 glEnable( GL_CULL_FACE);
1020 glEnable( GL_LIGHTING);
1021 // glEnable( GL_LIGHT_MODEL_AMBIENT);
1022 glEnable( GL_DITHER);
1023 glEnable( GL_COLOR_MATERIAL);
1024 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1025 glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1026 glAlphaFunc( GL_GREATER, 0.5f);
1028 GLint width = kContextWidth;
1029 GLint height = kContextHeight;
1030 gMidPoint.h = width / 2;
1031 gMidPoint.v = height / 2;
1033 screenheight=height;
1035 game.newdetail=detail;
1036 game.newscreenwidth=screenwidth;
1037 game.newscreenheight=screenheight;
1039 GLint stencilbits = 0;
1040 glGetIntegerv(GL_STENCIL_BITS, &stencilbits);
1041 if ( stencilbits < 1 ) {
1042 fprintf(stderr, "Failed to get a stencil buffer!\n");
1047 if ( stereomode == stereoHorizontalInterlaced || stereomode == stereoVerticalInterlaced ) {
1048 fprintf(stderr, "Stencil buffer has %i bits, good.\n", stencilbits);
1049 fprintf(stderr, "Screen width is %i, height is %i\n", kContextWidth, kContextHeight);
1051 glEnable( GL_STENCIL_TEST);
1053 glClear( GL_STENCIL_BUFFER_BIT );
1054 glStencilFunc(GL_ALWAYS, 0x1, 0x1);
1055 glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
1058 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
1059 glPixelStorei(GL_UNPACK_ROW_LENGTH, 3);
1060 glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
1061 glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
1062 glColorMask( 1.0, 1.0, 1.0, 1.0 );
1063 char stencil[] = {64,127,255};
1065 glViewport(0,0, kContextWidth, kContextHeight);
1066 glMatrixMode(GL_PROJECTION);
1068 glOrtho((GLdouble)0, (GLdouble)kContextWidth, (GLdouble)kContextHeight, 0, -1, 1);
1069 glMatrixMode(GL_MODELVIEW);
1072 for(int y=0;y<kContextHeight;y+=2) {
1074 for(int x=0;x<kContextWidth;x++) {
1075 glRasterPos2i(x, y);
1076 glDrawPixels(1, 1, GL_RGB, GL_UNSIGNED_BYTE, &stencil);
1080 glStencilFunc(GL_NOTEQUAL, 0x01, 0x01);
1081 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
1083 // Something gets screwed up due to the changes above
1084 // revert to default.
1085 glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
1086 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
1087 glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
1088 glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
1097 static void DoMouse(Game & game)
1100 if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1102 game.deltah *= usermousesensitivity;
1103 game.deltav *= usermousesensitivity;
1104 game.mousecoordh += game.deltah;
1105 game.mousecoordv += game.deltav;
1106 if (game.mousecoordh < 0)
1107 game.mousecoordh = 0;
1108 else if (game.mousecoordh >= kContextWidth)
1109 game.mousecoordh = kContextWidth - 1;
1110 if (game.mousecoordv < 0)
1111 game.mousecoordv = 0;
1112 else if (game.mousecoordv >= kContextHeight)
1113 game.mousecoordv = kContextHeight - 1;
1120 // --------------------------------------------------------------------------
1122 void DoKey (SInt8 theKey, SInt8 theCode)
1127 // --------------------------------------------------------------------------
1131 void DoFrameRate (int update)
1133 static long frames = 0;
1135 static AbsoluteTime time = {0,0};
1136 static AbsoluteTime frametime = {0,0};
1137 AbsoluteTime currTime = UpTime ();
1138 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1140 if (0 > deltaTime) // if negative microseconds
1141 deltaTime /= -1000000.0;
1142 else // else milliseconds
1143 deltaTime /= 1000.0;
1145 multiplier=deltaTime;
1146 if(multiplier<.001)multiplier=.001;
1147 if(multiplier>10)multiplier=10;
1148 if(update)frametime = currTime; // reset for next time interval
1150 deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1152 if (0 > deltaTime) // if negative microseconds
1153 deltaTime /= -1000000.0;
1154 else // else milliseconds
1155 deltaTime /= 1000.0;
1157 if (0.001 <= deltaTime) // has update interval passed
1160 time = currTime; // reset for next time interval
1167 void DoUpdate (Game & game)
1169 static float sps=200;
1171 static float oldmult;
1174 if(multiplier>.6)multiplier=.6;
1176 game.fps=1/multiplier;
1178 count = multiplier*sps;
1180 //if(count>10)count=10;
1182 realmultiplier=multiplier;
1183 multiplier*=gamespeed;
1184 if(difficulty==1)multiplier*=.9;
1185 if(difficulty==0)multiplier*=.8;
1187 if(game.loading==4)multiplier*=.00001;
1189 if(slomo&&!mainmenu)multiplier*=slomospeed;
1190 //if(freeze)multiplier*=0.00001;
1192 multiplier/=(float)count;
1198 for(int i=0;i<count;i++)
1204 game.TickOnceAfter();
1205 /* - Debug code to test how many channels were active on average per frame
1206 static long frames = 0;
1208 static AbsoluteTime start = {0,0};
1209 AbsoluteTime currTime = UpTime ();
1210 static int num_channels = 0;
1212 num_channels += OPENAL_GetChannelsPlaying();
1213 double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1215 if (0 > deltaTime) // if negative microseconds
1216 deltaTime /= -1000000.0;
1217 else // else milliseconds
1218 deltaTime /= 1000.0;
1225 float avg_channels = (float)num_channels / (float)frames;
1227 ofstream opstream("log.txt",ios::app);
1228 opstream << "Average frame count: ";
1230 opstream << " frames - ";
1231 opstream << avg_channels;
1232 opstream << " per frame.\n";
1242 // --------------------------------------------------------------------------
1255 #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1256 #include "glstubs.h"
1258 // cheat here...static destructors are calling glDeleteTexture() after
1259 // the context is destroyed and libGL unloaded by SDL_Quit().
1260 pglDeleteTextures = glDeleteTextures_doNothing;
1264 // --------------------------------------------------------------------------
1266 static bool IsFocused()
1268 return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
1272 static void launch_web_browser(const char *url)
1275 ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1277 #elif (defined(__APPLE__) && defined(__MACH__))
1278 const char *fmt = "open '%s'";
1279 const size_t len = strlen(fmt) + strlen(url) + 16;
1280 char *buf = new char[len];
1281 snprintf(buf, len, fmt, url);
1285 #elif PLATFORM_LINUX
1286 const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1287 const size_t len = strlen(fmt) + strlen(url) + 16;
1288 char *buf = new char[len];
1289 snprintf(buf, len, fmt, url);
1297 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1298 static char *findBinaryInPath(const char *bin, char *envr)
1300 size_t alloc_size = 0;
1308 ptr = strchr(start, ':'); /* find next $PATH separator. */
1312 size = strlen(start) + strlen(bin) + 2;
1313 if (size > alloc_size)
1315 char *x = (char *) realloc(exe, size);
1327 /* build full binary path... */
1329 if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1333 if (access(exe, X_OK) == 0) /* Exists as executable? We're done. */
1335 strcpy(exe, start); /* i'm lazy. piss off. */
1339 start = ptr + 1; /* start points to beginning of next element. */
1340 } while (ptr != NULL);
1345 return(NULL); /* doesn't exist in path. */
1346 } /* findBinaryInPath */
1349 char *calcBaseDir(const char *argv0)
1351 /* If there isn't a path on argv0, then look through the $PATH for it. */
1355 const char *ptr = strrchr((char *)argv0, '/');
1356 if (strchr(argv0, '/'))
1358 retval = strdup(argv0);
1360 *((char *) strrchr(retval, '/')) = '\0';
1364 envr = getenv("PATH");
1365 if (!envr) return NULL;
1366 envr = strdup(envr);
1367 if (!envr) return NULL;
1368 retval = findBinaryInPath(argv0, envr);
1373 static inline void chdirToAppPath(const char *argv0)
1375 char *dir = calcBaseDir(argv0);
1378 #if (defined(__APPLE__) && defined(__MACH__))
1379 // Chop off /Contents/MacOS if it's at the end of the string, so we
1380 // land in the base of the app bundle.
1381 const size_t len = strlen(dir);
1382 const char *bundledirs = "/Contents/MacOS";
1383 const size_t bundledirslen = strlen(bundledirs);
1384 if (len > bundledirslen)
1386 char *ptr = (dir + len) - bundledirslen;
1387 if (strcasecmp(ptr, bundledirs) == 0)
1398 int main(int argc, char **argv)
1405 // !!! FIXME: we could use a Win32 API for this. --ryan.
1407 chdirToAppPath(argv[0]);
1412 memset( &g_theKeys, 0, sizeof( KeyMap));
1418 bool regnow = false;
1423 //ofstream os("error.txt");
1425 //ofstream os("log.txt");
1431 while (!gDone&&!game.quit&&(!game.tryquit))
1437 // check windows messages
1443 while( SDL_PollEvent( &e ) )
1445 if( e.type == SDL_QUIT )
1450 sdlEventProc(e, game);
1461 // allow game chance to pause
1462 gameFocused = false;
1466 // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1467 STUBBED("give up CPU but sniff the event queue");
1471 regnow = game.registernow;
1476 // if(game.registernow){
1479 #if (defined(__APPLE__) && defined(__MACH__))
1480 launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1481 #elif PLATFORM_LINUX
1482 launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1484 launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1488 #if PLATFORM_LINUX // (this may not be necessary any more.)
1489 _exit(0); // !!! FIXME: hack...crashes on exit!
1493 catch (const std::exception& error)
1497 std::string e = "Caught exception: ";
1502 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1512 // --------------------------------------------------------------------------
1516 bool selectDetail(int & width, int & height, int & bpp, int & detail)
1520 // currently with SDL, we just use whatever is requested
1521 // and don't care. --ryan.
1527 extern int channels[100];
1528 extern OPENAL_SAMPLE * samp[100];
1529 extern OPENAL_STREAM * strm[20];
1531 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1533 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1534 if (currSample && currSample == samp[chan])
1536 if (OPENAL_GetPaused(channels[chan]))
1538 OPENAL_StopSound(channels[chan]);
1539 channels[chan] = OPENAL_FREE;
1541 else if (OPENAL_IsPlaying(channels[chan]))
1543 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1544 if (loop_mode & OPENAL_LOOP_OFF)
1546 channels[chan] = OPENAL_FREE;
1552 channels[chan] = OPENAL_FREE;
1555 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1556 if (channels[chan] < 0)
1558 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1562 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1564 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1565 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1567 OPENAL_StopSound(channels[chan]);
1568 OPENAL_Stream_Stop(sptr);
1572 OPENAL_Stream_Stop(sptr);
1573 channels[chan] = OPENAL_FREE;
1576 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1577 if (channels[chan] < 0)
1579 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1584 bool LoadImage(const char * fname, TGAImageRec & tex)
1588 if ( tex.data == NULL )
1594 res = load_image(fname, tex);
1600 void ScreenShot(const char * fname)
1609 static bool load_image(const char *file_name, TGAImageRec &tex)
1611 const char *ptr = strrchr((char *)file_name, '.');
1614 if (strcasecmp(ptr+1, "png") == 0)
1615 return load_png(file_name, tex);
1616 else if (strcasecmp(ptr+1, "jpg") == 0)
1617 return load_jpg(file_name, tex);
1620 STUBBED("Unsupported image type");
1625 struct my_error_mgr {
1626 struct jpeg_error_mgr pub; /* "public" fields */
1627 jmp_buf setjmp_buffer; /* for return to caller */
1629 typedef struct my_error_mgr * my_error_ptr;
1632 static void my_error_exit(j_common_ptr cinfo)
1634 struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1635 longjmp(err->setjmp_buffer, 1);
1638 /* stolen from public domain example.c code in libjpg distribution. */
1639 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1641 struct jpeg_decompress_struct cinfo;
1642 struct my_error_mgr jerr;
1643 JSAMPROW buffer[1]; /* Output row buffer */
1644 int row_stride; /* physical row width in output buffer */
1645 FILE *infile = fopen(file_name, "rb");
1650 cinfo.err = jpeg_std_error(&jerr.pub);
1651 jerr.pub.error_exit = my_error_exit;
1652 if (setjmp(jerr.setjmp_buffer)) {
1653 jpeg_destroy_decompress(&cinfo);
1658 jpeg_create_decompress(&cinfo);
1659 jpeg_stdio_src(&cinfo, infile);
1660 (void) jpeg_read_header(&cinfo, TRUE);
1662 cinfo.out_color_space = JCS_RGB;
1663 cinfo.quantize_colors = 0;
1664 (void) jpeg_calc_output_dimensions(&cinfo);
1665 (void) jpeg_start_decompress(&cinfo);
1667 row_stride = cinfo.output_width * cinfo.output_components;
1668 tex.sizeX = cinfo.output_width;
1669 tex.sizeY = cinfo.output_height;
1672 while (cinfo.output_scanline < cinfo.output_height) {
1673 buffer[0] = (JSAMPROW)(char *)tex.data +
1674 ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1675 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1678 (void) jpeg_finish_decompress(&cinfo);
1679 jpeg_destroy_decompress(&cinfo);
1686 /* stolen from public domain example.c code in libpng distribution. */
1687 static bool load_png(const char *file_name, TGAImageRec &tex)
1689 bool hasalpha = false;
1690 png_structp png_ptr = NULL;
1691 png_infop info_ptr = NULL;
1692 png_uint_32 width, height;
1693 int bit_depth, color_type, interlace_type;
1694 png_byte **rows = NULL;
1695 bool retval = false;
1696 png_byte **row_pointers = NULL;
1697 FILE *fp = fopen(file_name, "rb");
1702 png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1703 if (png_ptr == NULL)
1706 info_ptr = png_create_info_struct(png_ptr);
1707 if (info_ptr == NULL)
1710 if (setjmp(png_jmpbuf(png_ptr)))
1713 png_init_io(png_ptr, fp);
1714 png_read_png(png_ptr, info_ptr,
1715 PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1717 png_get_IHDR(png_ptr, info_ptr, &width, &height,
1718 &bit_depth, &color_type, &interlace_type, NULL, NULL);
1720 if (bit_depth != 8) // transform SHOULD handle this...
1723 if (color_type & PNG_COLOR_MASK_PALETTE) // !!! FIXME?
1726 if ((color_type & PNG_COLOR_MASK_COLOR) == 0) // !!! FIXME?
1729 hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1730 row_pointers = png_get_rows(png_ptr, info_ptr);
1736 png_byte *dst = tex.data;
1737 for (int i = height-1; i >= 0; i--)
1739 png_byte *src = row_pointers[i];
1740 for (int j = 0; j < width; j++)
1754 png_byte *dst = tex.data;
1755 int pitch = width * 4;
1756 for (int i = height-1; i >= 0; i--, dst += pitch)
1757 memcpy(dst, row_pointers[i], pitch);
1766 png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1773 static bool save_image(const char *file_name)
1775 const char *ptr = strrchr((char *)file_name, '.');
1778 if (strcasecmp(ptr+1, "png") == 0)
1779 return save_png(file_name);
1782 STUBBED("Unsupported image type");
1787 static bool save_png(const char *file_name)
1790 png_structp png_ptr = NULL;
1791 png_infop info_ptr = NULL;
1792 bool retval = false;
1794 fp = fopen(file_name, "wb");
1798 png_bytep *row_pointers = new png_bytep[kContextHeight];
1799 png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1800 if ((!screenshot) || (!row_pointers))
1804 glReadPixels(0, 0, kContextWidth, kContextHeight,
1805 GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1806 if (glGetError() != GL_NO_ERROR)
1809 for (int i = 0; i < kContextHeight; i++)
1810 row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1812 png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1813 if (png_ptr == NULL)
1816 info_ptr = png_create_info_struct(png_ptr);
1817 if (info_ptr == NULL)
1820 if (setjmp(png_jmpbuf(png_ptr)))
1823 png_init_io(png_ptr, fp);
1825 if (setjmp(png_jmpbuf(png_ptr)))
1828 png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1829 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1830 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1832 png_write_info(png_ptr, info_ptr);
1834 if (setjmp(png_jmpbuf(png_ptr)))
1837 png_write_image(png_ptr, row_pointers);
1839 if (setjmp(png_jmpbuf(png_ptr)))
1842 png_write_end(png_ptr, NULL);
1846 png_destroy_write_struct(&png_ptr, &info_ptr);
1847 delete[] screenshot;
1848 delete[] row_pointers;
1852 unlink(ConvertFileName(file_name));