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