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