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