]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
96e6a8811a29b7cc5c9bb16612595f62213a969e
[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 #ifdef WIN32
23 #define UINT8 WIN32API_UINT8
24 #define UINT16 WIN32API_UINT16
25 #define boolean WIN32API_boolean
26 #include <windows.h>
27 #undef UINT8
28 #undef UINT16
29 #undef boolean
30 #endif
31
32
33
34 #include "Game.h"
35 extern "C" {
36         #include "zlib.h"
37         #include "png.h"
38         #include "jpeglib.h"
39 }
40
41 static bool load_image(const char * fname, TGAImageRec & tex);
42 static bool load_png(const char * fname, TGAImageRec & tex);
43 static bool load_jpg(const char * fname, TGAImageRec & tex);
44 static bool save_image(const char * fname);
45 static bool save_png(const char * fname);
46
47
48 #include "openal_wrapper.h"
49
50 // ADDED GWC
51 #ifdef _MSC_VER
52 #pragma comment(lib, "opengl32.lib")
53 #pragma comment(lib, "glu32.lib")
54 #pragma comment(lib, "glaux.lib")
55 #endif
56
57 extern bool buttons[3];
58 extern float multiplier;
59 extern float screenwidth,screenheight;
60 extern float sps;
61 extern float realmultiplier;
62 extern int slomo;
63 extern bool ismotionblur;
64 extern float usermousesensitivity;
65 extern int detail;
66 extern bool floatjump;
67 extern bool cellophane;
68 // MODIFIED GWC
69 //extern int terraindetail;
70 //extern int texdetail;
71 extern float terraindetail;
72 extern float texdetail;
73 extern int bloodtoggle;
74 extern bool osx;
75 extern bool autoslomo;
76 extern bool foliage;
77 extern bool musictoggle;
78 extern bool trilinear;
79 extern float gamespeed;
80 extern int difficulty;
81 extern bool damageeffects;
82 extern int numplayers;
83 extern bool decals;
84 extern bool invertmouse;
85 extern bool texttoggle;
86 extern bool ambientsound;
87 extern bool mousejump;
88 extern bool freeze;
89 extern Person player[maxplayers];
90 extern bool vblsync;
91 extern bool stillloading;
92 extern bool showpoints;
93 extern bool alwaysblur;
94 extern bool immediate;
95 extern bool velocityblur;
96 extern bool debugmode;
97 extern int mainmenu;
98 /*extern*/ bool gameFocused;
99 extern int kBitsPerPixel;
100 extern float slomospeed;
101 extern float slomofreq;
102 extern float oldgamespeed;
103 extern float volume;
104
105 #include <math.h>
106 #include <stdio.h>
107 #include <string.h>
108 #include <fstream>
109 #include <iostream>
110 #include "gamegl.h"
111 #include "MacCompatibility.h"
112
113 #ifdef WIN32
114 #include <shellapi.h>
115 #endif
116
117 #include "res/resource.h"
118
119 using namespace std;
120
121
122
123 SDL_Rect **resolutions = NULL;
124 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
125 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
126 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
127 static SDL_Rect *hardcoded_resolutions[] = {
128     &rect_1024_768,
129     &rect_800_600,
130     &rect_640_480,
131     NULL
132 };
133
134
135
136 unsigned int resolutionDepths[8][2] = {0};
137
138 bool selectDetail(int & width, int & height, int & bpp, int & detail);
139 int closestResolution(int width, int height);
140 int resolutionID(int width, int height);
141
142 void ReportError (char * strError);
143
144 void SetupDSpFullScreen();
145 void ShutdownDSp();
146
147 void DrawGL(Game & game);
148
149 void CreateGLWindow (void);
150 Boolean SetUp (Game & game);
151 void DoKey (SInt8 theKey, SInt8 theCode);
152 void DoUpdate (Game & game);
153
154 void DoEvent (void);
155 void CleanUp (void);
156
157
158 // statics/globals (internal only) ------------------------------------------
159 #ifndef WIN32
160 typedef struct tagPOINT { 
161   int x;
162   int y;
163 } POINT, *PPOINT; 
164 #endif
165
166
167
168 #ifdef _MSC_VER
169 #pragma warning(push)
170 #pragma warning(disable: 4273)
171 #endif
172
173 #define GL_FUNC(ret,fn,params,call,rt) \
174     extern "C" { \
175         static ret (GLAPIENTRY *p##fn) params = NULL; \
176         ret GLAPIENTRY fn params { rt p##fn call; } \
177     }
178 #include "glstubs.h"
179 #undef GL_FUNC
180
181 #ifdef _MSC_VER
182 #pragma warning(pop)
183 #endif
184
185 static bool lookup_glsym(const char *funcname, void **func)
186 {
187     *func = SDL_GL_GetProcAddress(funcname);
188     if (*func == NULL)
189     {
190         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
191         return false;
192     }
193     return true;
194 }
195
196 static bool lookup_all_glsyms(void)
197 {
198     bool retval = true;
199     #define GL_FUNC(ret,fn,params,call,rt) \
200         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
201     #include "glstubs.h"
202     #undef GL_FUNC
203     return retval;
204 }
205
206 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
207 {
208     // no-op.
209 }
210
211
212
213 void sdlGetCursorPos(POINT *pt)
214 {
215     int x, y;
216     SDL_GetMouseState(&x, &y);
217     pt->x = x;
218     pt->y = y;
219 }
220 #define GetCursorPos(x) sdlGetCursorPos(x)
221 #define SetCursorPos(x, y) SDL_WarpMouse(x, y)
222 #define ScreenToClient(x, pt)
223 #define ClientToScreen(x, pt)
224 #ifdef MessageBox
225 #undef MessageBox
226 #endif
227 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
228
229
230 Point delta;
231
232 static bool g_button, fullscreen = true;
233
234
235 // Menu defs
236 enum 
237 {
238         kFileQuit = 1
239 };
240
241 enum 
242 {
243         kForegroundSleep = 10,
244         kBackgroundSleep = 10000
245 };
246
247
248 int kContextWidth;
249 int kContextHeight;
250
251 const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
252
253 GLuint gFontList;
254 char gcstrMode [256] = "";
255
256 UInt32 gSleepTime = kForegroundSleep;
257 Boolean gDone = false, gfFrontProcess = true;
258
259 Game * pgame = 0;
260
261 #ifndef __MINGW32__
262 static int _argc = 0;
263 static char **_argv = NULL;
264 #endif
265
266 bool cmdline(const char *cmd)
267 {
268     for (int i = 1; i < _argc; i++)
269     {
270         char *arg = _argv[i];
271         while (*arg == '-')
272             arg++;
273         if (strcasecmp(arg, cmd) == 0)
274             return true;
275     }
276
277     return false;
278 }
279
280
281 // --------------------------------------------------------------------------
282
283 void ReportError (char * strError)
284 {
285 #ifdef _MSC_VER  // !!! FIXME.  --ryan.
286         throw std::exception( strError);
287 #endif
288
289         /*      char errMsgCStr [256];
290         Str255 strErr;
291
292         sprintf (errMsgCStr, "%s", strError); 
293
294         // out as debug string
295         CToPStr (strErr, errMsgCStr);
296         DebugStr (strErr);
297         */
298 }
299
300 void SetupDSpFullScreen ()
301 {
302 }
303
304
305 void ShutdownDSp ()
306 {
307 }
308
309
310 //-----------------------------------------------------------------------------------------------------------------------
311
312 // OpenGL Drawing
313
314 void DrawGL (Game & game)
315 {
316         game.DrawGLScene();
317 }
318
319
320 static KeyMap g_theKeys;
321
322 void SetKey( int key)
323 {
324     g_theKeys[ key >> 3] |= (1 << (key & 7));
325 }
326
327 void ClearKey( int key)
328 {
329     g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
330 }
331
332 void GetKeys(  unsigned char theKeys[16])
333 {
334     memcpy( theKeys, &g_theKeys, 16);
335 }
336
337 Boolean Button()
338 {
339     return g_button;
340 }
341
342
343 #define MAX_SDLKEYS SDLK_LAST
344 static unsigned short KeyTable[MAX_SDLKEYS];
345
346 static void initSDLKeyTable(void)
347 {
348     memset(KeyTable, 0xFF, sizeof (KeyTable));
349     KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
350     KeyTable[SDLK_TAB] = MAC_TAB_KEY;
351     KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
352     KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
353     KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
354     KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
355     KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
356     KeyTable[SDLK_END] = MAC_END_KEY;
357     KeyTable[SDLK_HOME] = MAC_HOME_KEY;
358     KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
359     KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
360     KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
361     KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
362     KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
363     KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
364     KeyTable[SDLK_0] = MAC_0_KEY;
365     KeyTable[SDLK_1] = MAC_1_KEY;
366     KeyTable[SDLK_2] = MAC_2_KEY;
367     KeyTable[SDLK_3] = MAC_3_KEY;
368     KeyTable[SDLK_4] = MAC_4_KEY;
369     KeyTable[SDLK_5] = MAC_5_KEY;
370     KeyTable[SDLK_6] = MAC_6_KEY;
371     KeyTable[SDLK_7] = MAC_7_KEY;
372     KeyTable[SDLK_8] = MAC_8_KEY;
373     KeyTable[SDLK_9] = MAC_9_KEY;
374     KeyTable[SDLK_a] = MAC_A_KEY;
375     KeyTable[SDLK_b] = MAC_B_KEY;
376     KeyTable[SDLK_c] = MAC_C_KEY;
377     KeyTable[SDLK_d] = MAC_D_KEY;
378     KeyTable[SDLK_e] = MAC_E_KEY;
379     KeyTable[SDLK_f] = MAC_F_KEY;
380     KeyTable[SDLK_g] = MAC_G_KEY;
381     KeyTable[SDLK_h] = MAC_H_KEY;
382     KeyTable[SDLK_i] = MAC_I_KEY;
383     KeyTable[SDLK_j] = MAC_J_KEY;
384     KeyTable[SDLK_k] = MAC_K_KEY;
385     KeyTable[SDLK_l] = MAC_L_KEY;
386     KeyTable[SDLK_m] = MAC_M_KEY;
387     KeyTable[SDLK_n] = MAC_N_KEY;
388     KeyTable[SDLK_o] = MAC_O_KEY;
389     KeyTable[SDLK_p] = MAC_P_KEY;
390     KeyTable[SDLK_q] = MAC_Q_KEY;
391     KeyTable[SDLK_r] = MAC_R_KEY;
392     KeyTable[SDLK_s] = MAC_S_KEY;
393     KeyTable[SDLK_t] = MAC_T_KEY;
394     KeyTable[SDLK_u] = MAC_U_KEY;
395     KeyTable[SDLK_v] = MAC_V_KEY;
396     KeyTable[SDLK_w] = MAC_W_KEY;
397     KeyTable[SDLK_x] = MAC_X_KEY;
398     KeyTable[SDLK_y] = MAC_Y_KEY;
399     KeyTable[SDLK_z] = MAC_Z_KEY;
400     KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
401     KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
402     KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
403     KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
404     KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
405     KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
406     KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
407     KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
408     KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
409     KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
410     KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
411     KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
412     KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
413     KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
414     KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
415     KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
416     KeyTable[SDLK_F1] = MAC_F1_KEY;
417     KeyTable[SDLK_F2] = MAC_F2_KEY;
418     KeyTable[SDLK_F3] = MAC_F3_KEY;
419     KeyTable[SDLK_F4] = MAC_F4_KEY;
420     KeyTable[SDLK_F5] = MAC_F5_KEY;
421     KeyTable[SDLK_F6] = MAC_F6_KEY;
422     KeyTable[SDLK_F7] = MAC_F7_KEY;
423     KeyTable[SDLK_F8] = MAC_F8_KEY;
424     KeyTable[SDLK_F9] = MAC_F9_KEY;
425     KeyTable[SDLK_F10] = MAC_F10_KEY;
426     KeyTable[SDLK_F11] = MAC_F11_KEY;
427     KeyTable[SDLK_F12] = MAC_F12_KEY;
428     KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
429     KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
430     KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
431     KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
432     KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
433     KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
434     KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
435     KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
436     KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
437     KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
438     KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
439 }
440
441 static inline int clamp_sdl_mouse_button(Uint8 button)
442 {
443     if (button == 2)   // right mouse button is button 3 in SDL.
444         button = 3;
445     else if (button == 3)
446         button = 2;
447
448     if ((button >= 1) && (button <= 3))
449         return button - 1;
450     return -1;
451 }
452
453 static void sdlEventProc(const SDL_Event &e, Game &game)
454 {
455     int val;
456     bool skipkey = false;
457     SDLMod mod;
458
459     switch(e.type)
460         {
461         case SDL_MOUSEMOTION:
462             game.deltah += e.motion.xrel;
463             game.deltav += e.motion.yrel;
464             return;
465
466                 case SDL_MOUSEBUTTONDOWN:
467                         {
468                 val = clamp_sdl_mouse_button(e.button.button);
469                 if ((val >= 0) && (val <= 2))
470                 {
471                     if (val == 0)
472                                     g_button = true;
473                                 buttons[val] = true;
474                 }
475                         }
476                         return;
477
478                 case SDL_MOUSEBUTTONUP:
479                         {
480                 val = clamp_sdl_mouse_button(e.button.button);
481                 if ((val >= 0) && (val <= 2))
482                 {
483                     if (val == 0)
484                                     g_button = false;
485                                 buttons[val] = false;
486                 }
487                         }
488             return;
489
490         case SDL_KEYDOWN:
491             if (e.key.keysym.sym == SDLK_g)
492             {
493                 if (e.key.keysym.mod & KMOD_CTRL)
494                 {
495                     skipkey = true;
496                     SDL_GrabMode mode = SDL_GRAB_ON;
497                     if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
498                     {
499                         mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
500                         mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
501                     }
502                     SDL_WM_GrabInput(mode);
503                 }
504             }
505
506             else if (e.key.keysym.sym == SDLK_RETURN)
507             {
508                 if (e.key.keysym.mod & KMOD_ALT)
509                 {
510                     skipkey = true;
511                     SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
512                 }
513             }
514
515             if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
516             {
517                 if (KeyTable[e.key.keysym.sym] != 0xffff)
518                     SetKey(KeyTable[e.key.keysym.sym]);
519             }
520
521             mod = SDL_GetModState();
522             if (mod & KMOD_CTRL)
523                 SetKey(MAC_CONTROL_KEY);
524             if (mod & KMOD_ALT)
525                 SetKey(MAC_OPTION_KEY);
526             if (mod & KMOD_META)
527                 SetKey(MAC_COMMAND_KEY);
528             if (mod & KMOD_SHIFT)
529                 SetKey(MAC_SHIFT_KEY);
530             if (mod & KMOD_CAPS)
531                 SetKey(MAC_CAPS_LOCK_KEY);
532
533             return;
534
535         case SDL_KEYUP:
536             if (e.key.keysym.sym < SDLK_LAST)
537             {
538                 if (KeyTable[e.key.keysym.sym] != 0xffff)
539                     ClearKey(KeyTable[e.key.keysym.sym]);
540             }
541
542             mod = SDL_GetModState();
543             if ((mod & KMOD_CTRL) == 0)
544                 ClearKey(MAC_CONTROL_KEY);
545             if ((mod & KMOD_ALT) == 0)
546                 ClearKey(MAC_OPTION_KEY);
547             if ((mod & KMOD_META) == 0)
548                 ClearKey(MAC_COMMAND_KEY);
549             if ((mod & KMOD_SHIFT) == 0)
550                 ClearKey(MAC_SHIFT_KEY);
551             if ((mod & KMOD_CAPS) == 0)
552                 ClearKey(MAC_CAPS_LOCK_KEY);
553             return;
554     }
555 }
556
557
558 // --------------------------------------------------------------------------
559
560 static Point gMidPoint;
561
562 Boolean SetUp (Game & game)
563 {
564         char string[10];
565
566         LOGFUNC;
567
568         randSeed = UpTime().lo;
569
570         osx = 0;
571         ifstream ipstream(ConvertFileName("Data/config.txt"), std::ios::in /*| std::ios::nocreate*/);
572         detail=1;
573         ismotionblur=0;
574         usermousesensitivity=1;
575         kContextWidth=640;
576         kContextHeight=480;
577         kBitsPerPixel = 32;
578         floatjump=0;
579         cellophane=0;
580         texdetail=4;
581         autoslomo=1;
582         decals=1;
583         invertmouse=0;
584         bloodtoggle=0;
585         terraindetail=2;
586         foliage=1;
587         musictoggle=1;
588         trilinear=1;
589         gamespeed=1;
590         difficulty=1;
591         damageeffects=0;
592         texttoggle=1;
593         alwaysblur=0;
594         showpoints=0;
595         immediate=0;
596         velocityblur=0;
597
598         slomospeed=0.25;
599         slomofreq=8012;
600
601         volume = 0.8f;
602
603         game.crouchkey=MAC_SHIFT_KEY;
604         game.jumpkey=MAC_SPACE_KEY;
605         game.leftkey=MAC_A_KEY;
606         game.forwardkey=MAC_W_KEY;
607         game.backkey=MAC_S_KEY;
608         game.rightkey=MAC_D_KEY;
609         game.drawkey=MAC_E_KEY;
610         game.throwkey=MAC_Q_KEY;
611         game.attackkey=MAC_MOUSEBUTTON1;
612         game.chatkey=MAC_T_KEY;
613         numplayers=1;
614         ambientsound=1;
615         vblsync=0;
616         debugmode=0;
617
618         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
619
620         if(!ipstream) {
621                 ofstream opstream(ConvertFileName("Data/config.txt", "w"));
622                 opstream << "Screenwidth:\n";
623                 opstream << kContextWidth;
624                 opstream << "\nScreenheight:\n";
625                 opstream << kContextHeight;
626                 opstream << "\nMouse sensitivity:\n";
627                 opstream << usermousesensitivity;
628                 opstream << "\nBlur(0,1):\n";
629                 opstream << ismotionblur;
630                 opstream << "\nOverall Detail(0,1,2) higher=better:\n";
631                 opstream << detail;
632                 opstream << "\nFloating jump:\n";
633                 opstream << floatjump;
634                 opstream << "\nMouse jump:\n";
635                 opstream << mousejump;
636                 opstream << "\nAmbient sound:\n";
637                 opstream << ambientsound;
638                 opstream << "\nBlood (0,1,2):\n";
639                 opstream << bloodtoggle;
640                 opstream << "\nAuto slomo:\n";
641                 opstream << autoslomo;
642                 opstream << "\nFoliage:\n";
643                 opstream << foliage;
644                 opstream << "\nMusic:\n";
645                 opstream << musictoggle;
646                 opstream << "\nTrilinear:\n";
647                 opstream << trilinear;
648                 opstream << "\nDecals(shadows,blood puddles,etc):\n";
649                 opstream << decals;
650                 opstream << "\nInvert mouse:\n";
651                 opstream << invertmouse;
652                 opstream << "\nGamespeed:\n";
653                 opstream << gamespeed;
654                 opstream << "\nDifficulty(0,1,2) higher=harder:\n";
655                 opstream << difficulty;
656                 opstream << "\nDamage effects(blackout, doublevision):\n";
657                 opstream << damageeffects;
658                 opstream << "\nText:\n";
659                 opstream << texttoggle;
660                 opstream << "\nDebug:\n";
661                 opstream << debugmode;
662                 opstream << "\nVBL Sync:\n";
663                 opstream << vblsync;
664                 opstream << "\nShow Points:\n";
665                 opstream << showpoints;
666                 opstream << "\nAlways Blur:\n";
667                 opstream << alwaysblur;
668                 opstream << "\nImmediate mode (turn on on G5):\n";
669                 opstream << immediate;
670                 opstream << "\nVelocity blur:\n";
671                 opstream << velocityblur;
672                 opstream << "\nVolume:\n";
673                 opstream << volume;
674                 opstream << "\nForward key:\n";
675                 opstream << KeyToChar(game.forwardkey);
676                 opstream << "\nBack key:\n";
677                 opstream << KeyToChar(game.backkey);
678                 opstream << "\nLeft key:\n";
679                 opstream << KeyToChar(game.leftkey);
680                 opstream << "\nRight key:\n";
681                 opstream << KeyToChar(game.rightkey);
682                 opstream << "\nJump key:\n";
683                 opstream << KeyToChar(game.jumpkey);
684                 opstream << "\nCrouch key:\n";
685                 opstream << KeyToChar(game.crouchkey);
686                 opstream << "\nDraw key:\n";
687                 opstream << KeyToChar(game.drawkey);
688                 opstream << "\nThrow key:\n";
689                 opstream << KeyToChar(game.throwkey);
690                 opstream << "\nAttack key:\n";
691                 opstream << KeyToChar(game.attackkey);
692                 opstream << "\nChat key:\n";
693                 opstream << KeyToChar(game.chatkey);
694                 opstream.close();
695         }
696         if(ipstream){
697                 int i;
698                 ipstream.ignore(256,'\n');
699                 ipstream >> kContextWidth;
700                 ipstream.ignore(256,'\n');
701                 ipstream.ignore(256,'\n');
702                 ipstream >> kContextHeight;
703                 ipstream.ignore(256,'\n');
704                 ipstream.ignore(256,'\n');
705                 ipstream >> usermousesensitivity;
706                 ipstream.ignore(256,'\n');
707                 ipstream.ignore(256,'\n');
708                 ipstream >> i;
709                 ismotionblur = (i != 0);
710                 ipstream.ignore(256,'\n');
711                 ipstream.ignore(256,'\n');
712                 ipstream >> detail;
713                 if(detail!=0)kBitsPerPixel=32;
714                 else kBitsPerPixel=16;
715                 ipstream.ignore(256,'\n');
716                 ipstream.ignore(256,'\n');
717                 ipstream >> i;
718                 floatjump = (i != 0);
719                 ipstream.ignore(256,'\n');
720                 ipstream.ignore(256,'\n');
721                 ipstream >> i;
722                 mousejump = (i != 0);
723                 ipstream.ignore(256,'\n');
724                 ipstream.ignore(256,'\n');
725                 ipstream >> i;
726                 ambientsound = (i != 0);
727                 ipstream.ignore(256,'\n');
728                 ipstream.ignore(256,'\n');
729                 ipstream >> bloodtoggle;
730                 ipstream.ignore(256,'\n');
731                 ipstream.ignore(256,'\n');
732                 ipstream >> i;
733                 autoslomo = (i != 0);
734                 ipstream.ignore(256,'\n');
735                 ipstream.ignore(256,'\n');
736                 ipstream >> i;
737                 foliage = (i != 0);
738                 ipstream.ignore(256,'\n');
739                 ipstream.ignore(256,'\n');
740                 ipstream >> i;
741                 musictoggle = (i != 0);
742                 ipstream.ignore(256,'\n');
743                 ipstream.ignore(256,'\n');
744                 ipstream >> i;
745                 trilinear = (i != 0);
746                 ipstream.ignore(256,'\n');
747                 ipstream.ignore(256,'\n');
748                 ipstream >> i;
749                 decals = (i != 0);
750                 ipstream.ignore(256,'\n');
751                 ipstream.ignore(256,'\n');
752                 ipstream >> i;
753                 invertmouse = (i != 0);
754                 ipstream.ignore(256,'\n');
755                 ipstream.ignore(256,'\n');
756                 ipstream >> gamespeed;
757                 oldgamespeed=gamespeed;
758                 if(oldgamespeed==0){
759                         gamespeed=1;
760                         oldgamespeed=1;
761                 }
762                 ipstream.ignore(256,'\n');
763                 ipstream.ignore(256,'\n');
764                 ipstream >> difficulty;
765                 ipstream.ignore(256,'\n');
766                 ipstream.ignore(256,'\n');
767                 ipstream >> i;
768                 damageeffects = (i != 0);
769                 ipstream.ignore(256,'\n');
770                 ipstream.ignore(256,'\n');
771                 ipstream >> i;
772                 texttoggle = (i != 0);
773                 ipstream.ignore(256,'\n');
774                 ipstream.ignore(256,'\n');
775                 ipstream >> i;
776                 debugmode = (i != 0);
777                 ipstream.ignore(256,'\n');
778                 ipstream.ignore(256,'\n');
779                 ipstream >> i;
780                 vblsync = (i != 0);
781                 ipstream.ignore(256,'\n');
782                 ipstream.ignore(256,'\n');
783                 ipstream >> i;
784                 showpoints = (i != 0);
785                 ipstream.ignore(256,'\n');
786                 ipstream.ignore(256,'\n');
787                 ipstream >> i;
788                 alwaysblur = (i != 0);
789                 ipstream.ignore(256,'\n');
790                 ipstream.ignore(256,'\n');
791                 ipstream >> i;
792                 immediate = (i != 0);
793                 ipstream.ignore(256,'\n');
794                 ipstream.ignore(256,'\n');
795                 ipstream >> i;
796                 velocityblur = (i != 0);
797                 ipstream.ignore(256,'\n');
798                 ipstream.ignore(256,'\n'); 
799                 ipstream >> volume;
800                 ipstream.ignore(256,'\n');
801                 ipstream.ignore(256,'\n'); 
802                 ipstream >> string;
803                 game.forwardkey=CharToKey(string);
804                 ipstream.ignore(256,'\n');
805                 ipstream.ignore(256,'\n');
806                 ipstream >> string;
807                 game.backkey=CharToKey(string);
808                 ipstream.ignore(256,'\n');
809                 ipstream.ignore(256,'\n');
810                 ipstream >> string;
811                 game.leftkey=CharToKey(string);
812                 ipstream.ignore(256,'\n');
813                 ipstream.ignore(256,'\n');
814                 ipstream >> string;
815                 game.rightkey=CharToKey(string);
816                 ipstream.ignore(256,'\n');
817                 ipstream.ignore(256,'\n');
818                 ipstream >> string;
819                 game.jumpkey=CharToKey(string);
820                 ipstream.ignore(256,'\n');
821                 ipstream.ignore(256,'\n');
822                 ipstream >> string;
823                 game.crouchkey=CharToKey(string);
824                 ipstream.ignore(256,'\n');
825                 ipstream.ignore(256,'\n');
826                 ipstream >> string;
827                 game.drawkey=CharToKey(string);
828                 ipstream.ignore(256,'\n');
829                 ipstream.ignore(256,'\n');
830                 ipstream >> string;
831                 game.throwkey=CharToKey(string);
832                 ipstream.ignore(256,'\n');
833                 ipstream.ignore(256,'\n');
834                 ipstream >> string;
835                 game.attackkey=CharToKey(string);
836                 ipstream.ignore(256,'\n');
837                 ipstream.ignore(256,'\n');
838                 ipstream >> string;
839                 game.chatkey=CharToKey(string);
840                 ipstream.close();
841
842                 if(detail>2)detail=2;
843                 if(detail<0)detail=0;
844                 if(screenwidth<0)screenwidth=640;
845                 if(screenheight<0)screenheight=480;
846
847         }
848         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
849                 kBitsPerPixel=16;
850         }
851
852
853         selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
854
855         SetupDSpFullScreen();
856
857
858     if (!SDL_WasInit(SDL_INIT_VIDEO))
859     {
860         if (SDL_Init(SDL_INIT_VIDEO) == -1)
861         {
862             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
863             return false;
864         }
865
866         if (SDL_GL_LoadLibrary(NULL) == -1)
867         {
868             fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
869             SDL_Quit();
870             return false;
871         }
872
873         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
874         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
875             res = hardcoded_resolutions;
876
877         // reverse list (it was sorted biggest to smallest by SDL)...
878         int count;
879         for (count = 0; res[count]; count++)
880         {
881             if ((res[count]->w < 640) || (res[count]->h < 480))
882                 break;   // sane lower limit.
883         }
884
885         static SDL_Rect *resolutions_block = NULL;
886         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
887         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
888         if ((resolutions_block == NULL) || (resolutions == NULL))
889         {
890             SDL_Quit();
891             fprintf(stderr, "Out of memory!\n");
892             return false;
893         }
894
895         resolutions[count--] = NULL;
896         for (int i = 0; count >= 0; i++, count--)
897         {
898             memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
899             resolutions[count] = &resolutions_block[count];
900         }
901
902         if (cmdline("showresolutions"))
903         {
904             printf("Resolutions we think are okay:\n");
905             for (int i = 0; resolutions[i]; i++)
906                 printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
907         }
908     }
909
910     Uint32 sdlflags = SDL_OPENGL;
911     if (!cmdline("windowed"))
912         sdlflags |= SDL_FULLSCREEN;
913
914     SDL_WM_SetCaption("Lugaru", "Lugaru");
915
916     SDL_ShowCursor(0);
917
918     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
919
920     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
921     {
922         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
923         fprintf(stderr, "forcing 640x480...\n");
924         kContextWidth = 640;
925         kContextHeight = 480;
926         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
927         {
928             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
929             fprintf(stderr, "forcing 640x480 windowed mode...\n");
930             sdlflags &= ~SDL_FULLSCREEN;
931             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
932             {
933                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
934                 return false;
935             }
936         }
937     }
938
939     int dblbuf = 0;
940     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
941     {
942         fprintf(stderr, "Failed to get double buffered GL context!\n");
943         SDL_Quit();
944         return false;
945     }
946
947     if (!lookup_all_glsyms())
948     {
949         SDL_Quit();
950         return false;
951     }
952
953     if (!cmdline("nomousegrab"))
954         SDL_WM_GrabInput(SDL_GRAB_ON);
955
956
957         glClear( GL_COLOR_BUFFER_BIT );
958         swap_gl_buffers();
959
960         // clear all states
961         glDisable( GL_ALPHA_TEST);
962         glDisable( GL_BLEND);
963         glDisable( GL_DEPTH_TEST);
964         //      glDisable( GL_DITHER);
965         glDisable( GL_FOG);
966         glDisable( GL_LIGHTING);
967         glDisable( GL_LOGIC_OP);
968         glDisable( GL_STENCIL_TEST);
969         glDisable( GL_TEXTURE_1D);
970         glDisable( GL_TEXTURE_2D);
971         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
972         glPixelTransferi( GL_RED_SCALE, 1);
973         glPixelTransferi( GL_RED_BIAS, 0);
974         glPixelTransferi( GL_GREEN_SCALE, 1);
975         glPixelTransferi( GL_GREEN_BIAS, 0);
976         glPixelTransferi( GL_BLUE_SCALE, 1);
977         glPixelTransferi( GL_BLUE_BIAS, 0);
978         glPixelTransferi( GL_ALPHA_SCALE, 1);
979         glPixelTransferi( GL_ALPHA_BIAS, 0);
980
981         // set initial rendering states
982         glShadeModel( GL_SMOOTH);
983         glClearDepth( 1.0f);
984         glDepthFunc( GL_LEQUAL);
985         glDepthMask( GL_TRUE);
986         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
987         glEnable( GL_DEPTH_TEST);
988         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
989         glCullFace( GL_FRONT);
990         glEnable( GL_CULL_FACE);
991         glEnable( GL_LIGHTING);
992 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
993         glEnable( GL_DITHER);
994         glEnable( GL_COLOR_MATERIAL);
995         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
996         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
997         glAlphaFunc( GL_GREATER, 0.5f);
998
999         GLint width = kContextWidth;
1000         GLint height = kContextHeight;
1001         gMidPoint.h = width / 2;
1002         gMidPoint.v = height / 2;
1003         screenwidth=width;
1004         screenheight=height;
1005
1006         game.newdetail=detail;
1007         game.newscreenwidth=screenwidth;
1008         game.newscreenheight=screenheight;
1009
1010         game.InitGame();
1011
1012         return true;
1013 }
1014
1015
1016 static void DoMouse(Game & game)
1017 {
1018
1019         if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
1020         {
1021                 game.deltah *= usermousesensitivity;
1022                 game.deltav *= usermousesensitivity;
1023                 game.mousecoordh += game.deltah;
1024                 game.mousecoordv += game.deltav;
1025         if (game.mousecoordh < 0)
1026             game.mousecoordh = 0;
1027         else if (game.mousecoordh >= kContextWidth)
1028             game.mousecoordh = kContextWidth - 1;
1029         if (game.mousecoordv < 0)
1030             game.mousecoordv = 0;
1031         else if (game.mousecoordv >= kContextHeight)
1032             game.mousecoordv = kContextHeight - 1;
1033         }
1034
1035 }
1036
1037
1038
1039 // --------------------------------------------------------------------------
1040
1041 void DoKey (SInt8 theKey, SInt8 theCode)
1042 {
1043         // do nothing
1044 }
1045
1046 // --------------------------------------------------------------------------
1047
1048
1049
1050 void DoFrameRate (int update)
1051 {       
1052         static long frames = 0;
1053
1054         static AbsoluteTime time = {0,0};
1055         static AbsoluteTime frametime = {0,0};
1056         AbsoluteTime currTime = UpTime ();
1057         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
1058
1059         if (0 > deltaTime)      // if negative microseconds
1060                 deltaTime /= -1000000.0;
1061         else                            // else milliseconds
1062                 deltaTime /= 1000.0;
1063
1064         multiplier=deltaTime;
1065         if(multiplier<.001)multiplier=.001;
1066         if(multiplier>10)multiplier=10;
1067         if(update)frametime = currTime; // reset for next time interval
1068
1069         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
1070
1071         if (0 > deltaTime)      // if negative microseconds
1072                 deltaTime /= -1000000.0;
1073         else                            // else milliseconds
1074                 deltaTime /= 1000.0;
1075         frames++;
1076         if (0.001 <= deltaTime) // has update interval passed
1077         {
1078                 if(update){
1079                         time = currTime;        // reset for next time interval
1080                         frames = 0;
1081                 }
1082         }
1083 }
1084
1085
1086 void DoUpdate (Game & game)
1087 {
1088         static float sps=200;
1089         static int count;
1090         static float oldmult;
1091
1092         DoFrameRate(1);
1093         if(multiplier>.6)multiplier=.6;
1094
1095         game.fps=1/multiplier;
1096
1097         count = multiplier*sps;
1098         if(count<2)count=2;
1099         //if(count>10)count=10;
1100
1101         realmultiplier=multiplier;
1102         multiplier*=gamespeed;
1103         if(difficulty==1)multiplier*=.9;
1104         if(difficulty==0)multiplier*=.8;
1105
1106         if(game.loading==4)multiplier*=.00001;
1107         //multiplier*.9;
1108         if(slomo&&!mainmenu)multiplier*=slomospeed;
1109         //if(freeze)multiplier*=0.00001;
1110         oldmult=multiplier;
1111         multiplier/=(float)count;
1112
1113         DoMouse(game);
1114
1115         game.TickOnce();
1116
1117         for(int i=0;i<count;i++)
1118         {
1119                 game.Tick();
1120         }
1121         multiplier=oldmult;
1122
1123         game.TickOnceAfter();
1124 /* - Debug code to test how many channels were active on average per frame
1125         static long frames = 0;
1126
1127         static AbsoluteTime start = {0,0};
1128         AbsoluteTime currTime = UpTime ();
1129         static int num_channels = 0;
1130         
1131         num_channels += OPENAL_GetChannelsPlaying();
1132         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
1133
1134         if (0 > deltaTime)      // if negative microseconds
1135                 deltaTime /= -1000000.0;
1136         else                            // else milliseconds
1137                 deltaTime /= 1000.0;
1138
1139         ++frames;
1140
1141         if (deltaTime >= 1)
1142         {
1143                 start = currTime;
1144                 float avg_channels = (float)num_channels / (float)frames;
1145
1146                 ofstream opstream("log.txt",ios::app); 
1147                 opstream << "Average frame count: ";
1148                 opstream << frames;
1149                 opstream << " frames - ";
1150                 opstream << avg_channels;
1151                 opstream << " per frame.\n";
1152                 opstream.close();
1153
1154                 frames = 0;
1155                 num_channels = 0;
1156         }
1157 */
1158         DrawGL (game);
1159 }
1160
1161 // --------------------------------------------------------------------------
1162
1163
1164 void CleanUp (void)
1165 {
1166         LOGFUNC;
1167
1168 //      game.Dispose();
1169
1170
1171
1172
1173     SDL_Quit();
1174     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
1175     #include "glstubs.h"
1176     #undef GL_FUNC
1177     // cheat here...static destructors are calling glDeleteTexture() after
1178     //  the context is destroyed and libGL unloaded by SDL_Quit().
1179     pglDeleteTextures = glDeleteTextures_doNothing;
1180
1181 }
1182
1183 // --------------------------------------------------------------------------
1184
1185 static bool IsFocused()
1186 {
1187     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
1188 }
1189
1190
1191 static void launch_web_browser(const char *url)
1192 {
1193 #ifdef WIN32
1194     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
1195
1196 #elif (defined(__APPLE__) && defined(__MACH__))
1197     const char *fmt = "open '%s'";
1198     const size_t len = strlen(fmt) + strlen(url) + 16;
1199     char *buf = new char[len];
1200     snprintf(buf, len, fmt, url);
1201     system(buf);
1202     delete[] buf;
1203
1204 #elif PLATFORM_LINUX
1205     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
1206     const size_t len = strlen(fmt) + strlen(url) + 16;
1207     char *buf = new char[len];
1208     snprintf(buf, len, fmt, url);
1209     system(buf);
1210     delete[] buf;
1211 #endif
1212 }
1213
1214
1215 #ifndef WIN32
1216 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
1217 static char *findBinaryInPath(const char *bin, char *envr)
1218 {
1219     size_t alloc_size = 0;
1220     char *exe = NULL;
1221     char *start = envr;
1222     char *ptr;
1223
1224     do
1225     {
1226         size_t size;
1227         ptr = strchr(start, ':');  /* find next $PATH separator. */
1228         if (ptr)
1229             *ptr = '\0';
1230
1231         size = strlen(start) + strlen(bin) + 2;
1232         if (size > alloc_size)
1233         {
1234             char *x = (char *) realloc(exe, size);
1235             if (x == NULL)
1236             {
1237                 if (exe != NULL)
1238                     free(exe);
1239                 return(NULL);
1240             } /* if */
1241
1242             alloc_size = size;
1243             exe = x;
1244         } /* if */
1245
1246         /* build full binary path... */
1247         strcpy(exe, start);
1248         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
1249             strcat(exe, "/");
1250         strcat(exe, bin);
1251
1252         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
1253         {
1254             strcpy(exe, start);  /* i'm lazy. piss off. */
1255             return(exe);
1256         } /* if */
1257
1258         start = ptr + 1;  /* start points to beginning of next element. */
1259     } while (ptr != NULL);
1260
1261     if (exe != NULL)
1262         free(exe);
1263
1264     return(NULL);  /* doesn't exist in path. */
1265 } /* findBinaryInPath */
1266
1267
1268 char *calcBaseDir(const char *argv0)
1269 {
1270     /* If there isn't a path on argv0, then look through the $PATH for it. */
1271     char *retval;
1272     char *envr;
1273
1274     const char *ptr = strrchr((char *)argv0, '/');
1275     if (strchr(argv0, '/'))
1276     {
1277         retval = strdup(argv0);
1278         if (retval)
1279             *((char *) strrchr(retval, '/')) = '\0';
1280         return(retval);
1281     }
1282
1283     envr = getenv("PATH");
1284     if (!envr) return NULL;
1285     envr = strdup(envr);
1286     if (!envr) return NULL;
1287     retval = findBinaryInPath(argv0, envr);
1288     free(envr);
1289     return(retval);
1290 }
1291
1292 static inline void chdirToAppPath(const char *argv0)
1293 {
1294     char *dir = calcBaseDir(argv0);
1295     if (dir)
1296     {
1297         #if (defined(__APPLE__) && defined(__MACH__))
1298         // Chop off /Contents/MacOS if it's at the end of the string, so we
1299         //  land in the base of the app bundle.
1300         const size_t len = strlen(dir);
1301         const char *bundledirs = "/Contents/MacOS";
1302         const size_t bundledirslen = strlen(bundledirs);
1303         if (len > bundledirslen)
1304         {
1305             char *ptr = (dir + len) - bundledirslen;
1306             if (strcasecmp(ptr, bundledirs) == 0)
1307                 *ptr = '\0';
1308         }
1309         #endif
1310         chdir(dir);
1311         free(dir);
1312     }
1313 }
1314 #endif
1315
1316
1317 int main(int argc, char **argv)
1318 {
1319 #ifndef __MINGW32__
1320     _argc = argc;
1321     _argv = argv;
1322 #endif
1323
1324     // !!! FIXME: we could use a Win32 API for this.  --ryan.
1325 #ifndef WIN32
1326     chdirToAppPath(argv[0]);
1327 #endif
1328
1329         LOGFUNC;
1330
1331         memset( &g_theKeys, 0, sizeof( KeyMap));
1332
1333     initSDLKeyTable();
1334
1335         try
1336         {
1337                 bool regnow = false;
1338                 {
1339                         Game game;
1340                         pgame = &game;
1341
1342                         //ofstream os("error.txt");
1343                         //os.close();
1344                         //ofstream os("log.txt");
1345                         //os.close();
1346
1347                         if (!SetUp (game))
1348                 return 42;
1349
1350                         while (!gDone&&!game.quit&&(!game.tryquit))
1351                         {
1352                                 if (IsFocused())
1353                                 {
1354                                         gameFocused = true;
1355
1356                                         // check windows messages
1357                         
1358                                         game.deltah = 0;
1359                                         game.deltav = 0;
1360                                         SDL_Event e;
1361                                         // message pump
1362                                         while( SDL_PollEvent( &e ) )
1363                                         {
1364                                                 if( e.type == SDL_QUIT )
1365                                                 {
1366                                                         gDone=true;
1367                                                         break;
1368                                                 }
1369                                                 sdlEventProc(e, game);
1370                                         }
1371                                 
1372
1373                                         // game
1374                                         DoUpdate(game);
1375                                 }
1376                                 else
1377                                 {
1378                                         if (gameFocused)
1379                                         {
1380                                                 // allow game chance to pause
1381                                                 gameFocused = false;
1382                                                 DoUpdate(game);
1383                                         }
1384
1385                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
1386                     STUBBED("give up CPU but sniff the event queue");
1387                                 }
1388                         }
1389
1390                         regnow = game.registernow;
1391                 }
1392                 pgame = 0;
1393
1394                 CleanUp ();
1395 //              if(game.registernow){
1396                 if(regnow)
1397                 {
1398             #if (defined(__APPLE__) && defined(__MACH__))
1399             launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
1400             #elif PLATFORM_LINUX
1401             launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
1402             #else
1403             launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
1404             #endif
1405                 }
1406
1407         #if PLATFORM_LINUX  // (this may not be necessary any more.)
1408         _exit(0);  // !!! FIXME: hack...crashes on exit!
1409         #endif
1410                 return 0;
1411         }
1412         catch (const std::exception& error)
1413         {
1414                 CleanUp();
1415
1416                 std::string e = "Caught exception: ";
1417                 e += error.what();
1418
1419                 LOG(e);
1420
1421                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
1422         }
1423
1424         CleanUp();
1425
1426         return -1;
1427 }
1428
1429
1430
1431         // --------------------------------------------------------------------------
1432
1433
1434
1435         bool selectDetail(int & width, int & height, int & bpp, int & detail)
1436         {
1437                 bool res = true;
1438
1439                 // currently with SDL, we just use whatever is requested
1440                 //  and don't care.  --ryan.
1441                 
1442
1443                 return res;
1444         }
1445
1446         extern int channels[100];
1447         extern OPENAL_SAMPLE * samp[100];
1448         extern OPENAL_STREAM * strm[20];
1449
1450         extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1451         {
1452                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1453                 if (currSample && currSample == samp[chan])
1454                 {
1455                         if (OPENAL_GetPaused(channels[chan]))
1456                         {
1457                                 OPENAL_StopSound(channels[chan]);
1458                                 channels[chan] = OPENAL_FREE;
1459                         }
1460                         else if (OPENAL_IsPlaying(channels[chan]))
1461                         {
1462                                 int loop_mode = OPENAL_GetLoopMode(channels[chan]);
1463                                 if (loop_mode & OPENAL_LOOP_OFF)
1464                                 {
1465                                         channels[chan] = OPENAL_FREE;
1466                                 }
1467                         }
1468                 }
1469                 else
1470                 {
1471                         channels[chan] = OPENAL_FREE;
1472                 }
1473
1474                 channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
1475                 if (channels[chan] < 0)
1476                 {
1477                         channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
1478                 }
1479         }
1480
1481         extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
1482         {
1483                 const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
1484                 if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
1485                 {
1486                                 OPENAL_StopSound(channels[chan]);
1487                                 OPENAL_Stream_Stop(sptr);
1488                 }
1489                 else
1490                 {
1491                         OPENAL_Stream_Stop(sptr);
1492                         channels[chan] = OPENAL_FREE;
1493                 }
1494
1495                 channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
1496                 if (channels[chan] < 0)
1497                 {
1498                         channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
1499                 }
1500         }
1501
1502         bool LoadImage(const char * fname, TGAImageRec & tex)
1503         {
1504                 bool res = true;
1505
1506                 if ( tex.data == NULL )
1507                 {
1508                         return false;
1509                 }
1510
1511        
1512         res = load_image(fname, tex);
1513     
1514
1515                 return res;
1516         }
1517
1518         void ScreenShot(const char * fname)
1519         {
1520   
1521         save_image(fname);
1522   
1523         }
1524
1525
1526
1527 static bool load_image(const char *file_name, TGAImageRec &tex)
1528 {
1529     const char *ptr = strrchr((char *)file_name, '.');
1530     if (ptr)
1531     {
1532         if (strcasecmp(ptr+1, "png") == 0)
1533             return load_png(file_name, tex);
1534         else if (strcasecmp(ptr+1, "jpg") == 0)
1535             return load_jpg(file_name, tex);
1536     }
1537
1538     STUBBED("Unsupported image type");
1539     return false;
1540 }
1541
1542
1543 struct my_error_mgr {
1544   struct jpeg_error_mgr pub;    /* "public" fields */
1545   jmp_buf setjmp_buffer;        /* for return to caller */
1546 };
1547 typedef struct my_error_mgr * my_error_ptr;
1548
1549
1550 static void my_error_exit(j_common_ptr cinfo)
1551 {
1552         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
1553         longjmp(err->setjmp_buffer, 1);
1554 }
1555
1556 /* stolen from public domain example.c code in libjpg distribution. */
1557 static bool load_jpg(const char *file_name, TGAImageRec &tex)
1558 {
1559     struct jpeg_decompress_struct cinfo;
1560     struct my_error_mgr jerr;
1561     JSAMPROW buffer[1];         /* Output row buffer */
1562     int row_stride;             /* physical row width in output buffer */
1563     FILE *infile = fopen(file_name, "rb");
1564
1565     if (infile == NULL)
1566         return false;
1567
1568     cinfo.err = jpeg_std_error(&jerr.pub);
1569     jerr.pub.error_exit = my_error_exit;
1570     if (setjmp(jerr.setjmp_buffer)) {
1571         jpeg_destroy_decompress(&cinfo);
1572         fclose(infile);
1573         return false;
1574     }
1575
1576     jpeg_create_decompress(&cinfo);
1577     jpeg_stdio_src(&cinfo, infile);
1578     (void) jpeg_read_header(&cinfo, TRUE);
1579
1580     cinfo.out_color_space = JCS_RGB;
1581     cinfo.quantize_colors = 0;
1582     (void) jpeg_calc_output_dimensions(&cinfo);
1583     (void) jpeg_start_decompress(&cinfo);
1584
1585     row_stride = cinfo.output_width * cinfo.output_components;
1586     tex.sizeX = cinfo.output_width;
1587     tex.sizeY = cinfo.output_height;
1588     tex.bpp = 24;
1589
1590     while (cinfo.output_scanline < cinfo.output_height) {
1591         buffer[0] = (JSAMPROW)(char *)tex.data +
1592                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
1593         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
1594     }
1595
1596     (void) jpeg_finish_decompress(&cinfo);
1597     jpeg_destroy_decompress(&cinfo);
1598     fclose(infile);
1599
1600     return true;
1601 }
1602
1603
1604 /* stolen from public domain example.c code in libpng distribution. */
1605 static bool load_png(const char *file_name, TGAImageRec &tex)
1606 {
1607     bool hasalpha = false;
1608     png_structp png_ptr = NULL;
1609     png_infop info_ptr = NULL;
1610     png_uint_32 width, height;
1611     int bit_depth, color_type, interlace_type;
1612     png_byte **rows = NULL;
1613     bool retval = false;
1614     png_byte **row_pointers = NULL;
1615     FILE *fp = fopen(file_name, "rb");
1616
1617     if (fp == NULL)
1618         return(NULL);
1619
1620     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1621     if (png_ptr == NULL)
1622         goto png_done;
1623
1624     info_ptr = png_create_info_struct(png_ptr);
1625     if (info_ptr == NULL)
1626         goto png_done;
1627
1628     if (setjmp(png_jmpbuf(png_ptr)))
1629         goto png_done;
1630
1631     png_init_io(png_ptr, fp);
1632     png_read_png(png_ptr, info_ptr,
1633                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
1634                  NULL);
1635     png_get_IHDR(png_ptr, info_ptr, &width, &height,
1636                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
1637
1638     if (bit_depth != 8)  // transform SHOULD handle this...
1639         goto png_done;
1640
1641     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
1642         goto png_done;
1643
1644     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
1645         goto png_done;
1646
1647     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
1648     row_pointers = png_get_rows(png_ptr, info_ptr);
1649     if (!row_pointers)
1650         goto png_done;
1651
1652     if (!hasalpha)
1653     {
1654         png_byte *dst = tex.data;
1655         for (int i = height-1; i >= 0; i--)
1656         {
1657             png_byte *src = row_pointers[i];
1658             for (int j = 0; j < width; j++)
1659             {
1660                 dst[0] = src[0];
1661                 dst[1] = src[1];
1662                 dst[2] = src[2];
1663                 dst[3] = 0xFF;
1664                 src += 3;
1665                 dst += 4;
1666             }
1667         }
1668     }
1669
1670     else
1671     {
1672         png_byte *dst = tex.data;
1673         int pitch = width * 4;
1674         for (int i = height-1; i >= 0; i--, dst += pitch)
1675             memcpy(dst, row_pointers[i], pitch);
1676     }
1677
1678     tex.sizeX = width;
1679     tex.sizeY = height;
1680     tex.bpp = 32;
1681     retval = true;
1682
1683 png_done:
1684     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1685     if (fp)
1686         fclose(fp);
1687     return (retval);
1688 }
1689
1690
1691 static bool save_image(const char *file_name)
1692 {
1693     const char *ptr = strrchr((char *)file_name, '.');
1694     if (ptr)
1695     {
1696         if (strcasecmp(ptr+1, "png") == 0)
1697             return save_png(file_name);
1698     }
1699
1700     STUBBED("Unsupported image type");
1701     return false;
1702 }
1703
1704
1705 static bool save_png(const char *file_name)
1706 {
1707     FILE *fp = NULL;
1708     png_structp png_ptr = NULL;
1709     png_infop info_ptr = NULL;
1710     bool retval = false;
1711
1712     fp = fopen(file_name, "wb");
1713     if (fp == NULL)
1714         return false;
1715
1716     png_bytep *row_pointers = new png_bytep[kContextHeight];
1717     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1718     if ((!screenshot) || (!row_pointers))
1719         goto save_png_done;
1720
1721     glGetError();
1722     glReadPixels(0, 0, kContextWidth, kContextHeight,
1723                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1724     if (glGetError() != GL_NO_ERROR)
1725         goto save_png_done;
1726
1727     for (int i = 0; i < kContextHeight; i++)
1728         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1729
1730     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1731     if (png_ptr == NULL)
1732         goto save_png_done;
1733
1734     info_ptr = png_create_info_struct(png_ptr);
1735     if (info_ptr == NULL)
1736         goto save_png_done;
1737
1738     if (setjmp(png_jmpbuf(png_ptr)))
1739         goto save_png_done;
1740
1741     png_init_io(png_ptr, fp);
1742
1743     if (setjmp(png_jmpbuf(png_ptr)))
1744         goto save_png_done;
1745
1746     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1747                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1748                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1749
1750     png_write_info(png_ptr, info_ptr);
1751
1752     if (setjmp(png_jmpbuf(png_ptr)))
1753         goto save_png_done;
1754
1755         png_write_image(png_ptr, row_pointers);
1756
1757         if (setjmp(png_jmpbuf(png_ptr)))
1758         goto save_png_done;
1759
1760     png_write_end(png_ptr, NULL);
1761     retval = true;
1762
1763 save_png_done:
1764     png_destroy_write_struct(&png_ptr, &info_ptr);
1765     delete[] screenshot;
1766     delete[] row_pointers;
1767     if (fp)
1768         fclose(fp);
1769     if (!retval)
1770         unlink(ConvertFileName(file_name));
1771     return retval;
1772 }
1773
1774
1775