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