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