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