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