]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
b68c60bcfd37bc3d4e03960d401d03430aa5ddea
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
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.
10
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.  
14
15 See the GNU General Public License for more details.
16
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.
20 */
21
22
23 #ifdef WIN32
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
27 #include <windows.h>
28 #undef UINT8
29 #undef UINT16
30 #undef boolean
31 #endif
32
33
34
35 #include "Game.h"
36 extern "C" {
37         #include "zlib.h"
38         #include "png.h"
39    #ifdef WIN32
40                 #define INT32 INT32_jpeg
41                 #include "jpeglib.h"
42                 #undef INT32
43         #else
44                 #include "jpeglib.h"
45         #endif
46 }
47
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);
53
54
55 #include "openal_wrapper.h"
56
57 // ADDED GWC
58 #ifdef _MSC_VER
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
62 #endif
63
64 extern bool buttons[3];
65 extern float multiplier;
66 extern float sps;
67 extern float realmultiplier;
68 extern int slomo;
69 extern bool cellophane;
70 // MODIFIED GWC
71 //extern int terraindetail;
72 //extern int texdetail;
73 extern float terraindetail;
74 extern float texdetail;
75
76 extern bool osx;
77 extern int numplayers;
78 extern bool freeze;
79 extern Person player[maxplayers];
80 extern bool stillloading;
81 extern int mainmenu;
82 /*extern*/ bool gameFocused;
83
84 extern float slomospeed;
85 extern float slomofreq;
86
87
88
89 #include <math.h>
90 #include <stdio.h>
91 #include <string.h>
92 #include <fstream>
93 #include <iostream>
94 #include "gamegl.h"
95 #include "MacCompatibility.h"
96 #include "Settings.h"
97
98 #ifdef WIN32
99 #include <shellapi.h>
100 #include "win-res/resource.h"
101 #endif
102
103 using namespace std;
104
105
106
107 SDL_Rect **resolutions = NULL;
108 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
109 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
110 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
111 static SDL_Rect *hardcoded_resolutions[] = {
112     &rect_1024_768,
113     &rect_800_600,
114     &rect_640_480,
115     NULL
116 };
117
118
119
120 unsigned int resolutionDepths[8][2] = {0};
121
122 bool selectDetail(int & width, int & height, int & bpp, int & detail);
123 int closestResolution(int width, int height);
124 int resolutionID(int width, int height);
125
126 void ReportError (char * strError);
127
128 void SetupDSpFullScreen();
129 void ShutdownDSp();
130
131 void DrawGL(Game & game);
132
133 void CreateGLWindow (void);
134 Boolean SetUp (Game & game);
135 void DoKey (SInt8 theKey, SInt8 theCode);
136 void DoUpdate (Game & game);
137
138 void DoEvent (void);
139 void CleanUp (void);
140
141
142 // statics/globals (internal only) ------------------------------------------
143 #ifndef WIN32
144 typedef struct tagPOINT { 
145   int x;
146   int y;
147 } POINT, *PPOINT; 
148 #endif
149
150
151
152 #ifdef _MSC_VER
153 #pragma warning(push)
154 #pragma warning(disable: 4273)
155 #endif
156
157 #define GL_FUNC(ret,fn,params,call,rt) \
158     extern "C" { \
159         static ret (GLAPIENTRY *p##fn) params = NULL; \
160         ret GLAPIENTRY fn params { rt p##fn call; } \
161     }
162 #include "glstubs.h"
163 #undef GL_FUNC
164
165 #ifdef _MSC_VER
166 #pragma warning(pop)
167 #endif
168
169 static bool lookup_glsym(const char *funcname, void **func)
170 {
171     *func = SDL_GL_GetProcAddress(funcname);
172     if (*func == NULL)
173     {
174         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
175         return false;
176     }
177     return true;
178 }
179
180 static bool lookup_all_glsyms(void)
181 {
182     bool retval = true;
183     #define GL_FUNC(ret,fn,params,call,rt) \
184         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
185     #include "glstubs.h"
186     #undef GL_FUNC
187     return retval;
188 }
189
190 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
191 {
192     // no-op.
193 }
194
195
196
197 void sdlGetCursorPos(POINT *pt)
198 {
199     int x, y;
200     SDL_GetMouseState(&x, &y);
201     pt->x = x;
202     pt->y = y;
203 }
204 #define GetCursorPos(x) sdlGetCursorPos(x)
205 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
206 #define ScreenToClient(x, pt)
207 #define ClientToScreen(x, pt)
208 #ifdef MessageBox
209 #undef MessageBox
210 #endif
211 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
212
213
214 Point delta;
215
216 static bool g_button, fullscreen = true;
217
218
219 // Menu defs
220 enum 
221 {
222         kFileQuit = 1
223 };
224
225 enum 
226 {
227         kForegroundSleep = 10,
228         kBackgroundSleep = 10000
229 };
230
231
232 int kContextWidth;
233 int kContextHeight;
234
235 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
236
237 GLuint gFontList;
238 char gcstrMode [256] = "";
239
240 UInt32 gSleepTime = kForegroundSleep;
241 Boolean gDone = false, gfFrontProcess = true;
242
243 Game * pgame = 0;
244
245 #ifndef __MINGW32__
246 static int _argc = 0;
247 static char **_argv = NULL;
248 #endif
249
250 bool cmdline(const char *cmd)
251 {
252     for (int i = 1; i < _argc; i++)
253     {
254         char *arg = _argv[i];
255         while (*arg == '-')
256             arg++;
257         if (strcasecmp(arg, cmd) == 0)
258             return true;
259     }
260
261     return false;
262 }
263
264
265 // --------------------------------------------------------------------------
266
267 void ReportError (char * strError)
268 {
269 #ifdef _MSC_VER  // !!! FIXME.  --ryan.
270         throw std::exception( strError);
271 #endif
272
273         /*      char errMsgCStr [256];
274         Str255 strErr;
275
276         sprintf (errMsgCStr, "%s", strError); 
277
278         // out as debug string
279         CToPStr (strErr, errMsgCStr);
280         DebugStr (strErr);
281         */
282 }
283
284 void SetupDSpFullScreen ()
285 {
286 }
287
288
289 void ShutdownDSp ()
290 {
291 }
292
293
294 //-----------------------------------------------------------------------------------------------------------------------
295
296 // OpenGL Drawing
297
298 void DrawGL (Game & game)
299 {
300         if ( stereomode == stereoNone ) {
301                 game.DrawGLScene(stereoCenter);
302         } else {
303                 game.DrawGLScene(stereoLeft);
304                 game.DrawGLScene(stereoRight);
305         }
306 }
307
308
309 static KeyMap g_theKeys;
310
311 void SetKey( int key)
312 {
313     g_theKeys[ key >> 3] |= (1 << (key & 7));
314 }
315
316 void ClearKey( int key)
317 {
318     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
319 }
320
321 void GetKeys(  unsigned char theKeys[16])
322 {
323     memcpy( theKeys, &g_theKeys, 16);
324 }
325
326 Boolean Button()
327 {
328     return g_button;
329 }
330
331
332 #define MAX_SDLKEYS SDLK_LAST
333 static unsigned short KeyTable[MAX_SDLKEYS];
334
335 static void initSDLKeyTable(void)
336 {
337     memset(KeyTable, 0xFF, sizeof (KeyTable));
338     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
339     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
340     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
341     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
342     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
343     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
344     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
345     KeyTable[SDLK_END] = MAC_END_KEY;
346     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
347     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
348     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
349     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
350     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
351     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
352     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
353     KeyTable[SDLK_0] = MAC_0_KEY;
354     KeyTable[SDLK_1] = MAC_1_KEY;
355     KeyTable[SDLK_2] = MAC_2_KEY;
356     KeyTable[SDLK_3] = MAC_3_KEY;
357     KeyTable[SDLK_4] = MAC_4_KEY;
358     KeyTable[SDLK_5] = MAC_5_KEY;
359     KeyTable[SDLK_6] = MAC_6_KEY;
360     KeyTable[SDLK_7] = MAC_7_KEY;
361     KeyTable[SDLK_8] = MAC_8_KEY;
362     KeyTable[SDLK_9] = MAC_9_KEY;
363     KeyTable[SDLK_a] = MAC_A_KEY;
364     KeyTable[SDLK_b] = MAC_B_KEY;
365     KeyTable[SDLK_c] = MAC_C_KEY;
366     KeyTable[SDLK_d] = MAC_D_KEY;
367     KeyTable[SDLK_e] = MAC_E_KEY;
368     KeyTable[SDLK_f] = MAC_F_KEY;
369     KeyTable[SDLK_g] = MAC_G_KEY;
370     KeyTable[SDLK_h] = MAC_H_KEY;
371     KeyTable[SDLK_i] = MAC_I_KEY;
372     KeyTable[SDLK_j] = MAC_J_KEY;
373     KeyTable[SDLK_k] = MAC_K_KEY;
374     KeyTable[SDLK_l] = MAC_L_KEY;
375     KeyTable[SDLK_m] = MAC_M_KEY;
376     KeyTable[SDLK_n] = MAC_N_KEY;
377     KeyTable[SDLK_o] = MAC_O_KEY;
378     KeyTable[SDLK_p] = MAC_P_KEY;
379     KeyTable[SDLK_q] = MAC_Q_KEY;
380     KeyTable[SDLK_r] = MAC_R_KEY;
381     KeyTable[SDLK_s] = MAC_S_KEY;
382     KeyTable[SDLK_t] = MAC_T_KEY;
383     KeyTable[SDLK_u] = MAC_U_KEY;
384     KeyTable[SDLK_v] = MAC_V_KEY;
385     KeyTable[SDLK_w] = MAC_W_KEY;
386     KeyTable[SDLK_x] = MAC_X_KEY;
387     KeyTable[SDLK_y] = MAC_Y_KEY;
388     KeyTable[SDLK_z] = MAC_Z_KEY;
389     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
390     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
391     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
392     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
393     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
394     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
395     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
396     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
397     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
398     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
399     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
400     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
401     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
402     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
403     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
404     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
405     KeyTable[SDLK_F1] = MAC_F1_KEY;
406     KeyTable[SDLK_F2] = MAC_F2_KEY;
407     KeyTable[SDLK_F3] = MAC_F3_KEY;
408     KeyTable[SDLK_F4] = MAC_F4_KEY;
409     KeyTable[SDLK_F5] = MAC_F5_KEY;
410     KeyTable[SDLK_F6] = MAC_F6_KEY;
411     KeyTable[SDLK_F7] = MAC_F7_KEY;
412     KeyTable[SDLK_F8] = MAC_F8_KEY;
413     KeyTable[SDLK_F9] = MAC_F9_KEY;
414     KeyTable[SDLK_F10] = MAC_F10_KEY;
415     KeyTable[SDLK_F11] = MAC_F11_KEY;
416     KeyTable[SDLK_F12] = MAC_F12_KEY;
417     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
418     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
419     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
420     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
421     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
422     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
423     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
424     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
425     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
426     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
427     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
428 }
429
430 static inline int clamp_sdl_mouse_button(Uint8 button)
431 {
432     if (button == 2)   // right mouse button is button 3 in SDL.
433         button = 3;
434     else if (button == 3)
435         button = 2;
436
437     if ((button >= 1) && (button <= 3))
438         return button - 1;
439     return -1;
440 }
441
442 static void sdlEventProc(const SDL_Event &e, Game &game)
443 {
444     int val;
445     bool skipkey = false;
446     SDLMod mod;
447
448     switch(e.type)
449         {
450         case SDL_MOUSEMOTION:
451             game.deltah += e.motion.xrel;
452             game.deltav += e.motion.yrel;
453             return;
454
455                 case SDL_MOUSEBUTTONDOWN:
456                         {
457                 val = clamp_sdl_mouse_button(e.button.button);
458                 if ((val >= 0) && (val <= 2))
459                 {
460                     if (val == 0)
461                                     g_button = true;
462                                 buttons[val] = true;
463                 }
464                         }
465                         return;
466
467                 case SDL_MOUSEBUTTONUP:
468                         {
469                 val = clamp_sdl_mouse_button(e.button.button);
470                 if ((val >= 0) && (val <= 2))
471                 {
472                     if (val == 0)
473                                     g_button = false;
474                                 buttons[val] = false;
475                 }
476                         }
477             return;
478
479         case SDL_KEYDOWN:
480             if (e.key.keysym.sym == SDLK_g)
481             {
482                 if (e.key.keysym.mod & KMOD_CTRL)
483                 {
484                     skipkey = true;
485                     SDL_GrabMode mode = SDL_GRAB_ON;
486                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
487                     {
488                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
489                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
490                     }
491                     SDL_WM_GrabInput(mode);
492                 }
493             }
494
495             else if (e.key.keysym.sym == SDLK_RETURN)
496             {
497                 if (e.key.keysym.mod & KMOD_ALT)
498                 {
499                     skipkey = true;
500                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
501                 }
502             }
503
504             if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
505             {
506                 if (KeyTable[e.key.keysym.sym] != 0xffff)
507                     SetKey(KeyTable[e.key.keysym.sym]);
508             }
509
510             mod = SDL_GetModState();
511             if (mod & KMOD_CTRL)
512                 SetKey(MAC_CONTROL_KEY);
513             if (mod & KMOD_ALT)
514                 SetKey(MAC_OPTION_KEY);
515             if (mod & KMOD_META)
516                 SetKey(MAC_COMMAND_KEY);
517             if (mod & KMOD_SHIFT)
518                 SetKey(MAC_SHIFT_KEY);
519             if (mod & KMOD_CAPS)
520                 SetKey(MAC_CAPS_LOCK_KEY);
521
522             return;
523
524         case SDL_KEYUP:
525             if (e.key.keysym.sym < SDLK_LAST)
526             {
527                 if (KeyTable[e.key.keysym.sym] != 0xffff)
528                     ClearKey(KeyTable[e.key.keysym.sym]);
529             }
530
531             mod = SDL_GetModState();
532             if ((mod & KMOD_CTRL) == 0)
533                 ClearKey(MAC_CONTROL_KEY);
534             if ((mod & KMOD_ALT) == 0)
535                 ClearKey(MAC_OPTION_KEY);
536             if ((mod & KMOD_META) == 0)
537                 ClearKey(MAC_COMMAND_KEY);
538             if ((mod & KMOD_SHIFT) == 0)
539                 ClearKey(MAC_SHIFT_KEY);
540             if ((mod & KMOD_CAPS) == 0)
541                 ClearKey(MAC_CAPS_LOCK_KEY);
542             return;
543     }
544 }
545
546
547 // --------------------------------------------------------------------------
548
549 static Point gMidPoint;
550
551 Boolean SetUp (Game & game)
552 {
553         char string[10];
554
555         LOGFUNC;
556
557         randSeed = UpTime().lo;
558
559         osx = 0;
560         cellophane=0;
561         texdetail=4;
562         terraindetail=2;
563         slomospeed=0.25;
564         slomofreq=8012;
565         numplayers=1;
566         
567         DefaultSettings(game);
568
569         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
570
571         if(!LoadSettings(game)) {
572                 fprintf(stderr, "Failed to load config, creating default\n");
573                 SaveSettings(game);
574         }
575         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
576                 kBitsPerPixel=16;
577         }
578
579
580         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
581
582         SetupDSpFullScreen();
583
584
585     if (!SDL_WasInit(SDL_INIT_VIDEO))
586     {
587         if (SDL_Init(SDL_INIT_VIDEO) == -1)
588         {
589             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
590             return false;
591         }
592
593         if (SDL_GL_LoadLibrary(NULL) == -1)
594         {
595             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
596             SDL_Quit();
597             return false;
598         }
599
600         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
601         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
602             res = hardcoded_resolutions;
603
604         // reverse list (it was sorted biggest to smallest by SDL)...
605         int count;
606         for (count = 0; res[count]; count++)
607         {
608             if ((res[count]->w < 640) || (res[count]->h < 480))
609                 break;   // sane lower limit.
610         }
611
612         static SDL_Rect *resolutions_block = NULL;
613         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
614         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
615         if ((resolutions_block == NULL) || (resolutions == NULL))
616         {
617             SDL_Quit();
618             fprintf(stderr, "Out of memory!\n");
619             return false;
620         }
621
622         resolutions[count--] = NULL;
623         for (int i = 0; count >= 0; i++, count--)
624         {
625             memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
626             resolutions[count] = &resolutions_block[count];
627         }
628
629         if (cmdline("showresolutions"))
630         {
631             printf("Resolutions we think are okay:\n");
632             for (int i = 0; resolutions[i]; i++)
633                 printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
634         }
635     }
636
637     Uint32 sdlflags = SDL_OPENGL;
638     if (!cmdline("windowed"))
639         sdlflags |= SDL_FULLSCREEN;
640
641     SDL_WM_SetCaption("Lugaru", "Lugaru");
642
643     SDL_ShowCursor(0);
644
645     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
646     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
647     
648     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
649     {
650         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
651         fprintf(stderr, "forcing 640x480...\n");
652         kContextWidth = 640;
653         kContextHeight = 480;
654         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
655         {
656             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
657             fprintf(stderr, "forcing 640x480 windowed mode...\n");
658             sdlflags &= ~SDL_FULLSCREEN;
659             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
660             {
661                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
662                 return false;
663             }
664         }
665     }
666
667     int dblbuf = 0;
668     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
669     {
670         fprintf(stderr, "Failed to get double buffered GL context!\n");
671         SDL_Quit();
672         return false;
673     }
674
675     if (!lookup_all_glsyms())
676     {
677         SDL_Quit();
678         return false;
679     }
680
681     if (!cmdline("nomousegrab"))
682         SDL_WM_GrabInput(SDL_GRAB_ON);
683
684
685         glClear( GL_COLOR_BUFFER_BIT );
686         swap_gl_buffers();
687
688         // clear all states
689         glDisable( GL_ALPHA_TEST);
690         glDisable( GL_BLEND);
691         glDisable( GL_DEPTH_TEST);
692         //      glDisable( GL_DITHER);
693         glDisable( GL_FOG);
694         glDisable( GL_LIGHTING);
695         glDisable( GL_LOGIC_OP);
696         glDisable( GL_TEXTURE_1D);
697         glDisable( GL_TEXTURE_2D);
698         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
699         glPixelTransferi( GL_RED_SCALE, 1);
700         glPixelTransferi( GL_RED_BIAS, 0);
701         glPixelTransferi( GL_GREEN_SCALE, 1);
702         glPixelTransferi( GL_GREEN_BIAS, 0);
703         glPixelTransferi( GL_BLUE_SCALE, 1);
704         glPixelTransferi( GL_BLUE_BIAS, 0);
705         glPixelTransferi( GL_ALPHA_SCALE, 1);
706         glPixelTransferi( GL_ALPHA_BIAS, 0);
707
708         // set initial rendering states
709         glShadeModel( GL_SMOOTH);
710         glClearDepth( 1.0f);
711         glDepthFunc( GL_LEQUAL);
712         glDepthMask( GL_TRUE);
713         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
714         glEnable( GL_DEPTH_TEST);
715         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
716         glCullFace( GL_FRONT);
717         glEnable( GL_CULL_FACE);
718         glEnable( GL_LIGHTING);
719 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
720         glEnable( GL_DITHER);
721         glEnable( GL_COLOR_MATERIAL);
722         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
723         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
724         glAlphaFunc( GL_GREATER, 0.5f);
725
726         GLint width = kContextWidth;
727         GLint height = kContextHeight;
728         gMidPoint.h = width / 2;
729         gMidPoint.v = height / 2;
730         screenwidth=width;
731         screenheight=height;
732
733         game.newdetail=detail;
734         game.newscreenwidth=screenwidth;
735         game.newscreenheight=screenheight;
736
737         if ( CanInitStereo(stereomode) ) {
738                 InitStereo(stereomode);
739         } else {
740                 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
741                 stereomode = stereoNone;
742         }
743
744         game.InitGame();
745
746         return true;
747 }
748
749
750 static void DoMouse(Game & game)
751 {
752
753         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
754         {
755                 game.deltah *= usermousesensitivity;
756                 game.deltav *= usermousesensitivity;
757                 game.mousecoordh += game.deltah;
758                 game.mousecoordv += game.deltav;
759         if (game.mousecoordh < 0)
760             game.mousecoordh = 0;
761         else if (game.mousecoordh >= kContextWidth)
762             game.mousecoordh = kContextWidth - 1;
763         if (game.mousecoordv < 0)
764             game.mousecoordv = 0;
765         else if (game.mousecoordv >= kContextHeight)
766             game.mousecoordv = kContextHeight - 1;
767         }
768
769 }
770
771
772
773 // --------------------------------------------------------------------------
774
775 void DoKey (SInt8 theKey, SInt8 theCode)
776 {
777         // do nothing
778 }
779
780 // --------------------------------------------------------------------------
781
782
783
784 void DoFrameRate (int update)
785 {       
786         static long frames = 0;
787
788         static AbsoluteTime time = {0,0};
789         static AbsoluteTime frametime = {0,0};
790         AbsoluteTime currTime = UpTime ();
791         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
792
793         if (0 > deltaTime)      // if negative microseconds
794                 deltaTime /= -1000000.0;
795         else                            // else milliseconds
796                 deltaTime /= 1000.0;
797
798         multiplier=deltaTime;
799         if(multiplier<.001)multiplier=.001;
800         if(multiplier>10)multiplier=10;
801         if(update)frametime = currTime; // reset for next time interval
802
803         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
804
805         if (0 > deltaTime)      // if negative microseconds
806                 deltaTime /= -1000000.0;
807         else                            // else milliseconds
808                 deltaTime /= 1000.0;
809         frames++;
810         if (0.001 <= deltaTime) // has update interval passed
811         {
812                 if(update){
813                         time = currTime;        // reset for next time interval
814                         frames = 0;
815                 }
816         }
817 }
818
819
820 void DoUpdate (Game & game)
821 {
822         static float sps=200;
823         static int count;
824         static float oldmult;
825
826         DoFrameRate(1);
827         if(multiplier>.6)multiplier=.6;
828
829         game.fps=1/multiplier;
830
831         count = multiplier*sps;
832         if(count<2)count=2;
833         //if(count>10)count=10;
834
835         realmultiplier=multiplier;
836         multiplier*=gamespeed;
837         if(difficulty==1)multiplier*=.9;
838         if(difficulty==0)multiplier*=.8;
839
840         if(game.loading==4)multiplier*=.00001;
841         //multiplier*.9;
842         if(slomo&&!mainmenu)multiplier*=slomospeed;
843         //if(freeze)multiplier*=0.00001;
844         oldmult=multiplier;
845         multiplier/=(float)count;
846
847         DoMouse(game);
848
849         game.TickOnce();
850
851         for(int i=0;i<count;i++)
852         {
853                 game.Tick();
854         }
855         multiplier=oldmult;
856
857         game.TickOnceAfter();
858 /* - Debug code to test how many channels were active on average per frame
859         static long frames = 0;
860
861         static AbsoluteTime start = {0,0};
862         AbsoluteTime currTime = UpTime ();
863         static int num_channels = 0;
864         
865         num_channels += OPENAL_GetChannelsPlaying();
866         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
867
868         if (0 > deltaTime)      // if negative microseconds
869                 deltaTime /= -1000000.0;
870         else                            // else milliseconds
871                 deltaTime /= 1000.0;
872
873         ++frames;
874
875         if (deltaTime >= 1)
876         {
877                 start = currTime;
878                 float avg_channels = (float)num_channels / (float)frames;
879
880                 ofstream opstream("log.txt",ios::app); 
881                 opstream << "Average frame count: ";
882                 opstream << frames;
883                 opstream << " frames - ";
884                 opstream << avg_channels;
885                 opstream << " per frame.\n";
886                 opstream.close();
887
888                 frames = 0;
889                 num_channels = 0;
890         }
891 */
892         DrawGL (game);
893 }
894
895 // --------------------------------------------------------------------------
896
897
898 void CleanUp (void)
899 {
900         LOGFUNC;
901
902 //      game.Dispose();
903
904
905
906
907     SDL_Quit();
908     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
909     #include "glstubs.h"
910     #undef GL_FUNC
911     // cheat here...static destructors are calling glDeleteTexture() after
912     //  the context is destroyed and libGL unloaded by SDL_Quit().
913     pglDeleteTextures = glDeleteTextures_doNothing;
914
915 }
916
917 // --------------------------------------------------------------------------
918
919 static bool IsFocused()
920 {
921     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
922 }
923
924
925 static void launch_web_browser(const char *url)
926 {
927 #ifdef WIN32
928     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
929
930 #elif (defined(__APPLE__) && defined(__MACH__))
931     const char *fmt = "open '%s'";
932     const size_t len = strlen(fmt) + strlen(url) + 16;
933     char *buf = new char[len];
934     snprintf(buf, len, fmt, url);
935     system(buf);
936     delete[] buf;
937
938 #elif PLATFORM_LINUX
939     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
940     const size_t len = strlen(fmt) + strlen(url) + 16;
941     char *buf = new char[len];
942     snprintf(buf, len, fmt, url);
943     system(buf);
944     delete[] buf;
945 #endif
946 }
947
948
949 #ifndef WIN32
950 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
951 static char *findBinaryInPath(const char *bin, char *envr)
952 {
953     size_t alloc_size = 0;
954     char *exe = NULL;
955     char *start = envr;
956     char *ptr;
957
958     do
959     {
960         size_t size;
961         ptr = strchr(start, ':');  /* find next $PATH separator. */
962         if (ptr)
963             *ptr = '\0';
964
965         size = strlen(start) + strlen(bin) + 2;
966         if (size > alloc_size)
967         {
968             char *x = (char *) realloc(exe, size);
969             if (x == NULL)
970             {
971                 if (exe != NULL)
972                     free(exe);
973                 return(NULL);
974             } /* if */
975
976             alloc_size = size;
977             exe = x;
978         } /* if */
979
980         /* build full binary path... */
981         strcpy(exe, start);
982         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
983             strcat(exe, "/");
984         strcat(exe, bin);
985
986         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
987         {
988             strcpy(exe, start);  /* i'm lazy. piss off. */
989             return(exe);
990         } /* if */
991
992         start = ptr + 1;  /* start points to beginning of next element. */
993     } while (ptr != NULL);
994
995     if (exe != NULL)
996         free(exe);
997
998     return(NULL);  /* doesn't exist in path. */
999 } /* findBinaryInPath */
1000
1001
1002 char *calcBaseDir(const char *argv0)
1003 {
1004     /* If there isn't a path on argv0, then look through the $PATH for it. */
1005     char *retval;
1006     char *envr;
1007
1008     const char *ptr = strrchr((char *)argv0, '/');
1009     if (strchr(argv0, '/'))
1010     {
1011         retval = strdup(argv0);
1012         if (retval)
1013             *((char *) strrchr(retval, '/')) = '\0';
1014         return(retval);
1015     }
1016
1017     envr = getenv("PATH");
1018     if (!envr) return NULL;
1019     envr = strdup(envr);
1020     if (!envr) return NULL;
1021     retval = findBinaryInPath(argv0, envr);
1022     free(envr);
1023     return(retval);
1024 }
1025
1026 static inline void chdirToAppPath(const char *argv0)
1027 {
1028     char *dir = calcBaseDir(argv0);
1029     if (dir)
1030     {
1031         #if (defined(__APPLE__) && defined(__MACH__))
1032         // Chop off /Contents/MacOS if it's at the end of the string, so we
1033         //  land in the base of the app bundle.
1034         const size_t len = strlen(dir);
1035         const char *bundledirs = "/Contents/MacOS";
1036         const size_t bundledirslen = strlen(bundledirs);
1037         if (len > bundledirslen)
1038         {
1039             char *ptr = (dir + len) - bundledirslen;
1040             if (strcasecmp(ptr, bundledirs) == 0)
1041                 *ptr = '\0';
1042         }
1043         #endif
1044         chdir(dir);
1045         free(dir);
1046     }
1047 }
1048 #endif
1049
1050
1051 int main(int argc, char **argv)
1052 {
1053 #ifndef __MINGW32__
1054     _argc = argc;
1055     _argv = argv;
1056 #endif
1057
1058     // !!! FIXME: we could use a Win32 API for this.  --ryan.
1059 #ifndef WIN32
1060     chdirToAppPath(argv[0]);
1061 #endif
1062
1063         LOGFUNC;
1064
1065         memset( &g_theKeys, 0, sizeof( KeyMap));
1066
1067     initSDLKeyTable();
1068
1069         try
1070         {
1071                 bool regnow = false;
1072                 {
1073                         Game game;
1074                         pgame = &game;
1075
1076                         //ofstream os("error.txt");
1077                         //os.close();
1078                         //ofstream os("log.txt");
1079                         //os.close();
1080
1081                         if (!SetUp (game))
1082                 return 42;
1083
1084                         while (!gDone&&!game.quit&&(!game.tryquit))
1085                         {
1086                                 if (IsFocused())
1087                                 {
1088                                         gameFocused = true;
1089
1090                                         // check windows messages
1091                         
1092                                         game.deltah = 0;
1093                                         game.deltav = 0;
1094                                         SDL_Event e;
1095                                         // message pump
1096                                         while( SDL_PollEvent( &e ) )
1097                                         {
1098                                                 if( e.type == SDL_QUIT )
1099                                                 {
1100                                                         gDone=true;
1101                                                         break;
1102                                                 }
1103                                                 sdlEventProc(e, game);
1104                                         }
1105                                 
1106
1107                                         // game
1108                                         DoUpdate(game);
1109                                 }
1110                                 else
1111                                 {
1112                                         if (gameFocused)
1113                                         {
1114                                                 // allow game chance to pause
1115                                                 gameFocused = false;
1116                                                 DoUpdate(game);
1117                                         }
1118
1119                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1120                     STUBBED("give up CPU but sniff the event queue");
1121                                 }
1122                         }
1123
1124                         regnow = game.registernow;
1125                 }
1126                 pgame = 0;
1127
1128                 CleanUp ();
1129 //              if(game.registernow){
1130                 if(regnow)
1131                 {
1132             #if (defined(__APPLE__) && defined(__MACH__))
1133             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1134             #elif PLATFORM_LINUX
1135             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1136             #else
1137             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1138             #endif
1139                 }
1140
1141         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1142         _exit(0);  // !!! FIXME: hack...crashes on exit!
1143         #endif
1144                 return 0;
1145         }
1146         catch (const std::exception& error)
1147         {
1148                 CleanUp();
1149
1150                 std::string e = "Caught exception: ";
1151                 e += error.what();
1152
1153                 LOG(e);
1154
1155                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1156         }
1157
1158         CleanUp();
1159
1160         return -1;
1161 }
1162
1163
1164
1165         // --------------------------------------------------------------------------
1166
1167
1168
1169         bool selectDetail(int & width, int & height, int & bpp, int & detail)
1170         {
1171                 bool res = true;
1172
1173                 // currently with SDL, we just use whatever is requested
1174                 //  and don't care.  --ryan.
1175                 
1176
1177                 return res;
1178         }
1179
1180         extern int channels[100];
1181         extern OPENAL_SAMPLE * samp[100];
1182         extern OPENAL_STREAM * strm[20];
1183
1184         extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1185         {
1186                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1187                 if (currSample && currSample == samp[chan])
1188                 {
1189                         if (OPENAL_GetPaused(channels[chan]))
1190                         {
1191                                 OPENAL_StopSound(channels[chan]);
1192                                 channels[chan] = OPENAL_FREE;
1193                         }
1194                         else if (OPENAL_IsPlaying(channels[chan]))
1195                         {
1196                                 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1197                                 if (loop_mode & OPENAL_LOOP_OFF)
1198                                 {
1199                                         channels[chan] = OPENAL_FREE;
1200                                 }
1201                         }
1202                 }
1203                 else
1204                 {
1205                         channels[chan] = OPENAL_FREE;
1206                 }
1207
1208                 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1209                 if (channels[chan] < 0)
1210                 {
1211                         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1212                 }
1213         }
1214
1215         extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1216         {
1217                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1218                 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1219                 {
1220                                 OPENAL_StopSound(channels[chan]);
1221                                 OPENAL_Stream_Stop(sptr);
1222                 }
1223                 else
1224                 {
1225                         OPENAL_Stream_Stop(sptr);
1226                         channels[chan] = OPENAL_FREE;
1227                 }
1228
1229                 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1230                 if (channels[chan] < 0)
1231                 {
1232                         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1233                 }
1234         }
1235
1236
1237         bool LoadImage(const char * fname, TGAImageRec & tex)
1238         {
1239                 bool res = true;
1240
1241                 if ( tex.data == NULL )
1242                 {
1243                         return false;
1244                 }
1245
1246        
1247         res = load_image(fname, tex);
1248     
1249
1250                 return res;
1251         }
1252
1253         void ScreenShot(const char * fname)
1254         {
1255   
1256         save_image(fname);
1257   
1258         }
1259
1260
1261
1262 static bool load_image(const char *file_name, TGAImageRec &tex)
1263 {
1264     const char *ptr = strrchr((char *)file_name, '.');
1265     if (ptr)
1266     {
1267         if (strcasecmp(ptr+1, "png") == 0)
1268             return load_png(file_name, tex);
1269         else if (strcasecmp(ptr+1, "jpg") == 0)
1270             return load_jpg(file_name, tex);
1271     }
1272
1273     STUBBED("Unsupported image type");
1274     return false;
1275 }
1276
1277
1278 struct my_error_mgr {
1279   struct jpeg_error_mgr pub;    /* "public" fields */
1280   jmp_buf setjmp_buffer;        /* for return to caller */
1281 };
1282 typedef struct my_error_mgr * my_error_ptr;
1283
1284
1285 static void my_error_exit(j_common_ptr cinfo)
1286 {
1287         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1288         longjmp(err->setjmp_buffer, 1);
1289 }
1290
1291 /* stolen from public domain example.c code in libjpg distribution. */
1292 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1293 {
1294     struct jpeg_decompress_struct cinfo;
1295     struct my_error_mgr jerr;
1296     JSAMPROW buffer[1];         /* Output row buffer */
1297     int row_stride;             /* physical row width in output buffer */
1298     FILE *infile = fopen(file_name, "rb");
1299
1300     if (infile == NULL)
1301         return false;
1302
1303     cinfo.err = jpeg_std_error(&jerr.pub);
1304     jerr.pub.error_exit = my_error_exit;
1305     if (setjmp(jerr.setjmp_buffer)) {
1306         jpeg_destroy_decompress(&cinfo);
1307         fclose(infile);
1308         return false;
1309     }
1310
1311     jpeg_create_decompress(&cinfo);
1312     jpeg_stdio_src(&cinfo, infile);
1313     (void) jpeg_read_header(&cinfo, TRUE);
1314
1315     cinfo.out_color_space = JCS_RGB;
1316     cinfo.quantize_colors = 0;
1317     (void) jpeg_calc_output_dimensions(&cinfo);
1318     (void) jpeg_start_decompress(&cinfo);
1319
1320     row_stride = cinfo.output_width * cinfo.output_components;
1321     tex.sizeX = cinfo.output_width;
1322     tex.sizeY = cinfo.output_height;
1323     tex.bpp = 24;
1324
1325     while (cinfo.output_scanline < cinfo.output_height) {
1326         buffer[0] = (JSAMPROW)(char *)tex.data +
1327                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1328         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1329     }
1330
1331     (void) jpeg_finish_decompress(&cinfo);
1332     jpeg_destroy_decompress(&cinfo);
1333     fclose(infile);
1334
1335     return true;
1336 }
1337
1338
1339 /* stolen from public domain example.c code in libpng distribution. */
1340 static bool load_png(const char *file_name, TGAImageRec &tex)
1341 {
1342     bool hasalpha = false;
1343     png_structp png_ptr = NULL;
1344     png_infop info_ptr = NULL;
1345     png_uint_32 width, height;
1346     int bit_depth, color_type, interlace_type;
1347     png_byte **rows = NULL;
1348     bool retval = false;
1349     png_byte **row_pointers = NULL;
1350     FILE *fp = fopen(file_name, "rb");
1351
1352     if (fp == NULL)
1353         return(NULL);
1354
1355     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1356     if (png_ptr == NULL)
1357         goto png_done;
1358
1359     info_ptr = png_create_info_struct(png_ptr);
1360     if (info_ptr == NULL)
1361         goto png_done;
1362
1363     if (setjmp(png_jmpbuf(png_ptr)))
1364         goto png_done;
1365
1366     png_init_io(png_ptr, fp);
1367     png_read_png(png_ptr, info_ptr,
1368                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1369                  NULL);
1370     png_get_IHDR(png_ptr, info_ptr, &width, &height,
1371                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
1372
1373     if (bit_depth != 8)  // transform SHOULD handle this...
1374         goto png_done;
1375
1376     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
1377         goto png_done;
1378
1379     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
1380         goto png_done;
1381
1382     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1383     row_pointers = png_get_rows(png_ptr, info_ptr);
1384     if (!row_pointers)
1385         goto png_done;
1386
1387     if (!hasalpha)
1388     {
1389         png_byte *dst = tex.data;
1390         for (int i = height-1; i >= 0; i--)
1391         {
1392             png_byte *src = row_pointers[i];
1393             for (int j = 0; j < width; j++)
1394             {
1395                 dst[0] = src[0];
1396                 dst[1] = src[1];
1397                 dst[2] = src[2];
1398                 dst[3] = 0xFF;
1399                 src += 3;
1400                 dst += 4;
1401             }
1402         }
1403     }
1404
1405     else
1406     {
1407         png_byte *dst = tex.data;
1408         int pitch = width * 4;
1409         for (int i = height-1; i >= 0; i--, dst += pitch)
1410             memcpy(dst, row_pointers[i], pitch);
1411     }
1412
1413     tex.sizeX = width;
1414     tex.sizeY = height;
1415     tex.bpp = 32;
1416     retval = true;
1417
1418 png_done:
1419     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1420     if (fp)
1421         fclose(fp);
1422     return (retval);
1423 }
1424
1425
1426 static bool save_image(const char *file_name)
1427 {
1428     const char *ptr = strrchr((char *)file_name, '.');
1429     if (ptr)
1430     {
1431         if (strcasecmp(ptr+1, "png") == 0)
1432             return save_png(file_name);
1433     }
1434
1435     STUBBED("Unsupported image type");
1436     return false;
1437 }
1438
1439
1440 static bool save_png(const char *file_name)
1441 {
1442     FILE *fp = NULL;
1443     png_structp png_ptr = NULL;
1444     png_infop info_ptr = NULL;
1445     bool retval = false;
1446
1447     fp = fopen(file_name, "wb");
1448     if (fp == NULL)
1449         return false;
1450
1451     png_bytep *row_pointers = new png_bytep[kContextHeight];
1452     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1453     if ((!screenshot) || (!row_pointers))
1454         goto save_png_done;
1455
1456     glGetError();
1457     glReadPixels(0, 0, kContextWidth, kContextHeight,
1458                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1459     if (glGetError() != GL_NO_ERROR)
1460         goto save_png_done;
1461
1462     for (int i = 0; i < kContextHeight; i++)
1463         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1464
1465     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1466     if (png_ptr == NULL)
1467         goto save_png_done;
1468
1469     info_ptr = png_create_info_struct(png_ptr);
1470     if (info_ptr == NULL)
1471         goto save_png_done;
1472
1473     if (setjmp(png_jmpbuf(png_ptr)))
1474         goto save_png_done;
1475
1476     png_init_io(png_ptr, fp);
1477
1478     if (setjmp(png_jmpbuf(png_ptr)))
1479         goto save_png_done;
1480
1481     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1482                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1483                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1484
1485     png_write_info(png_ptr, info_ptr);
1486
1487     if (setjmp(png_jmpbuf(png_ptr)))
1488         goto save_png_done;
1489
1490         png_write_image(png_ptr, row_pointers);
1491
1492         if (setjmp(png_jmpbuf(png_ptr)))
1493         goto save_png_done;
1494
1495     png_write_end(png_ptr, NULL);
1496     retval = true;
1497
1498 save_png_done:
1499     png_destroy_write_struct(&png_ptr, &info_ptr);
1500     delete[] screenshot;
1501     delete[] row_pointers;
1502     if (fp)
1503         fclose(fp);
1504     if (!retval)
1505         unlink(ConvertFileName(file_name));
1506     return retval;
1507 }
1508
1509
1510