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