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