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