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