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