]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Allow Mac OS X builds to quit with Apple-Q hotkey.
[lugaru.git] / Source / OpenGL_Windows.cpp
1
2 #ifdef WIN32
3 #include <vld.h>
4 #endif
5
6 #include "Game.h"
7
8 #ifndef USE_DEVIL
9 #  ifdef WIN32
10 #    define USE_DEVIL
11 #  endif
12 #endif
13
14 #if USE_DEVIL
15     #include "IL/il.h"
16     #include "IL/ilu.h"
17     #include "IL/ilut.h"
18 #else
19     // just use libpng and libjpg directly; it's lighter-weight and easier
20     //  to manage the dependencies on Linux...
21     extern "C" {
22         #include "png.h"
23         #include "jpeglib.h"
24     }
25     static bool load_image(const char * fname, TGAImageRec & tex);
26     static bool load_png(const char * fname, TGAImageRec & tex);
27     static bool load_jpg(const char * fname, TGAImageRec & tex);
28     static bool save_image(const char * fname);
29     static bool save_png(const char * fname);
30 #endif
31
32 // ADDED GWC
33 #ifdef _MSC_VER
34 #pragma comment(lib, "opengl32.lib")
35 #pragma comment(lib, "glu32.lib")
36 #pragma comment(lib, "glaux.lib")
37 #endif
38
39 extern bool buttons[3];
40 extern float multiplier;
41 extern float screenwidth,screenheight;
42 extern float sps;
43 extern float realmultiplier;
44 extern int slomo;
45 extern bool ismotionblur;
46 extern float usermousesensitivity;
47 extern int detail;
48 extern bool floatjump;
49 extern bool cellophane;
50 // MODIFIED GWC
51 //extern int terraindetail;
52 //extern int texdetail;
53 extern float terraindetail;
54 extern float texdetail;
55 extern int bloodtoggle;
56 extern bool osx;
57 extern bool autoslomo;
58 extern bool foliage;
59 extern bool musictoggle;
60 extern bool trilinear;
61 extern float gamespeed;
62 extern int difficulty;
63 extern bool damageeffects;
64 extern int numplayers;
65 extern bool decals;
66 extern bool invertmouse;
67 extern bool texttoggle;
68 extern bool ambientsound;
69 extern bool mousejump;
70 extern bool freeze;
71 extern Person player[maxplayers];
72 extern bool vblsync;
73 extern bool stillloading;
74 extern bool showpoints;
75 extern bool alwaysblur;
76 extern bool immediate;
77 extern bool velocityblur;
78 extern bool debugmode;
79 extern int mainmenu;
80 /*extern*/ bool gameFocused;
81 extern int kBitsPerPixel;
82 extern float slomospeed;
83 extern float slomofreq;
84 extern float oldgamespeed;
85 extern float volume;
86
87 #include <math.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <fstream>
91 #include <iostream>
92 #include "gamegl.h"
93 #include "MacCompatibility.h"
94
95 #ifdef WIN32
96 #include <shellapi.h>
97 #endif
98
99 #include "fmod.h"
100
101 #include "res/resource.h"
102
103 using namespace std;
104
105
106 unsigned int resolutionDepths[8][2] = {0};
107
108 bool selectDetail(int & width, int & height, int & bpp, int & detail);
109 int closestResolution(int width, int height);
110 int resolutionID(int width, int height);
111
112 void ReportError (char * strError);
113
114 void SetupDSpFullScreen();
115 void ShutdownDSp();
116
117 void DrawGL(Game & game);
118
119 void CreateGLWindow (void);
120 Boolean SetUp (Game & game);
121 void DoKey (SInt8 theKey, SInt8 theCode);
122 void DoUpdate (Game & game);
123
124 void DoEvent (void);
125 void CleanUp (void);
126
127
128 // statics/globals (internal only) ------------------------------------------
129 #ifndef WIN32
130 typedef struct tagPOINT { 
131   int x;
132   int y;
133 } POINT, *PPOINT; 
134 #endif
135
136 #if USE_SDL
137 #define GL_FUNC(ret,fn,params,call,rt) \
138     extern "C" { \
139         static ret GLAPIENTRY (*p##fn) params = NULL; \
140         ret GLAPIENTRY fn params { rt p##fn call; } \
141     }
142 #include "glstubs.h"
143 #undef GL_FUNC
144
145 static bool lookup_glsym(const char *funcname, void **func)
146 {
147     *func = SDL_GL_GetProcAddress(funcname);
148     if (*func == NULL)
149     {
150         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
151         return false;
152     }
153     return true;
154 }
155
156 static bool lookup_all_glsyms(void)
157 {
158     bool retval = true;
159     #define GL_FUNC(ret,fn,params,call,rt) \
160         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
161     #include "glstubs.h"
162     #undef GL_FUNC
163     return retval;
164 }
165
166 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
167 {
168     // no-op.
169 }
170
171
172
173 void sdlGetCursorPos(POINT *pt)
174 {
175     int x, y;
176     SDL_GetMouseState(&x, &y);
177     pt->x = x;
178     pt->y = y;
179 }
180 #define GetCursorPos(x) sdlGetCursorPos(x)
181 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
182 #define ScreenToClient(x, pt)
183 #define ClientToScreen(x, pt)
184 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
185 #endif
186
187 Point delta;
188
189 #ifdef WIN32
190 static const char g_wndClassName[]={ "LUGARUWINDOWCLASS" };
191 static HINSTANCE g_appInstance;
192 static HWND g_windowHandle;
193 static HGLRC hRC;
194 #endif
195
196 static bool g_button, fullscreen = true;
197
198
199 // Menu defs
200 enum 
201 {
202         kFileQuit = 1
203 };
204
205 enum 
206 {
207         kForegroundSleep = 10,
208         kBackgroundSleep = 10000
209 };
210
211
212 int kContextWidth;
213 int kContextHeight;
214
215 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
216
217 GLuint gFontList;
218 char gcstrMode [256] = "";
219
220 UInt32 gSleepTime = kForegroundSleep;
221 Boolean gDone = false, gfFrontProcess = true;
222
223 Game * pgame = 0;
224
225
226 static int _argc = 0;
227 static char **_argv = NULL;
228
229 bool cmdline(const char *cmd)
230 {
231     for (int i = 1; i < _argc; i++)
232     {
233         char *arg = _argv[i];
234         while (*arg == '-')
235             arg++;
236         if (stricmp(arg, cmd) == 0)
237             return true;
238     }
239
240     return false;
241 }
242
243
244 // --------------------------------------------------------------------------
245
246 void ReportError (char * strError)
247 {
248 #ifdef WIN32  // !!! FIXME.  --ryan.
249         throw std::exception( strError);
250 #endif
251
252         /*      char errMsgCStr [256];
253         Str255 strErr;
254
255         sprintf (errMsgCStr, "%s", strError); 
256
257         // out as debug string
258         CToPStr (strErr, errMsgCStr);
259         DebugStr (strErr);
260         */
261 }
262
263 void SetupDSpFullScreen ()
264 {
265 #ifdef WIN32
266         LOGFUNC;
267
268         if (fullscreen)
269         {
270                 DEVMODE dmScreenSettings;
271                 memset( &dmScreenSettings, 0, sizeof( dmScreenSettings));
272                 dmScreenSettings.dmSize = sizeof( dmScreenSettings);
273                 dmScreenSettings.dmPelsWidth    = kContextWidth;
274                 dmScreenSettings.dmPelsHeight   = kContextHeight;
275                 dmScreenSettings.dmBitsPerPel   = kBitsPerPixel;
276                 dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
277
278                 // set video mode
279                 if (ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
280                 {
281                         ReportError( "Could not set display mode");
282                         return;
283                 }
284         }
285
286         ShowCursor(FALSE);
287 #endif
288 }
289
290
291 void ShutdownDSp ()
292 {
293 #ifdef WIN32
294         LOGFUNC;
295
296         if (fullscreen)
297         {
298                 ChangeDisplaySettings( NULL, 0);
299         }
300
301         ShowCursor(TRUE);
302 #endif
303 }
304
305
306 //-----------------------------------------------------------------------------------------------------------------------
307
308 // OpenGL Drawing
309
310 void DrawGL (Game & game)
311 {
312 #ifdef WIN32
313         if (hDC == 0)
314                 return;
315 #endif
316
317         game.DrawGLScene();
318 }
319
320
321 static KeyMap g_theKeys;
322
323 void SetKey( int key)
324 {
325     g_theKeys[ key >> 3] |= (1 << (key & 7));
326 }
327
328 void ClearKey( int key)
329 {
330     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
331 }
332
333 void GetKeys(  unsigned char theKeys[16])
334 {
335     memcpy( theKeys, &g_theKeys, 16);
336 }
337
338 Boolean Button()
339 {
340     return g_button;
341 }
342
343 #if !USE_SDL
344 static void initSDLKeyTable(void) {}
345 #else
346 #define MAX_SDLKEYS SDLK_LAST
347 static unsigned short KeyTable[MAX_SDLKEYS];
348
349 static void initSDLKeyTable(void)
350 {
351     memset(KeyTable, 0xFF, sizeof (KeyTable));
352     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
353     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
354     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
355     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
356     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
357     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
358     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
359     KeyTable[SDLK_END] = MAC_END_KEY;
360     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
361     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
362     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
363     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
364     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
365     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
366     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
367     KeyTable[SDLK_0] = MAC_0_KEY;
368     KeyTable[SDLK_1] = MAC_1_KEY;
369     KeyTable[SDLK_2] = MAC_2_KEY;
370     KeyTable[SDLK_3] = MAC_3_KEY;
371     KeyTable[SDLK_4] = MAC_4_KEY;
372     KeyTable[SDLK_5] = MAC_5_KEY;
373     KeyTable[SDLK_6] = MAC_6_KEY;
374     KeyTable[SDLK_7] = MAC_7_KEY;
375     KeyTable[SDLK_8] = MAC_8_KEY;
376     KeyTable[SDLK_9] = MAC_9_KEY;
377     KeyTable[SDLK_a] = MAC_A_KEY;
378     KeyTable[SDLK_b] = MAC_B_KEY;
379     KeyTable[SDLK_c] = MAC_C_KEY;
380     KeyTable[SDLK_d] = MAC_D_KEY;
381     KeyTable[SDLK_e] = MAC_E_KEY;
382     KeyTable[SDLK_f] = MAC_F_KEY;
383     KeyTable[SDLK_g] = MAC_G_KEY;
384     KeyTable[SDLK_h] = MAC_H_KEY;
385     KeyTable[SDLK_i] = MAC_I_KEY;
386     KeyTable[SDLK_j] = MAC_J_KEY;
387     KeyTable[SDLK_k] = MAC_K_KEY;
388     KeyTable[SDLK_l] = MAC_L_KEY;
389     KeyTable[SDLK_m] = MAC_M_KEY;
390     KeyTable[SDLK_n] = MAC_N_KEY;
391     KeyTable[SDLK_o] = MAC_O_KEY;
392     KeyTable[SDLK_p] = MAC_P_KEY;
393     KeyTable[SDLK_q] = MAC_Q_KEY;
394     KeyTable[SDLK_r] = MAC_R_KEY;
395     KeyTable[SDLK_s] = MAC_S_KEY;
396     KeyTable[SDLK_t] = MAC_T_KEY;
397     KeyTable[SDLK_u] = MAC_U_KEY;
398     KeyTable[SDLK_v] = MAC_V_KEY;
399     KeyTable[SDLK_w] = MAC_W_KEY;
400     KeyTable[SDLK_x] = MAC_X_KEY;
401     KeyTable[SDLK_y] = MAC_Y_KEY;
402     KeyTable[SDLK_z] = MAC_Z_KEY;
403     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
404     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
405     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
406     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
407     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
408     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
409     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
410     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
411     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
412     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
413     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
414     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
415     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
416     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
417     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
418     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
419     KeyTable[SDLK_F1] = MAC_F1_KEY;
420     KeyTable[SDLK_F2] = MAC_F2_KEY;
421     KeyTable[SDLK_F3] = MAC_F3_KEY;
422     KeyTable[SDLK_F4] = MAC_F4_KEY;
423     KeyTable[SDLK_F5] = MAC_F5_KEY;
424     KeyTable[SDLK_F6] = MAC_F6_KEY;
425     KeyTable[SDLK_F7] = MAC_F7_KEY;
426     KeyTable[SDLK_F8] = MAC_F8_KEY;
427     KeyTable[SDLK_F9] = MAC_F9_KEY;
428     KeyTable[SDLK_F10] = MAC_F10_KEY;
429     KeyTable[SDLK_F11] = MAC_F11_KEY;
430     KeyTable[SDLK_F12] = MAC_F12_KEY;
431     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
432     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
433     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
434     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
435     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
436     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
437     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
438     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
439     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
440     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
441     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
442 }
443
444 static inline int clamp_sdl_mouse_button(Uint8 button)
445 {
446     if (button == 2)   // right mouse button is button 3 in SDL.
447         button = 3;
448     else if (button == 3)
449         button = 2;
450
451     if ((button >= 1) && (button <= 3))
452         return button - 1;
453     return -1;
454 }
455
456 static void sdlEventProc(const SDL_Event &e, Game &game)
457 {
458     int val;
459     SDLMod mod;
460
461     switch(e.type)
462         {
463         case SDL_MOUSEMOTION:
464             game.deltah += e.motion.xrel;
465             game.deltav += e.motion.yrel;
466             return;
467
468                 case SDL_MOUSEBUTTONDOWN:
469                         {
470                 val = clamp_sdl_mouse_button(e.button.button);
471                 if ((val >= 0) && (val <= 2))
472                 {
473                     if (val == 0)
474                                     g_button = true;
475                                 buttons[val] = true;
476                 }
477                         }
478                         return;
479
480                 case SDL_MOUSEBUTTONUP:
481                         {
482                 val = clamp_sdl_mouse_button(e.button.button);
483                 if ((val >= 0) && (val <= 2))
484                 {
485                     if (val == 0)
486                                     g_button = false;
487                                 buttons[val] = false;
488                 }
489                         }
490             return;
491
492         case SDL_KEYDOWN:
493             if (e.key.keysym.sym == SDLK_g)
494             {
495                 if (e.key.keysym.mod & KMOD_CTRL)
496                 {
497                     SDL_GrabMode mode = SDL_GRAB_ON;
498                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
499                     {
500                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
501                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
502                     }
503                     SDL_WM_GrabInput(mode);
504                 }
505             }
506
507             #if (defined(__APPLE__) && defined(__MACH__))
508             if (e.key.keysym.sym == SDLK_q)
509             {
510                 if (e.key.keysym.mod & KMOD_META)
511                 {
512                     gDone=true;
513                 }
514             }
515             #endif
516
517             else if (e.key.keysym.sym == SDLK_RETURN)
518             {
519                 if (e.key.keysym.mod & KMOD_ALT)
520                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
521             }
522
523             if (e.key.keysym.sym < SDLK_LAST)
524             {
525                 if (KeyTable[e.key.keysym.sym] != 0xffff)
526                     SetKey(KeyTable[e.key.keysym.sym]);
527             }
528
529             mod = SDL_GetModState();
530             if (mod & KMOD_CTRL)
531                 SetKey(MAC_CONTROL_KEY);
532             if (mod & KMOD_ALT)
533                 SetKey(MAC_OPTION_KEY);
534             if (mod & KMOD_SHIFT)
535                 SetKey(MAC_SHIFT_KEY);
536             if (mod & KMOD_CAPS)
537                 SetKey(MAC_CAPS_LOCK_KEY);
538
539             return;
540
541         case SDL_KEYUP:
542             if (e.key.keysym.sym < SDLK_LAST)
543             {
544                 if (KeyTable[e.key.keysym.sym] != 0xffff)
545                     ClearKey(KeyTable[e.key.keysym.sym]);
546             }
547
548             mod = SDL_GetModState();
549             if ((mod & KMOD_CTRL) == 0)
550                 ClearKey(MAC_CONTROL_KEY);
551             if ((mod & KMOD_ALT) == 0)
552                 ClearKey(MAC_OPTION_KEY);
553             if ((mod & KMOD_SHIFT) == 0)
554                 ClearKey(MAC_SHIFT_KEY);
555             if ((mod & KMOD_CAPS) == 0)
556                 ClearKey(MAC_CAPS_LOCK_KEY);
557             return;
558     }
559 }
560 #endif
561
562 // --------------------------------------------------------------------------
563
564 static Point gMidPoint;
565
566 Boolean SetUp (Game & game)
567 {
568         char string[10];
569
570         LOGFUNC;
571
572         randSeed = UpTime().lo;
573
574         osx = 0;
575         ifstream ipstream(ConvertFileName(":Data:config.txt"), std::ios::in /*| std::ios::nocreate*/);
576         detail=1;
577         ismotionblur=0;
578         usermousesensitivity=1;
579         kContextWidth=640;
580         kContextHeight=480;
581         kBitsPerPixel = 32;
582         floatjump=0;
583         cellophane=0;
584         texdetail=4;
585         autoslomo=1;
586         decals=1;
587         invertmouse=0;
588         bloodtoggle=0;
589         terraindetail=2;
590         foliage=1;
591         musictoggle=1;
592         trilinear=1;
593         gamespeed=1;
594         difficulty=1;
595         damageeffects=0;
596         texttoggle=1;
597         alwaysblur=0;
598         showpoints=0;
599         immediate=0;
600         velocityblur=0;
601
602         slomospeed=0.25;
603         slomofreq=8012;
604
605         volume = 0.8f;
606
607         game.crouchkey=MAC_SHIFT_KEY;
608         game.jumpkey=MAC_SPACE_KEY;
609         game.leftkey=MAC_A_KEY;
610         game.forwardkey=MAC_W_KEY;
611         game.backkey=MAC_S_KEY;
612         game.rightkey=MAC_D_KEY;
613         game.drawkey=MAC_E_KEY;
614         game.throwkey=MAC_Q_KEY;
615         game.attackkey=MAC_MOUSEBUTTON1;
616         game.chatkey=MAC_T_KEY;
617         numplayers=1;
618         ambientsound=1;
619         vblsync=0;
620         debugmode=0;
621
622         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
623
624         if(!ipstream) {
625                 ofstream opstream(ConvertFileName(":Data:config.txt", "w"));
626                 opstream << "Screenwidth:\n";
627                 opstream << kContextWidth;
628                 opstream << "\nScreenheight:\n";
629                 opstream << kContextHeight;
630                 opstream << "\nMouse sensitivity:\n";
631                 opstream << usermousesensitivity;
632                 opstream << "\nBlur(0,1):\n";
633                 opstream << ismotionblur;
634                 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
635                 opstream << detail;
636                 opstream << "\nFloating jump:\n";
637                 opstream << floatjump;
638                 opstream << "\nMouse jump:\n";
639                 opstream << mousejump;
640                 opstream << "\nAmbient sound:\n";
641                 opstream << ambientsound;
642                 opstream << "\nBlood (0,1,2):\n";
643                 opstream << bloodtoggle;
644                 opstream << "\nAuto slomo:\n";
645                 opstream << autoslomo;
646                 opstream << "\nFoliage:\n";
647                 opstream << foliage;
648                 opstream << "\nMusic:\n";
649                 opstream << musictoggle;
650                 opstream << "\nTrilinear:\n";
651                 opstream << trilinear;
652                 opstream << "\nDecals(shadows,blood puddles,etc):\n";
653                 opstream << decals;
654                 opstream << "\nInvert mouse:\n";
655                 opstream << invertmouse;
656                 opstream << "\nGamespeed:\n";
657                 opstream << gamespeed;
658                 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
659                 opstream << difficulty;
660                 opstream << "\nDamage effects(blackout, doublevision):\n";
661                 opstream << damageeffects;
662                 opstream << "\nText:\n";
663                 opstream << texttoggle;
664                 opstream << "\nDebug:\n";
665                 opstream << debugmode;
666                 opstream << "\nVBL Sync:\n";
667                 opstream << vblsync;
668                 opstream << "\nShow Points:\n";
669                 opstream << showpoints;
670                 opstream << "\nAlways Blur:\n";
671                 opstream << alwaysblur;
672                 opstream << "\nImmediate mode (turn on on G5):\n";
673                 opstream << immediate;
674                 opstream << "\nVelocity blur:\n";
675                 opstream << velocityblur;
676                 opstream << "\nVolume:\n";
677                 opstream << volume;
678                 opstream << "\nForward key:\n";
679                 opstream << KeyToChar(game.forwardkey);
680                 opstream << "\nBack key:\n";
681                 opstream << KeyToChar(game.backkey);
682                 opstream << "\nLeft key:\n";
683                 opstream << KeyToChar(game.leftkey);
684                 opstream << "\nRight key:\n";
685                 opstream << KeyToChar(game.rightkey);
686                 opstream << "\nJump key:\n";
687                 opstream << KeyToChar(game.jumpkey);
688                 opstream << "\nCrouch key:\n";
689                 opstream << KeyToChar(game.crouchkey);
690                 opstream << "\nDraw key:\n";
691                 opstream << KeyToChar(game.drawkey);
692                 opstream << "\nThrow key:\n";
693                 opstream << KeyToChar(game.throwkey);
694                 opstream << "\nAttack key:\n";
695                 opstream << KeyToChar(game.attackkey);
696                 opstream << "\nChat key:\n";
697                 opstream << KeyToChar(game.chatkey);
698                 opstream.close();
699         }
700         if(ipstream){
701                 int i;
702                 ipstream.ignore(256,'\n');
703                 ipstream >> kContextWidth;
704                 ipstream.ignore(256,'\n');
705                 ipstream.ignore(256,'\n');
706                 ipstream >> kContextHeight;
707                 ipstream.ignore(256,'\n');
708                 ipstream.ignore(256,'\n');
709                 ipstream >> usermousesensitivity;
710                 ipstream.ignore(256,'\n');
711                 ipstream.ignore(256,'\n');
712                 ipstream >> i;
713                 ismotionblur = (i != 0);
714                 ipstream.ignore(256,'\n');
715                 ipstream.ignore(256,'\n');
716                 ipstream >> detail;
717                 if(detail!=0)kBitsPerPixel=32;
718                 else kBitsPerPixel=16;
719                 ipstream.ignore(256,'\n');
720                 ipstream.ignore(256,'\n');
721                 ipstream >> i;
722                 floatjump = (i != 0);
723                 ipstream.ignore(256,'\n');
724                 ipstream.ignore(256,'\n');
725                 ipstream >> i;
726                 mousejump = (i != 0);
727                 ipstream.ignore(256,'\n');
728                 ipstream.ignore(256,'\n');
729                 ipstream >> i;
730                 ambientsound = (i != 0);
731                 ipstream.ignore(256,'\n');
732                 ipstream.ignore(256,'\n');
733                 ipstream >> bloodtoggle;
734                 ipstream.ignore(256,'\n');
735                 ipstream.ignore(256,'\n');
736                 ipstream >> i;
737                 autoslomo = (i != 0);
738                 ipstream.ignore(256,'\n');
739                 ipstream.ignore(256,'\n');
740                 ipstream >> i;
741                 foliage = (i != 0);
742                 ipstream.ignore(256,'\n');
743                 ipstream.ignore(256,'\n');
744                 ipstream >> i;
745                 musictoggle = (i != 0);
746                 ipstream.ignore(256,'\n');
747                 ipstream.ignore(256,'\n');
748                 ipstream >> i;
749                 trilinear = (i != 0);
750                 ipstream.ignore(256,'\n');
751                 ipstream.ignore(256,'\n');
752                 ipstream >> i;
753                 decals = (i != 0);
754                 ipstream.ignore(256,'\n');
755                 ipstream.ignore(256,'\n');
756                 ipstream >> i;
757                 invertmouse = (i != 0);
758                 ipstream.ignore(256,'\n');
759                 ipstream.ignore(256,'\n');
760                 ipstream >> gamespeed;
761                 oldgamespeed=gamespeed;
762                 if(oldgamespeed==0){
763                         gamespeed=1;
764                         oldgamespeed=1;
765                 }
766                 ipstream.ignore(256,'\n');
767                 ipstream.ignore(256,'\n');
768                 ipstream >> difficulty;
769                 ipstream.ignore(256,'\n');
770                 ipstream.ignore(256,'\n');
771                 ipstream >> i;
772                 damageeffects = (i != 0);
773                 ipstream.ignore(256,'\n');
774                 ipstream.ignore(256,'\n');
775                 ipstream >> i;
776                 texttoggle = (i != 0);
777                 ipstream.ignore(256,'\n');
778                 ipstream.ignore(256,'\n');
779                 ipstream >> i;
780                 debugmode = (i != 0);
781                 ipstream.ignore(256,'\n');
782                 ipstream.ignore(256,'\n');
783                 ipstream >> i;
784                 vblsync = (i != 0);
785                 ipstream.ignore(256,'\n');
786                 ipstream.ignore(256,'\n');
787                 ipstream >> i;
788                 showpoints = (i != 0);
789                 ipstream.ignore(256,'\n');
790                 ipstream.ignore(256,'\n');
791                 ipstream >> i;
792                 alwaysblur = (i != 0);
793                 ipstream.ignore(256,'\n');
794                 ipstream.ignore(256,'\n');
795                 ipstream >> i;
796                 immediate = (i != 0);
797                 ipstream.ignore(256,'\n');
798                 ipstream.ignore(256,'\n');
799                 ipstream >> i;
800                 velocityblur = (i != 0);
801                 ipstream.ignore(256,'\n');
802                 ipstream.ignore(256,'\n'); 
803                 ipstream >> volume;
804                 ipstream.ignore(256,'\n');
805                 ipstream.ignore(256,'\n'); 
806                 ipstream >> string;
807                 game.forwardkey=CharToKey(string);
808                 ipstream.ignore(256,'\n');
809                 ipstream.ignore(256,'\n');
810                 ipstream >> string;
811                 game.backkey=CharToKey(string);
812                 ipstream.ignore(256,'\n');
813                 ipstream.ignore(256,'\n');
814                 ipstream >> string;
815                 game.leftkey=CharToKey(string);
816                 ipstream.ignore(256,'\n');
817                 ipstream.ignore(256,'\n');
818                 ipstream >> string;
819                 game.rightkey=CharToKey(string);
820                 ipstream.ignore(256,'\n');
821                 ipstream.ignore(256,'\n');
822                 ipstream >> string;
823                 game.jumpkey=CharToKey(string);
824                 ipstream.ignore(256,'\n');
825                 ipstream.ignore(256,'\n');
826                 ipstream >> string;
827                 game.crouchkey=CharToKey(string);
828                 ipstream.ignore(256,'\n');
829                 ipstream.ignore(256,'\n');
830                 ipstream >> string;
831                 game.drawkey=CharToKey(string);
832                 ipstream.ignore(256,'\n');
833                 ipstream.ignore(256,'\n');
834                 ipstream >> string;
835                 game.throwkey=CharToKey(string);
836                 ipstream.ignore(256,'\n');
837                 ipstream.ignore(256,'\n');
838                 ipstream >> string;
839                 game.attackkey=CharToKey(string);
840                 ipstream.ignore(256,'\n');
841                 ipstream.ignore(256,'\n');
842                 ipstream >> string;
843                 game.chatkey=CharToKey(string);
844                 ipstream.close();
845
846                 if(detail>2)detail=2;
847                 if(detail<0)detail=0;
848                 if(screenwidth>3000)screenwidth=640;
849                 if(screenwidth<0)screenwidth=640;
850                 if(screenheight>3000)screenheight=480;
851                 if(screenheight<0)screenheight=480;
852         }
853         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
854                 kBitsPerPixel=16;
855         }
856
857
858         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
859
860         SetupDSpFullScreen();
861
862 #if USE_SDL
863     if (!SDL_WasInit(SDL_INIT_VIDEO))
864     {
865         if (SDL_Init(SDL_INIT_VIDEO) == -1)
866         {
867             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
868             return false;
869         }
870
871         if (SDL_GL_LoadLibrary(NULL) == -1)
872         {
873             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
874             SDL_Quit();
875             return false;
876         }
877     }
878
879     Uint32 sdlflags = SDL_OPENGL;
880     if (!cmdline("windowed"))
881         sdlflags |= SDL_FULLSCREEN;
882
883     SDL_WM_SetCaption("Lugaru", "Lugaru");
884
885     SDL_ShowCursor(0);
886
887     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
888     {
889         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
890         return false;
891     }
892
893     if (!lookup_all_glsyms())
894     {
895         SDL_Quit();
896         return false;
897     }
898
899     if (!cmdline("nomousegrab"))
900         SDL_WM_GrabInput(SDL_GRAB_ON);
901
902 #elif (defined WIN32)
903         //------------------------------------------------------------------
904         // create window
905         int x = 0, y = 0;
906         RECT r = {0, 0, kContextWidth-1, kContextHeight-1};
907         DWORD dwStyle = WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE;
908         DWORD dwExStyle = WS_EX_APPWINDOW;
909
910         if (fullscreen)
911         {
912                 dwStyle |= WS_POPUP;
913         }
914         else
915         {
916
917                 dwStyle |= WS_OVERLAPPEDWINDOW;
918                 dwExStyle |= WS_EX_WINDOWEDGE;
919         }
920
921         AdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);
922
923         if (!fullscreen)
924         {
925                 x = (GetSystemMetrics(SM_CXSCREEN) >> 1) - ((r.right - r.left + 1) >> 1);
926                 y = (GetSystemMetrics(SM_CYSCREEN) >> 1) - ((r.bottom - r.top + 1) >> 1);
927         }
928
929         g_windowHandle=CreateWindowEx(
930                 dwExStyle,
931                 g_wndClassName, "Lugaru", dwStyle,
932                 x, y,
933 //              kContextWidth, kContextHeight,
934                 r.right - r.left + 1, r.bottom - r.top + 1,
935                 NULL,NULL,g_appInstance,NULL );
936         if (!g_windowHandle)
937         {
938                 ReportError("Could not create window");
939                 return false;
940         }
941
942         //------------------------------------------------------------------
943         // setup OpenGL
944
945         static PIXELFORMATDESCRIPTOR pfd =
946         {
947                 sizeof(PIXELFORMATDESCRIPTOR),                          // Size Of This Pixel Format Descriptor
948                         1,                                                                                      // Version Number
949                         PFD_DRAW_TO_WINDOW |                                            // Format Must Support Window
950                         PFD_SUPPORT_OPENGL |                                            // Format Must Support OpenGL
951                         PFD_DOUBLEBUFFER,                                                       // Must Support Double Buffering
952                         PFD_TYPE_RGBA,                                                          // Request An RGBA Format
953                         kBitsPerPixel,                                                          // Select Our Color Depth
954                         0, 0, 0, 0, 0, 0,                                                       // Color Bits Ignored
955                         0,                                                                                      // No Alpha Buffer
956                         0,                                                                                      // Shift Bit Ignored
957                         0,                                                                                      // No Accumulation Buffer
958                         0, 0, 0, 0,                                                                     // Accumulation Bits Ignored
959                         16,                                                                                     // 16Bit Z-Buffer (Depth Buffer)  
960                         0,                                                                                      // No Stencil Buffer
961                         0,                                                                                      // No Auxiliary Buffer
962                         PFD_MAIN_PLANE,                                                         // Main Drawing Layer
963                         0,                                                                                      // Reserved
964                         0, 0, 0                                                                         // Layer Masks Ignored
965         };
966
967         if (!(hDC = GetDC( g_windowHandle)))
968                 ReportError( "Could not get device context");
969
970         GLuint PixelFormat;
971         if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))
972         {
973                 ReportError( "Could not find appropriate pixel format");
974                 return false;
975         }
976
977         if (!DescribePixelFormat(hDC, PixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd))
978         {
979                 ReportError( "Could not retrieve pixel format");
980                 return false;
981         }
982
983         if (!SetPixelFormat( hDC, PixelFormat, &pfd))
984         {
985                 ReportError( "Could not set pixel format");
986                 return false;
987         }
988
989         if (!(hRC = wglCreateContext(hDC)))
990         {
991                 ReportError( "Could not create rendering context");
992                 return false;
993         }
994
995         if (!wglMakeCurrent(hDC, hRC))
996         {
997                 ReportError( "Could not activate rendering context");
998                 return false;
999         }
1000
1001         if (fullscreen)
1002         {
1003                 // Place the window above all topmost windows
1004                 SetWindowPos( g_windowHandle, HWND_TOPMOST, 0,0,0,0,
1005                         SWP_NOMOVE | SWP_NOSIZE );
1006         }
1007
1008         SetForegroundWindow(g_windowHandle);
1009         SetFocus(g_windowHandle);
1010 #endif
1011
1012         glClear( GL_COLOR_BUFFER_BIT );
1013         swap_gl_buffers();
1014
1015         // clear all states
1016         glDisable( GL_ALPHA_TEST);
1017         glDisable( GL_BLEND);
1018         glDisable( GL_DEPTH_TEST);
1019         //      glDisable( GL_DITHER);
1020         glDisable( GL_FOG);
1021         glDisable( GL_LIGHTING);
1022         glDisable( GL_LOGIC_OP);
1023         glDisable( GL_STENCIL_TEST);
1024         glDisable( GL_TEXTURE_1D);
1025         glDisable( GL_TEXTURE_2D);
1026         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
1027         glPixelTransferi( GL_RED_SCALE, 1);
1028         glPixelTransferi( GL_RED_BIAS, 0);
1029         glPixelTransferi( GL_GREEN_SCALE, 1);
1030         glPixelTransferi( GL_GREEN_BIAS, 0);
1031         glPixelTransferi( GL_BLUE_SCALE, 1);
1032         glPixelTransferi( GL_BLUE_BIAS, 0);
1033         glPixelTransferi( GL_ALPHA_SCALE, 1);
1034         glPixelTransferi( GL_ALPHA_BIAS, 0);
1035
1036         // set initial rendering states
1037         glShadeModel( GL_SMOOTH);
1038         glClearDepth( 1.0f);
1039         glDepthFunc( GL_LEQUAL);
1040         glDepthMask( GL_TRUE);
1041         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
1042         glEnable( GL_DEPTH_TEST);
1043         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
1044         glCullFace( GL_FRONT);
1045         glEnable( GL_CULL_FACE);
1046         glEnable( GL_LIGHTING);
1047 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
1048         glEnable( GL_DITHER);
1049         glEnable( GL_COLOR_MATERIAL);
1050         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1051         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1052         glAlphaFunc( GL_GREATER, 0.5f);
1053
1054 #if USE_DEVIL
1055         if (ilGetInteger(IL_VERSION_NUM) < IL_VERSION ||
1056                 iluGetInteger(ILU_VERSION_NUM) < ILU_VERSION ||
1057                 ilutGetInteger(ILUT_VERSION_NUM) < ILUT_VERSION)
1058         {
1059                 ReportError("DevIL version is different...exiting!\n");
1060                 return false;
1061         }
1062
1063         ilInit();
1064         iluInit();
1065         ilutInit();
1066
1067         ilutRenderer(ILUT_OPENGL);
1068
1069         ilEnable(IL_ORIGIN_SET);
1070         ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
1071 #endif
1072
1073         GLint width = kContextWidth;
1074         GLint height = kContextHeight;
1075         gMidPoint.h = width / 2;
1076         gMidPoint.v = height / 2;
1077         screenwidth=width;
1078         screenheight=height;
1079
1080         game.newdetail=detail;
1081         game.newscreenwidth=screenwidth;
1082         game.newscreenheight=screenheight;
1083
1084         game.InitGame();
1085
1086         return true;
1087 }
1088
1089
1090 static void DoMouse(Game & game)
1091 {
1092 #if USE_SDL
1093         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1094         {
1095                 game.deltah *= usermousesensitivity;
1096                 game.deltav *= usermousesensitivity;
1097                 game.mousecoordh += game.deltah;
1098                 game.mousecoordv += game.deltav;
1099         if (game.mousecoordh < 0)
1100             game.mousecoordh = 0;
1101         else if (game.mousecoordh >= kContextWidth)
1102             game.mousecoordh = kContextWidth - 1;
1103         if (game.mousecoordv < 0)
1104             game.mousecoordv = 0;
1105         else if (game.mousecoordv >= kContextHeight)
1106             game.mousecoordv = kContextHeight - 1;
1107         }
1108 #else
1109         static Point lastMouse = {-1,-1};
1110         Point globalMouse;
1111
1112         POINT pos;
1113         GetCursorPos(&pos);
1114         ScreenToClient(g_windowHandle, &pos);
1115         globalMouse.h = pos.x;
1116         globalMouse.v = pos.y;
1117
1118         if (lastMouse.h == globalMouse.h && lastMouse.v == globalMouse.v)
1119         {
1120                 game.deltah=0;
1121                 game.deltav=0;
1122         }
1123         else
1124         {
1125                 static Point virtualMouse = {0,0};
1126                 delta = globalMouse;
1127
1128                 delta.h -= lastMouse.h;
1129                 delta.v -= lastMouse.v;
1130                 lastMouse.h = pos.x;
1131                 lastMouse.v = pos.y;
1132
1133                 if(mainmenu||(abs(delta.h)<10*realmultiplier*1000&&abs(delta.v)<10*realmultiplier*1000)){
1134                         game.deltah=delta.h*usermousesensitivity;
1135                         game.deltav=delta.v*usermousesensitivity;
1136                         game.mousecoordh=globalMouse.h;
1137                         game.mousecoordv=globalMouse.v;
1138                 }
1139
1140                 if(!mainmenu)
1141                 {
1142                         if(lastMouse.h>gMidPoint.h+100||lastMouse.h<gMidPoint.h-100||lastMouse.v>gMidPoint.v+100||lastMouse.v<gMidPoint.v-100){
1143                                 pos.x = gMidPoint.h;
1144                                 pos.y = gMidPoint.v;
1145                                 ClientToScreen(g_windowHandle, &pos);
1146                                 //SetCursorPos( gMidPoint.h,gMidPoint.v);
1147                                 SetCursorPos(pos.x, pos.y);
1148                                 lastMouse = gMidPoint;
1149                         }
1150                 }
1151         }
1152 #endif
1153 }
1154
1155
1156
1157 // --------------------------------------------------------------------------
1158
1159 void DoKey (SInt8 theKey, SInt8 theCode)
1160 {
1161         // do nothing
1162 }
1163
1164 // --------------------------------------------------------------------------
1165
1166
1167
1168 void DoFrameRate (int update)
1169 {       
1170         static long frames = 0;
1171
1172         static AbsoluteTime time = {0,0};
1173         static AbsoluteTime frametime = {0,0};
1174         AbsoluteTime currTime = UpTime ();
1175         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1176
1177         if (0 > deltaTime)      // if negative microseconds
1178                 deltaTime /= -1000000.0;
1179         else                            // else milliseconds
1180                 deltaTime /= 1000.0;
1181
1182         multiplier=deltaTime;
1183         if(multiplier<.001)multiplier=.001;
1184         if(multiplier>10)multiplier=10;
1185         if(update)frametime = currTime; // reset for next time interval
1186
1187         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1188
1189         if (0 > deltaTime)      // if negative microseconds
1190                 deltaTime /= -1000000.0;
1191         else                            // else milliseconds
1192                 deltaTime /= 1000.0;
1193         frames++;
1194         if (0.001 <= deltaTime) // has update interval passed
1195         {
1196                 if(update){
1197                         time = currTime;        // reset for next time interval
1198                         frames = 0;
1199                 }
1200         }
1201 }
1202
1203
1204 void DoUpdate (Game & game)
1205 {
1206         static float sps=200;
1207         static int count;
1208         static float oldmult;
1209
1210         DoFrameRate(1);
1211         if(multiplier>.6)multiplier=.6;
1212
1213         game.fps=1/multiplier;
1214
1215         count = multiplier*sps;
1216         if(count<2)count=2;
1217         //if(count>10)count=10;
1218
1219         realmultiplier=multiplier;
1220         multiplier*=gamespeed;
1221         if(difficulty==1)multiplier*=.9;
1222         if(difficulty==0)multiplier*=.8;
1223
1224         if(game.loading==4)multiplier*=.00001;
1225         //multiplier*.9;
1226         if(slomo&&!mainmenu)multiplier*=slomospeed;
1227         //if(freeze)multiplier*=0.00001;
1228         oldmult=multiplier;
1229         multiplier/=(float)count;
1230
1231         DoMouse(game);
1232
1233         game.TickOnce();
1234
1235         for(int i=0;i<count;i++)
1236         {
1237                 game.Tick();
1238         }
1239         multiplier=oldmult;
1240
1241         game.TickOnceAfter();
1242 /* - Debug code to test how many channels were active on average per frame
1243         static long frames = 0;
1244
1245         static AbsoluteTime start = {0,0};
1246         AbsoluteTime currTime = UpTime ();
1247         static int num_channels = 0;
1248         
1249         num_channels += FSOUND_GetChannelsPlaying();
1250         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1251
1252         if (0 > deltaTime)      // if negative microseconds
1253                 deltaTime /= -1000000.0;
1254         else                            // else milliseconds
1255                 deltaTime /= 1000.0;
1256
1257         ++frames;
1258
1259         if (deltaTime >= 1)
1260         {
1261                 start = currTime;
1262                 float avg_channels = (float)num_channels / (float)frames;
1263
1264                 ofstream opstream("log.txt",ios::app); 
1265                 opstream << "Average frame count: ";
1266                 opstream << frames;
1267                 opstream << " frames - ";
1268                 opstream << avg_channels;
1269                 opstream << " per frame.\n";
1270                 opstream.close();
1271
1272                 frames = 0;
1273                 num_channels = 0;
1274         }
1275 */
1276         DrawGL (game);
1277 }
1278
1279 // --------------------------------------------------------------------------
1280
1281
1282 void CleanUp (void)
1283 {
1284         LOGFUNC;
1285
1286 //      game.Dispose();
1287
1288 #if USE_DEVIL
1289         ilShutDown();
1290 #endif
1291
1292 #if USE_SDL
1293     SDL_Quit();
1294     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1295     #include "glstubs.h"
1296     #undef GL_FUNC
1297     // cheat here...static destructors are calling glDeleteTexture() after
1298     //  the context is destroyed and libGL unloaded by SDL_Quit().
1299     pglDeleteTextures = glDeleteTextures_doNothing;
1300
1301 #elif (defined WIN32)
1302         if (hRC)
1303         {
1304                 wglMakeCurrent( NULL, NULL);
1305                 wglDeleteContext( hRC);
1306                 hRC = NULL;
1307         }
1308
1309         if (hDC)
1310         {
1311                 ReleaseDC( g_windowHandle, hDC);
1312                 hDC = NULL;
1313         }
1314
1315         if (g_windowHandle)
1316         {
1317                 ShowWindow( g_windowHandle, SW_HIDE );
1318                 DestroyWindow( g_windowHandle);
1319                 g_windowHandle = NULL;
1320         }
1321
1322         ShutdownDSp ();
1323         ClipCursor(NULL);
1324 #endif
1325 }
1326
1327 // --------------------------------------------------------------------------
1328
1329 static bool g_focused = true;
1330
1331
1332 static bool IsFocused()
1333 {
1334 #ifdef WIN32
1335         if (!g_focused)
1336                 return false;
1337
1338         if (GetActiveWindow() != g_windowHandle)
1339                 return false;
1340
1341         if (IsIconic( g_windowHandle))
1342                 return false;
1343 #endif
1344
1345         return true;
1346 }
1347
1348
1349 static void launch_web_browser(const char *url)
1350 {
1351 #ifdef WIN32
1352     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1353
1354 #elif (defined(__APPLE__) && defined(__MACH__))
1355     const char *fmt = "open '%s'";
1356     const size_t len = strlen(fmt) + strlen(url) + 16;
1357     char *buf = new char[len];
1358     snprintf(buf, len, fmt, url);
1359     system(buf);
1360     delete[] buf;
1361
1362 #elif PLATFORM_LINUX
1363     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1364     const size_t len = strlen(fmt) + strlen(url) + 16;
1365     char *buf = new char[len];
1366     snprintf(buf, len, fmt, url);
1367     system(buf);
1368     delete[] buf;
1369 #endif
1370 }
1371
1372
1373 #ifndef WIN32
1374 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1375 static char *findBinaryInPath(const char *bin, char *envr)
1376 {
1377     size_t alloc_size = 0;
1378     char *exe = NULL;
1379     char *start = envr;
1380     char *ptr;
1381
1382     do
1383     {
1384         size_t size;
1385         ptr = strchr(start, ':');  /* find next $PATH separator. */
1386         if (ptr)
1387             *ptr = '\0';
1388
1389         size = strlen(start) + strlen(bin) + 2;
1390         if (size > alloc_size)
1391         {
1392             char *x = (char *) realloc(exe, size);
1393             if (x == NULL)
1394             {
1395                 if (exe != NULL)
1396                     free(exe);
1397                 return(NULL);
1398             } /* if */
1399
1400             alloc_size = size;
1401             exe = x;
1402         } /* if */
1403
1404         /* build full binary path... */
1405         strcpy(exe, start);
1406         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1407             strcat(exe, "/");
1408         strcat(exe, bin);
1409
1410         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
1411         {
1412             strcpy(exe, start);  /* i'm lazy. piss off. */
1413             return(exe);
1414         } /* if */
1415
1416         start = ptr + 1;  /* start points to beginning of next element. */
1417     } while (ptr != NULL);
1418
1419     if (exe != NULL)
1420         free(exe);
1421
1422     return(NULL);  /* doesn't exist in path. */
1423 } /* findBinaryInPath */
1424
1425
1426 char *calcBaseDir(const char *argv0)
1427 {
1428     /* If there isn't a path on argv0, then look through the $PATH for it. */
1429     char *retval;
1430     char *envr;
1431
1432     char *ptr = strrchr(argv0, '/');
1433     if (strchr(argv0, '/'))
1434     {
1435         retval = strdup(argv0);
1436         if (retval)
1437             *(strrchr(retval, '/')) = '\0';
1438         return(retval);
1439     }
1440
1441     envr = getenv("PATH");
1442     if (!envr) return NULL;
1443     envr = strdup(envr);
1444     if (!envr) return NULL;
1445     retval = findBinaryInPath(argv0, envr);
1446     free(envr);
1447     return(retval);
1448 }
1449
1450 static inline void chdirToAppPath(const char *argv0)
1451 {
1452     char *dir = calcBaseDir(argv0);
1453     if (dir)
1454     {
1455         #if (defined(__APPLE__) && defined(__MACH__))
1456         // Chop off /Contents/MacOS if it's at the end of the string, so we
1457         //  land in the base of the app bundle.
1458         const size_t len = strlen(dir);
1459         const char *bundledirs = "/Contents/MacOS";
1460         const size_t bundledirslen = strlen(bundledirs);
1461         if (len > bundledirslen)
1462         {
1463             char *ptr = (dir + len) - bundledirslen;
1464             if (strcasecmp(ptr, bundledirs) == 0)
1465                 *ptr = '\0';
1466         }
1467         #endif
1468         chdir(dir);
1469         free(dir);
1470     }
1471 }
1472 #endif
1473
1474
1475 int main(int argc, char **argv)
1476 {
1477     _argc = argc;
1478     _argv = argv;
1479 #ifndef WIN32
1480     chdirToAppPath(argv[0]);
1481 #endif
1482
1483         LOGFUNC;
1484
1485 #ifndef WIN32  // this is in WinMain, too.
1486         logger.start(true);
1487         memset( &g_theKeys, 0, sizeof( KeyMap));
1488 #endif
1489
1490     initSDLKeyTable();
1491
1492         try
1493         {
1494                 bool regnow = false;
1495                 {
1496                         Game game;
1497                         pgame = &game;
1498
1499                         //ofstream os("error.txt");
1500                         //os.close();
1501                         //ofstream os("log.txt");
1502                         //os.close();
1503
1504                         if (!SetUp (game))
1505                 return 42;
1506
1507                         while (!gDone&&!game.quit&&(!game.tryquit||!game.registered))
1508                         {
1509                                 if (IsFocused())
1510                                 {
1511                                         gameFocused = true;
1512
1513                                         // check windows messages
1514                                         #if USE_SDL
1515                                         game.deltah = 0;
1516                                         game.deltav = 0;
1517                                         SDL_Event e;
1518                                         // message pump
1519                                         while( SDL_PollEvent( &e ) )
1520                                         {
1521                                                 if( e.type == SDL_QUIT )
1522                                                 {
1523                                                         gDone=true;
1524                                                         break;
1525                                                 }
1526                                                 sdlEventProc(e, game);
1527                                         }
1528
1529                                         #elif (defined WIN32)
1530                                         MSG msg;
1531                                         // message pump
1532                                         while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE | PM_NOYIELD ) )
1533                                         {
1534                                                 if( msg.message == WM_QUIT )
1535                                                 {
1536                                                         gDone=true;
1537                                                         break;
1538                                                 }
1539                                                 else
1540                                                 {
1541                                                         TranslateMessage( &msg );
1542                                                         DispatchMessage( &msg );
1543                                                 }
1544                                         }
1545                                         #endif
1546
1547                                         // game
1548                                         DoUpdate(game);
1549                                 }
1550                                 else
1551                                 {
1552                                         if (gameFocused)
1553                                         {
1554                                                 // allow game chance to pause
1555                                                 gameFocused = false;
1556                                                 DoUpdate(game);
1557                                         }
1558
1559                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1560                     #ifdef WIN32
1561                                         MSG msg;
1562                                         BOOL bRet;
1563                                         //if (GetMessage( &msg, g_windowHandle, 0, 0 ))
1564                                         /*if (GetMessage( &msg, NULL, 0, 0 ))
1565                                         {
1566                                                 TranslateMessage(&msg);
1567                                                 DispatchMessage(&msg);
1568                                         }*/
1569                                         if ( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
1570                                         { 
1571                                                 if (bRet <= 0)
1572                                                 {
1573                                                         // handle the error and possibly exit
1574                                                         gDone=true;
1575                                                 }
1576                                                 else
1577                                                 {
1578                                                         TranslateMessage(&msg); 
1579                                                         DispatchMessage(&msg); 
1580                                                 }
1581                                         }
1582                     #else
1583                     STUBBED("give up CPU but sniff the event queue");
1584                     #endif
1585                                 }
1586                         }
1587
1588                         regnow = game.registernow;
1589                 }
1590                 pgame = 0;
1591
1592                 CleanUp ();
1593 //              if(game.registernow){
1594                 if(regnow)
1595                 {
1596             #if (defined(__APPLE__) && defined(__MACH__))
1597             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1598             #elif PLATFORM_LINUX
1599             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1600             #else
1601             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1602             #endif
1603                 }
1604
1605         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1606         _exit(0);  // !!! FIXME: hack...crashes on exit!
1607         #endif
1608                 return 0;
1609         }
1610         catch (const std::exception& error)
1611         {
1612                 CleanUp();
1613
1614                 std::string e = "Caught exception: ";
1615                 e += error.what();
1616
1617                 LOG(e, Logger::LOG_ERR);
1618
1619                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1620         }
1621
1622         CleanUp();
1623
1624         return -1;
1625 }
1626
1627
1628
1629         // --------------------------------------------------------------------------
1630
1631 #ifdef WIN32
1632 #define MAX_WINKEYS 256
1633         static unsigned short KeyTable[MAX_WINKEYS]=
1634         {
1635                 0xffff,  // (0)
1636                         MAC_MOUSEBUTTON1,  // VK_LBUTTON        (1)
1637                         MAC_MOUSEBUTTON2,  // VK_RBUTTON        (2)
1638                         0xffff,  // VK_CANCEL   (3)
1639                         0xffff,  // VK_MBUTTON  (4)
1640                         0xffff,  // (5)
1641                         0xffff,  // (6)
1642                         0xffff,  // (7)
1643                         MAC_DELETE_KEY,  // VK_BACK     (8)
1644                         MAC_TAB_KEY,  // VK_TAB (9)
1645                         0xffff,  // (10)
1646                         0xffff,  // (11)
1647                         0xffff,  // VK_CLEAR    (12)
1648                         MAC_RETURN_KEY,  // VK_RETURN   (13)
1649                         0xffff,  // (14)
1650                         0xffff,  // (15)
1651                         MAC_SHIFT_KEY,  // VK_SHIFT     (16)
1652                         MAC_CONTROL_KEY,  // VK_CONTROL (17)
1653                         MAC_OPTION_KEY,  // VK_MENU     (18)
1654                         0xffff,  // VK_PAUSE    (19)
1655                         MAC_CAPS_LOCK_KEY,  // #define VK_CAPITAL       (20)
1656                         0xffff,  // (21)
1657                         0xffff,  // (22)
1658                         0xffff,  // (23)
1659                         0xffff,  // (24)
1660                         0xffff,  // (25)
1661                         0xffff,  // (26)
1662                         MAC_ESCAPE_KEY,  // VK_ESCAPE   (27)
1663                         0xffff,  // (28)
1664                         0xffff,  // (29)
1665                         0xffff,  // (30)
1666                         0xffff,  // (31)
1667                         MAC_SPACE_KEY,  // VK_SPACE     (32)
1668                         MAC_PAGE_UP_KEY,  // VK_PRIOR   (33)
1669                         MAC_PAGE_DOWN_KEY,  // VK_NEXT  (34)
1670                         MAC_END_KEY,  // VK_END (35)
1671                         MAC_HOME_KEY,  // VK_HOME       (36)
1672                         MAC_ARROW_LEFT_KEY,  // VK_LEFT (37)
1673                         MAC_ARROW_UP_KEY,  // VK_UP     (38)
1674                         MAC_ARROW_RIGHT_KEY,  // VK_RIGHT       (39)
1675                         MAC_ARROW_DOWN_KEY,  // VK_DOWN (40)
1676                         0xffff,  // VK_SELECT   (41)
1677                         0xffff,  // VK_PRINT    (42)
1678                         0xffff,  // VK_EXECUTE  (43)
1679                         0xffff,  // VK_SNAPSHOT (44)
1680                         MAC_INSERT_KEY,  // VK_INSERT   (45)
1681                         MAC_DEL_KEY,  // VK_DELETE      (46)
1682                         0xffff,  // VK_HELP     (47)
1683                         MAC_0_KEY,  // VK_0     (48)
1684                         MAC_1_KEY,  // VK_1     (49)
1685                         MAC_2_KEY,  // VK_2     (50)
1686                         MAC_3_KEY,  // VK_3     (51)
1687                         MAC_4_KEY,  // VK_4     (52)
1688                         MAC_5_KEY,  // VK_5     (53)
1689                         MAC_6_KEY,  // VK_6     (54)
1690                         MAC_7_KEY,  // VK_7     (55)
1691                         MAC_8_KEY,  // VK_8     (56)
1692                         MAC_9_KEY,  // VK_9     (57)
1693                         0xffff,  // (58)
1694                         0xffff,  // (59)
1695                         0xffff,  // (60)
1696                         0xffff,  // (61)
1697                         0xffff,  // (62)
1698                         0xffff,  // (63)
1699                         0xffff,  // (64)
1700                         MAC_A_KEY,  // VK_A     (65)
1701                         MAC_B_KEY,  // VK_B     (66)
1702                         MAC_C_KEY,  // VK_C     (67)
1703                         MAC_D_KEY,  // VK_D     (68)
1704                         MAC_E_KEY,  // VK_E     (69)
1705                         MAC_F_KEY,  // VK_F     (70)
1706                         MAC_G_KEY,  // VK_G     (71)
1707                         MAC_H_KEY,  // VK_H     (72)
1708                         MAC_I_KEY,  // VK_I     (73)
1709                         MAC_J_KEY,  // VK_J     (74)
1710                         MAC_K_KEY,  // VK_K     (75)
1711                         MAC_L_KEY,  // VK_L     (76)
1712                         MAC_M_KEY,  // VK_M     (77)
1713                         MAC_N_KEY,  // VK_N     (78)
1714                         MAC_O_KEY,  // VK_O     (79)
1715                         MAC_P_KEY,  // VK_P     (80)
1716                         MAC_Q_KEY,  // VK_Q     (81)
1717                         MAC_R_KEY,  // VK_R     (82)
1718                         MAC_S_KEY,  // VK_S     (83)
1719                         MAC_T_KEY,  // VK_T     (84)
1720                         MAC_U_KEY,  // VK_U     (85)
1721                         MAC_V_KEY,  // VK_V     (86)
1722                         MAC_W_KEY,  // VK_W     (87)
1723                         MAC_X_KEY,  // VK_X     (88)
1724                         MAC_Y_KEY,  // VK_Y     (89)
1725                         MAC_Z_KEY,  // VK_Z     (90)
1726                         0xffff,  // (91)
1727                         0xffff,  // (92)
1728                         0xffff,  // (93)
1729                         0xffff,  // (94)
1730                         0xffff,  // (95)
1731                         MAC_NUMPAD_0_KEY,  // VK_NUMPAD0        (96)
1732                         MAC_NUMPAD_1_KEY,  // VK_NUMPAD1        (97)
1733                         MAC_NUMPAD_2_KEY,  // VK_NUMPAD2        (98)
1734                         MAC_NUMPAD_3_KEY,  // VK_NUMPAD3        (99)
1735                         MAC_NUMPAD_4_KEY,  // VK_NUMPAD4        (100)
1736                         MAC_NUMPAD_5_KEY,  // VK_NUMPAD5        (101)
1737                         MAC_NUMPAD_6_KEY,  // VK_NUMPAD6        (102)
1738                         MAC_NUMPAD_7_KEY,  // VK_NUMPAD7        (103)
1739                         MAC_NUMPAD_8_KEY,  // VK_NUMPAD8        (104)
1740                         MAC_NUMPAD_9_KEY,  // VK_NUMPAD9        (105)
1741                         MAC_NUMPAD_ASTERISK_KEY,  // VK_MULTIPLY        (106)
1742                         MAC_NUMPAD_PLUS_KEY,  // VK_ADD (107)
1743                         MAC_NUMPAD_ENTER_KEY,  // VK_SEPARATOR  (108)
1744                         MAC_NUMPAD_MINUS_KEY,  // VK_SUBTRACT   (109)
1745                         MAC_NUMPAD_PERIOD_KEY,  // VK_DECIMAL   (110)
1746                         MAC_NUMPAD_SLASH_KEY,  // VK_DIVIDE     (111)
1747                         MAC_F1_KEY,  // VK_F1   (112)
1748                         MAC_F2_KEY,  // VK_F2   (113)
1749                         MAC_F3_KEY,  // VK_F3   (114)
1750                         MAC_F4_KEY,  // VK_F4   (115)
1751                         MAC_F5_KEY,  // VK_F5   (116)
1752                         MAC_F6_KEY,  // VK_F6   (117)
1753                         MAC_F7_KEY,  // VK_F7   (118)
1754                         MAC_F8_KEY,  // VK_F8   (119)
1755                         MAC_F9_KEY,  // VK_F9   (120)
1756                         MAC_F10_KEY,  // VK_F10 (121)
1757                         MAC_F11_KEY,  // VK_F11 (122)
1758                         MAC_F12_KEY,  // VK_F12 (123)
1759                         0xffff,  // (124)
1760                         0xffff,  // (125)
1761                         0xffff,  // (126)
1762                         0xffff,  // (127)
1763                         0xffff,  // (128)
1764                         0xffff,  // (129)
1765                         0xffff,  // (130)
1766                         0xffff,  // (131)
1767                         0xffff,  // (132)
1768                         0xffff,  // (133)
1769                         0xffff,  // (134)
1770                         0xffff,  // (135)
1771                         0xffff,  // (136)
1772                         0xffff,  // (137)
1773                         0xffff,  // (138)
1774                         0xffff,  // (139)
1775                         0xffff,  // (130)
1776                         0xffff,  // (141)
1777                         0xffff,  // (142)
1778                         0xffff,  // (143)
1779                         0xffff,  // VK_NUMLOCK  (144)
1780                         0xffff,  // VK_SCROLL   (145)
1781                         0xffff,  // (146)
1782                         0xffff,  // (147)
1783                         0xffff,  // (148)
1784                         0xffff,  // (149)
1785                         0xffff,  // (150)
1786                         0xffff,  // (151)
1787                         0xffff,  // (152)
1788                         0xffff,  // (153)
1789                         0xffff,  // (154)
1790                         0xffff,  // (155)
1791                         0xffff,  // (156)
1792                         0xffff,  // (157)
1793                         0xffff,  // (158)
1794                         0xffff,  // (159)
1795                         MAC_SHIFT_KEY,  // VK_LSHIFT    (160)
1796                         MAC_SHIFT_KEY,  // VK_RSHIFT    (161)
1797                         MAC_CONTROL_KEY,  // VK_LCONTROL        (162)
1798                         MAC_CONTROL_KEY,  // VK_RCONTROL        (163)
1799                         MAC_OPTION_KEY,  // VK_LMENU    (164)
1800                         MAC_OPTION_KEY,  // VK_RMENU    (165)
1801                         0xffff,  // (166)
1802                         0xffff,  // (167)
1803                         0xffff,  // (168)
1804                         0xffff,  // (169)
1805                         0xffff,  // (170)
1806                         0xffff,  // (171)
1807                         0xffff,  // (172)
1808                         0xffff,  // (173)
1809                         0xffff,  // (174)
1810                         0xffff,  // (175)
1811                         0xffff,  // (176)
1812                         0xffff,  // (177)
1813                         0xffff,  // (178)
1814                         0xffff,  // (179)
1815                         0xffff,  // (180)
1816                         0xffff,  // (181)
1817                         0xffff,  // (182)
1818                         0xffff,  // (183)
1819                         0xffff,  // (184)
1820                         0xffff,  // (185)
1821                         MAC_SEMICOLON_KEY,  // (186)
1822                         MAC_PLUS_KEY,  // (187)
1823                         MAC_COMMA_KEY,  // (188)
1824                         MAC_MINUS_KEY,  // (189)
1825                         MAC_PERIOD_KEY,  // (190)
1826                         MAC_SLASH_KEY,  // (191)
1827                         MAC_TILDE_KEY,  // (192)
1828                         0xffff,  // (193)
1829                         0xffff,  // (194)
1830                         0xffff,  // (195)
1831                         0xffff,  // (196)
1832                         0xffff,  // (197)
1833                         0xffff,  // (198)
1834                         0xffff,  // (199)
1835                         0xffff,  // (200)
1836                         0xffff,  // (201)
1837                         0xffff,  // (202)
1838                         0xffff,  // (203)
1839                         0xffff,  // (204)
1840                         0xffff,  // (205)
1841                         0xffff,  // (206)
1842                         0xffff,  // (207)
1843                         0xffff,  // (208)
1844                         0xffff,  // (209)
1845                         0xffff,  // (210)
1846                         0xffff,  // (211)
1847                         0xffff,  // (212)
1848                         0xffff,  // (213)
1849                         0xffff,  // (214)
1850                         0xffff,  // (215)
1851                         0xffff,  // (216)
1852                         0xffff,  // (217)
1853                         0xffff,  // (218)
1854                         MAC_LEFTBRACKET_KEY,  // (219)
1855                         MAC_BACKSLASH_KEY,  // (220)
1856                         MAC_RIGHTBRACKET_KEY,  // (221)
1857                         MAC_APOSTROPHE_KEY,  // (222)
1858                         0xffff,  // (223)
1859                         0xffff,  // (224)
1860                         0xffff,  // (225)
1861                         0xffff,  // (226)
1862                         0xffff,  // (227)
1863                         0xffff,  // (228)
1864                         0xffff,  // (229)
1865                         0xffff,  // (230)
1866                         0xffff,  // (231)
1867                         0xffff,  // (232)
1868                         0xffff,  // (233)
1869                         0xffff,  // (234)
1870                         0xffff,  // (235)
1871                         0xffff,  // (236)
1872                         0xffff,  // (237)
1873                         0xffff,  // (238)
1874                         0xffff,  // (239)
1875                         0xffff,  // (240)
1876                         0xffff,  // (241)
1877                         0xffff,  // (242)
1878                         0xffff,  // (243)
1879                         0xffff,  // (244)
1880                         0xffff,  // (245)
1881                         0xffff,  // (246)
1882                         0xffff,  // (247)
1883                         0xffff,  // (248)
1884                         0xffff,  // (249)
1885                         0xffff,  // (250)
1886                         0xffff,  // (251)
1887                         0xffff,  // (252)
1888                         0xffff,  // (253)
1889                         0xffff,  // (254)
1890                         0xffff,  // (255)
1891         };
1892
1893         void ClipMouseToWindow(HWND window)
1894         {
1895                 RECT wRect;
1896
1897                 GetClientRect(window, &wRect);
1898
1899                 ClientToScreen(window, (LPPOINT)&wRect.left);
1900                 ClientToScreen(window, (LPPOINT)&wRect.right);
1901
1902                 ClipCursor(&wRect);
1903
1904                 return;
1905         }
1906
1907         LRESULT FAR PASCAL AppWndProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
1908         {
1909                 /* this is where we receive all messages concerning this window
1910                 * we can either process a message or pass it on to the default
1911                 * message handler of windows */
1912
1913                 static PAINTSTRUCT ps;
1914
1915                 switch(msg)
1916                 {
1917                 case WM_ACTIVATE:       // Watch For Window Activate Message
1918                         {
1919                                 // Check Minimization State
1920                                 BOOL iconified = HIWORD(wParam) ? TRUE : FALSE;
1921
1922                                 if (LOWORD(wParam) == WA_INACTIVE)
1923                                 {
1924                                         ClipCursor(NULL);
1925
1926                                         if (fullscreen)
1927                                         {
1928                                                 if( !iconified )
1929                                                 {
1930                                                         // Minimize window
1931                                                         CloseWindow( hWnd );
1932
1933                                                         // The window is now iconified
1934                                                         iconified = GL_TRUE;
1935                                                 }
1936                                         }
1937
1938                                         ShutdownDSp();
1939
1940                                         g_focused=false;                                // Program Is Active
1941                                 }
1942                                 else
1943                                 {
1944                                         SetupDSpFullScreen();
1945
1946                                         if( iconified )
1947                                         {
1948                                                 // Minimize window
1949                                                 OpenIcon( hWnd );
1950
1951                                                 // The window is now iconified
1952                                                 iconified = GL_FALSE;
1953
1954                                                 // Activate window
1955                                                 ShowWindow( hWnd, SW_SHOW );
1956                                                 SetForegroundWindow( hWnd );
1957                                                 SetFocus( hWnd );
1958                                         }
1959
1960                                         ClipMouseToWindow(hWnd);
1961                                         g_focused=true;                 // Program Is No Longer Active
1962                                 }
1963
1964                                 return 0;                                               // Return To The Message Loop
1965                         }
1966
1967                 case WM_KEYDOWN:
1968                 case WM_SYSKEYDOWN:
1969                         {
1970                                 // check for Alt-F4 (exit hotkey)
1971                                 if (wParam == VK_F4)
1972                                 {
1973                                         if (GetKeyState( VK_MENU) & 0x8080)
1974                                         {
1975                                                 gDone = true;
1976                                                 break;
1977                                         }
1978                                 }
1979                                 if (wParam < MAX_WINKEYS)
1980                                 {
1981                                         if (KeyTable[wParam] != 0xffff)
1982                                                 SetKey( KeyTable[wParam]);
1983                                 }
1984                                 return (0);
1985                         }
1986
1987                 case WM_KEYUP:
1988                 case WM_SYSKEYUP:
1989                         {
1990                                 if (wParam < MAX_WINKEYS)
1991                                         if (KeyTable[wParam] != 0xffff)
1992                                                 ClearKey( KeyTable[wParam]);
1993                                 return (0);
1994                         }
1995
1996                 case WM_CHAR:
1997                 case WM_DEADCHAR:
1998                 case WM_SYSCHAR:
1999                 case WM_SYSDEADCHAR:
2000                         return (0);
2001
2002                 case WM_NCLBUTTONDOWN:
2003                 case WM_LBUTTONDOWN:
2004                         {
2005                                 g_button = true;
2006                                 buttons[ 0] = true;
2007                         }
2008                         return (0);
2009
2010                 case WM_NCRBUTTONDOWN:
2011                 case WM_RBUTTONDOWN:
2012                         {
2013                                 buttons[ 1] = true;
2014                         }
2015                         return (0);
2016
2017                 case WM_NCMBUTTONDOWN:
2018                 case WM_MBUTTONDOWN:
2019                         {
2020                                 buttons[ 2] = true;
2021                         }
2022                         return (0);
2023
2024                 case WM_NCLBUTTONUP:
2025                 case WM_LBUTTONUP:
2026                         {
2027                                 g_button = false;
2028                                 buttons[ 0] = false;
2029                         }
2030                         return (0);
2031
2032                 case WM_NCRBUTTONUP:
2033                 case WM_RBUTTONUP:
2034                         {
2035                                 buttons[ 1] = false;
2036                         }
2037                         return (0);
2038
2039                 case WM_NCMBUTTONUP:
2040                 case WM_MBUTTONUP:
2041                         {
2042                                 buttons[ 2] = false;
2043                         }
2044                         return (0);
2045
2046                 case WM_NCLBUTTONDBLCLK:
2047                 case WM_NCRBUTTONDBLCLK:
2048                 case WM_NCMBUTTONDBLCLK:
2049                 case WM_LBUTTONDBLCLK:
2050                         return (0);
2051                 case WM_RBUTTONDBLCLK:
2052                 case WM_MBUTTONDBLCLK:
2053                         return (0);
2054
2055                 case WM_NCMOUSEMOVE:
2056                 case WM_MOUSEMOVE:
2057                         /*                      ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseX = (signed short)(lParam & 0xffff);
2058                         ((WindowInfo *)g_lastWindow->GetInfo())->m_mouseY = (signed short)(lParam >> 16);
2059                         if (g_lastWindow->m_mouseCallbacksEnabled) g_lastWindow->MouseMoveCallback();
2060                         *///                    goto winmessage;
2061                         return (0);
2062
2063                 case WM_SYSCOMMAND:                                             // Intercept System Commands
2064                         {
2065                                 switch (wParam)                                         // Check System Calls
2066                                 {
2067                                 case SC_SCREENSAVE:                             // Screensaver Trying To Start?
2068                                 case SC_MONITORPOWER:                   // Monitor Trying To Enter Powersave?
2069                                         return 0;                                       // Prevent From Happening
2070
2071                                         // User trying to access application menu using ALT?
2072                                 case SC_KEYMENU:
2073                                         return 0;
2074                                 }
2075                         }
2076                         break;
2077
2078                 case WM_MOVE:
2079 //                      {
2080 //                              ReleaseCapture();
2081 //                              ClipMouseToWindow(hWnd);
2082 //                      }
2083                         break;
2084
2085                 case WM_SIZE:
2086                         break;
2087
2088                 case WM_CLOSE:
2089                         {
2090                                 //gDone =  true;
2091                                 //game.tryquit=1;
2092                         }
2093                         //return (0);
2094
2095                 case WM_DESTROY:
2096                         {
2097                                 //ClipCursor(NULL);
2098                                 PostQuitMessage(0);  /* Terminate Application */
2099                         }
2100                         return (0);
2101
2102                 case WM_ERASEBKGND:
2103                         break;
2104
2105                 case WM_PAINT:
2106 //                      BeginPaint( g_windowHandle,&ps);
2107 //                      EndPaint( g_windowHandle,&ps);
2108                         break;
2109
2110                 default:
2111                         break;
2112                 }
2113
2114                 /* We processed the message and there
2115                 * is no processing by Windows necessary */
2116
2117                 /* We didn't process the message so let Windows do it */
2118                 return DefWindowProc(hWnd,msg,wParam,lParam);
2119         }
2120
2121
2122         static BOOL RegisterWindowClasses(HINSTANCE hFirstInstance)
2123         {
2124                 WNDCLASSEX wc;
2125                 memset( &wc, 0, sizeof( wc));
2126
2127                 /* Register the window class. */
2128                 wc.cbSize = sizeof(wc);
2129 #undef style
2130                 wc.style = (CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC);  /* Combination of Class Styles */
2131                 wc.lpfnWndProc = AppWndProc;       /* Adress of Window Procedure */
2132                 wc.cbClsExtra = 0;                 /* Extra Bytes allocated for this Class */
2133                 wc.cbWndExtra = 0;                 /* Extra Bytes allocated for each Window */
2134                 wc.hInstance = hFirstInstance;     /* Handle of program instance */
2135                 wc.hIcon = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2136                 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
2137                 wc.hbrBackground = NULL;
2138                 wc.lpszMenuName  = NULL;
2139                 wc.lpszClassName = g_wndClassName; /* Name of the Window Class */
2140                 wc.hIconSm = LoadIcon( hFirstInstance, MAKEINTRESOURCE(IDI_LUGARU) );
2141
2142                 if (!RegisterClassEx(&wc)) return FALSE;  /* Register Class failed */
2143
2144                 return TRUE;
2145         }
2146 #endif
2147
2148         int resolutionID(int width, int height)
2149         {
2150                 int whichres;
2151                 whichres=-1;
2152                 if(width==640 && height==480)whichres=0;
2153                 if(width==800 && height==600)whichres=1;
2154                 if(width==1024 && height==768)whichres=2;
2155                 if(width==1280 && height==1024)whichres=3;
2156                 if(width==1600 && height==1200)whichres=4;
2157                 if(width==840 && height==524)whichres=5;
2158                 if(width==1024 && height==640)whichres=6;
2159                 if(width==1344 && height==840)whichres=7;
2160                 if(width==1920 && height==1200)whichres=8;
2161
2162                 return whichres;
2163         }
2164
2165         int closestResolution(int width, int height)
2166         {
2167                 int whichres;
2168                 whichres=-1;
2169                 if(width>=640 && height>=480)whichres=0;
2170                 if(width>=800 && height>=600)whichres=1;
2171                 if(width>=1024 && height>=768)whichres=2;
2172                 if(width>=1280 && height>=1024)whichres=3;
2173                 if(width>=1600 && height>=1200)whichres=4;
2174                 if(width==840 && height==524)whichres=5;
2175                 if(width==1024 && height==640)whichres=6;
2176                 if(width==1344 && height==840)whichres=7;
2177                 if(width>=1920 && height>=1200)whichres=8;
2178
2179                 return whichres;
2180         }
2181
2182         bool selectDetail(int & width, int & height, int & bpp, int & detail)
2183         {
2184                 bool res = true;
2185                 int whichres = closestResolution(width, height);
2186
2187                 while (true)
2188                 {
2189                         if(whichres<=0 || whichres>8){
2190                                 whichres = 0;
2191                                 width=640;
2192                                 height=480;
2193                         }
2194                         if(whichres==1){
2195                                 width=800;
2196                                 height=600;
2197                         }
2198                         if(whichres==2){
2199                                 width=1024;
2200                                 height=768;
2201                         }
2202                         if(whichres==3){
2203                                 width=1280;
2204                                 height=1024;
2205                         }
2206                         if(whichres==4){
2207                                 width=1600;
2208                                 height=1200;
2209                         }
2210                         if(whichres==5){
2211                                 width=840;
2212                                 height=524;
2213                         }
2214                         if(whichres==6){
2215                                 width=1024;
2216                                 height=640;
2217                         }
2218                         if(whichres==7){
2219                                 width=1344;
2220                                 height=840;
2221                         }
2222                         if(whichres==8){
2223                                 width=1920;
2224                                 height=1200;
2225                         }
2226
2227             // currently with SDL, we just use whatever the native bitdepth
2228             //  of the display is and don't care.
2229             #if USE_SDL
2230             break;
2231             #endif
2232
2233                         if ((detail != 0) && (resolutionDepths[whichres][1] != 0))
2234                         {
2235                                 break;
2236                         }
2237                         else if ((detail == 0) && (resolutionDepths[whichres][0] != 0))
2238                         {
2239                                 break;
2240                         }
2241                         else if ((detail != 0) && (resolutionDepths[whichres][0] != 0))
2242                         {
2243                                 res = false;
2244                                 detail = 0;
2245                                 break;
2246                         }
2247                         else
2248
2249             if (0 == whichres)
2250                         {
2251                                 break;
2252                         }
2253
2254                         --whichres;
2255                 }
2256
2257                 bpp = resolutionDepths[whichres][(detail != 0)];
2258
2259                 return res;
2260         }
2261
2262     #ifdef WIN32
2263         int __stdcall WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
2264         {
2265                 int argc = 0;
2266                 LPWSTR * cl = CommandLineToArgvW(GetCommandLineW(), &argc);
2267                 if (argc > 1)
2268                 {
2269                         if (0 == _wcsicmp(cl[1], L"-windowed"))
2270                         {
2271                                 fullscreen = false;
2272                         }
2273                 }
2274
2275                 logger.start(true);
2276
2277                 memset( &g_theKeys, 0, sizeof( KeyMap));
2278
2279                 unsigned int i = 0;
2280                 DEVMODE mode;
2281                 memset(&mode, 0, sizeof(mode));
2282                 mode.dmSize = sizeof(mode);
2283                 while (EnumDisplaySettings(NULL, i++, &mode))
2284                 {
2285                         if (mode.dmBitsPerPel < 16)
2286                         {
2287                                 continue;
2288                         }
2289
2290                         int res = resolutionID(mode.dmPelsWidth, mode.dmPelsHeight);
2291
2292                         if (res > -1 && res < 8)
2293                         {
2294                                 if (DISP_CHANGE_SUCCESSFUL != ChangeDisplaySettings(&mode, CDS_TEST))
2295                                 {
2296                                         continue;
2297                                 }
2298
2299                                 switch(mode.dmBitsPerPel)
2300                                 {
2301                                 case 32:
2302                                 case 24:
2303                                         resolutionDepths[res][1] = mode.dmBitsPerPel;
2304                                         break;
2305                                 case 16:
2306                                         resolutionDepths[res][0] = mode.dmBitsPerPel;
2307                                         break;
2308                                 }
2309                         }
2310                 }
2311
2312                 /* if there is no Instance of our program in memory then register the window class */
2313                 if (hPrevInstance == NULL && !RegisterWindowClasses(hInstance))
2314                         return FALSE;  /* registration failed! */
2315
2316                 g_appInstance=hInstance;
2317
2318                 main(0, NULL);
2319
2320                 UnregisterClass( g_wndClassName, hInstance);
2321
2322                 return TRUE;
2323
2324         }
2325     #endif
2326
2327         extern int channels[100];
2328         extern FSOUND_SAMPLE * samp[100];
2329         extern FSOUND_STREAM * strm[20];
2330
2331         extern "C" void PlaySoundEx(int chan, FSOUND_SAMPLE *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2332         {
2333                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2334                 if (currSample && currSample == samp[chan])
2335                 {
2336                         if (FSOUND_GetPaused(channels[chan]))
2337                         {
2338                                 FSOUND_StopSound(channels[chan]);
2339                                 channels[chan] = FSOUND_FREE;
2340                         }
2341                         else if (FSOUND_IsPlaying(channels[chan]))
2342                         {
2343                                 int loop_mode = FSOUND_GetLoopMode(channels[chan]);
2344                                 if (loop_mode & FSOUND_LOOP_OFF)
2345                                 {
2346                                         channels[chan] = FSOUND_FREE;
2347                                 }
2348                         }
2349                 }
2350                 else
2351                 {
2352                         channels[chan] = FSOUND_FREE;
2353                 }
2354
2355                 channels[chan] = FSOUND_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
2356                 if (channels[chan] < 0)
2357                 {
2358                         channels[chan] = FSOUND_PlaySoundEx(FSOUND_FREE, sptr, dsp, startpaused);
2359                 }
2360         }
2361
2362         extern "C" void PlayStreamEx(int chan, FSOUND_STREAM *sptr, FSOUND_DSPUNIT *dsp, signed char startpaused)
2363         {
2364                 const FSOUND_SAMPLE * currSample = FSOUND_GetCurrentSample(channels[chan]);
2365                 if (currSample && currSample == FSOUND_Stream_GetSample(sptr))
2366                 {
2367                                 FSOUND_StopSound(channels[chan]);
2368                                 FSOUND_Stream_Stop(sptr);
2369                 }
2370                 else
2371                 {
2372                         FSOUND_Stream_Stop(sptr);
2373                         channels[chan] = FSOUND_FREE;
2374                 }
2375
2376                 channels[chan] = FSOUND_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
2377                 if (channels[chan] < 0)
2378                 {
2379                         channels[chan] = FSOUND_Stream_PlayEx(FSOUND_FREE, sptr, dsp, startpaused);
2380                 }
2381         }
2382
2383         bool LoadImage(const char * fname, TGAImageRec & tex)
2384         {
2385                 bool res = true;
2386
2387                 if ( tex.data == NULL )
2388                 {
2389                         return false;
2390                 }
2391
2392         #if USE_DEVIL
2393                 ILstring f = strdup(ConvertFileName(fname));
2394                 if (!f)
2395                 {
2396                         return false;
2397                 }
2398
2399                 ILuint iid=0;
2400                 ilGenImages(1, &iid);
2401                 ilBindImage(iid);
2402                 if (ilLoadImage(f))
2403                 {
2404                         //iluFlipImage();
2405                         tex.sizeX = ilGetInteger(IL_IMAGE_WIDTH);
2406                         tex.sizeY = ilGetInteger(IL_IMAGE_HEIGHT);
2407                         tex.bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
2408                         ILuint Bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL),
2409                                 imageSize = tex.sizeX * tex.sizeY * Bpp;
2410                         ILubyte *Data = ilGetData();
2411                         memcpy(tex.data, Data, imageSize);
2412
2413                         // Truvision Targa files are stored as BGR colors
2414                         // We want RGB so Blue and Red bytes are switched
2415                         if (IL_TGA == ilGetInteger(IL_IMAGE_FORMAT))
2416                         {
2417                                 // Loop Through The Image Data
2418                                 for (GLuint i = 0; i < int(imageSize); i += Bpp)
2419                                 {
2420                                         // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
2421                                         GLbyte temp;                                            // Temporary Variable
2422                                         temp = tex.data[i];                                     // Temporarily Store The Value At Image Data 'i'
2423                                         tex.data[i] = tex.data[i + 2];          // Set The 1st Byte To The Value Of The 3rd Byte
2424                                         tex.data[i + 2] = temp;                         // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
2425                                 }
2426                         }
2427                 }
2428                 else
2429                 {
2430                         res = false;
2431                 }
2432                 ilDeleteImages(1, &iid);
2433 /*
2434                 if (tid)
2435                 {
2436                         GLuint texid = ilutGLLoadImage(f);
2437                         *tid = texid;
2438                 }
2439                 else if (mip)
2440                 {
2441                         ilutGLBuildMipmaps()
2442                 }
2443                 else
2444                 {
2445                         ilutGLTexImage(0);
2446                 }
2447 */
2448                 free(f);
2449         #else
2450         res = load_image(fname, tex);
2451         //if (!res) printf("failed to load %s\n", fname);
2452         #endif
2453
2454                 return res;
2455         }
2456
2457         void ScreenShot(const char * fname)
2458         {
2459         #if USE_DEVIL
2460                 ILstring f = strdup(fname);
2461                 if (!f)
2462                 {
2463                         return;
2464                 }
2465
2466                 ILuint iid;
2467                 ilGenImages(1, &iid);
2468                 ilBindImage(iid);
2469                 if (ilutGLScreen())
2470                 {
2471                         ilSaveImage(f);
2472                 }
2473                 ilDeleteImages(1, &iid);
2474
2475                 free(f);
2476         #else
2477         save_image(fname);
2478         #endif
2479         }
2480
2481
2482 #if !USE_DEVIL
2483 static bool load_image(const char *file_name, TGAImageRec &tex)
2484 {
2485     char *ptr = strrchr(file_name, '.');
2486     if (ptr)
2487     {
2488         if (stricmp(ptr+1, "png") == 0)
2489             return load_png(file_name, tex);
2490         else if (stricmp(ptr+1, "jpg") == 0)
2491             return load_jpg(file_name, tex);
2492     }
2493
2494     STUBBED("Unsupported image type");
2495     return false;
2496 }
2497
2498
2499 struct my_error_mgr {
2500   struct jpeg_error_mgr pub;    /* "public" fields */
2501   jmp_buf setjmp_buffer;        /* for return to caller */
2502 };
2503 typedef struct my_error_mgr * my_error_ptr;
2504
2505
2506 static void my_error_exit(j_common_ptr cinfo)
2507 {
2508         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
2509         longjmp(err->setjmp_buffer, 1);
2510 }
2511
2512 /* stolen from public domain example.c code in libjpg distribution. */
2513 static bool load_jpg(const char *file_name, TGAImageRec &tex)
2514 {
2515     struct jpeg_decompress_struct cinfo;
2516     struct my_error_mgr jerr;
2517     JSAMPROW buffer[1];         /* Output row buffer */
2518     int row_stride;             /* physical row width in output buffer */
2519     FILE *infile = fopen(file_name, "rb");
2520
2521     if (infile == NULL)
2522         return false;
2523
2524     cinfo.err = jpeg_std_error(&jerr.pub);
2525     jerr.pub.error_exit = my_error_exit;
2526     if (setjmp(jerr.setjmp_buffer)) {
2527         jpeg_destroy_decompress(&cinfo);
2528         fclose(infile);
2529         return false;
2530     }
2531
2532     jpeg_create_decompress(&cinfo);
2533     jpeg_stdio_src(&cinfo, infile);
2534     (void) jpeg_read_header(&cinfo, TRUE);
2535
2536     cinfo.out_color_space = JCS_RGB;
2537     cinfo.quantize_colors = 0;
2538     (void) jpeg_calc_output_dimensions(&cinfo);
2539     (void) jpeg_start_decompress(&cinfo);
2540
2541     row_stride = cinfo.output_width * cinfo.output_components;
2542     tex.sizeX = cinfo.output_width;
2543     tex.sizeY = cinfo.output_height;
2544     tex.bpp = 24;
2545
2546     while (cinfo.output_scanline < cinfo.output_height) {
2547         buffer[0] = (JSAMPROW)(char *)tex.data +
2548                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
2549         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
2550     }
2551
2552     (void) jpeg_finish_decompress(&cinfo);
2553     jpeg_destroy_decompress(&cinfo);
2554     fclose(infile);
2555
2556     return true;
2557 }
2558
2559
2560 /* stolen from public domain example.c code in libpng distribution. */
2561 static bool load_png(const char *file_name, TGAImageRec &tex)
2562 {
2563     bool hasalpha = false;
2564     png_structp png_ptr = NULL;
2565     png_infop info_ptr = NULL;
2566     png_uint_32 width, height;
2567     int bit_depth, color_type, interlace_type;
2568     png_byte **rows = NULL;
2569     bool retval = false;
2570     png_byte **row_pointers = NULL;
2571     FILE *fp = fopen(file_name, "rb");
2572
2573     if (fp == NULL)
2574         return(NULL);
2575
2576     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2577     if (png_ptr == NULL)
2578         goto png_done;
2579
2580     info_ptr = png_create_info_struct(png_ptr);
2581     if (info_ptr == NULL)
2582         goto png_done;
2583
2584     if (setjmp(png_jmpbuf(png_ptr)))
2585         goto png_done;
2586
2587     png_init_io(png_ptr, fp);
2588     png_read_png(png_ptr, info_ptr,
2589                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
2590                  png_voidp_NULL);
2591     png_get_IHDR(png_ptr, info_ptr, &width, &height,
2592                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
2593
2594     if (bit_depth != 8)  // transform SHOULD handle this...
2595         goto png_done;
2596
2597     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
2598         goto png_done;
2599
2600     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
2601         goto png_done;
2602
2603     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
2604     row_pointers = png_get_rows(png_ptr, info_ptr);
2605     if (!row_pointers)
2606         goto png_done;
2607
2608     if (!hasalpha)
2609     {
2610         png_byte *dst = tex.data;
2611         for (int i = height-1; i >= 0; i--)
2612         {
2613             png_byte *src = row_pointers[i];
2614             for (int j = 0; j < width; j++)
2615             {
2616                 dst[0] = src[0];
2617                 dst[1] = src[1];
2618                 dst[2] = src[2];
2619                 dst[3] = 0xFF;
2620                 src += 3;
2621                 dst += 4;
2622             }
2623         }
2624     }
2625
2626     else
2627     {
2628         png_byte *dst = tex.data;
2629         int pitch = width * 4;
2630         for (int i = height-1; i >= 0; i--, dst += pitch)
2631             memcpy(dst, row_pointers[i], pitch);
2632     }
2633
2634     tex.sizeX = width;
2635     tex.sizeY = height;
2636     tex.bpp = 32;
2637     retval = true;
2638
2639 png_done:
2640     png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
2641     if (fp)
2642         fclose(fp);
2643     return (retval);
2644 }
2645
2646
2647 static bool save_image(const char *file_name)
2648 {
2649     char *ptr = strrchr(file_name, '.');
2650     if (ptr)
2651     {
2652         if (stricmp(ptr+1, "png") == 0)
2653             return save_png(file_name);
2654     }
2655
2656     STUBBED("Unsupported image type");
2657     return false;
2658 }
2659
2660
2661 static bool save_png(const char *file_name)
2662 {
2663     FILE *fp = NULL;
2664     png_structp png_ptr = NULL;
2665     png_infop info_ptr = NULL;
2666     bool retval = false;
2667
2668     fp = fopen(file_name, "wb");
2669     if (fp == NULL)
2670         return false;
2671
2672     png_bytep *row_pointers = new png_bytep[kContextHeight];
2673     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
2674     if ((!screenshot) || (!row_pointers))
2675         goto save_png_done;
2676
2677     glGetError();
2678     glReadPixels(0, 0, kContextWidth, kContextHeight,
2679                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
2680     if (glGetError() != GL_NO_ERROR)
2681         goto save_png_done;
2682
2683     for (int i = 0; i < kContextHeight; i++)
2684         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
2685
2686     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
2687     if (png_ptr == NULL)
2688         goto save_png_done;
2689
2690     info_ptr = png_create_info_struct(png_ptr);
2691     if (info_ptr == NULL)
2692         goto save_png_done;
2693
2694     if (setjmp(png_jmpbuf(png_ptr)))
2695         goto save_png_done;
2696
2697     png_init_io(png_ptr, fp);
2698
2699     if (setjmp(png_jmpbuf(png_ptr)))
2700         goto save_png_done;
2701
2702     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
2703                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
2704                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
2705
2706     png_write_info(png_ptr, info_ptr);
2707
2708     if (setjmp(png_jmpbuf(png_ptr)))
2709         goto save_png_done;
2710
2711         png_write_image(png_ptr, row_pointers);
2712
2713         if (setjmp(png_jmpbuf(png_ptr)))
2714         goto save_png_done;
2715
2716     png_write_end(png_ptr, NULL);
2717     retval = true;
2718
2719 save_png_done:
2720     png_destroy_write_struct(&png_ptr, &info_ptr);
2721     delete[] screenshot;
2722     delete[] row_pointers;
2723     if (fp)
2724         fclose(fp);
2725     if (!retval)
2726         unlink(ConvertFileName(file_name));
2727     return retval;
2728 }
2729
2730 #endif
2731