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