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