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