]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
Merge
[lugaru.git] / Source / OpenGL_Windows.cpp
1 /*
2 Copyright (C) 2003, 2010 - Wolfire Games
3
4 This file is part of Lugaru.
5
6 Lugaru is free software; you can redistribute it and/or
7 modify it under the terms of the GNU General Public License
8 as published by the Free Software Foundation; either version 2
9 of the License, or (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
14
15 See the GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 */
21
22
23 #ifdef WIN32
24 #define UINT8 WIN32API_UINT8
25 #define UINT16 WIN32API_UINT16
26 #define boolean WIN32API_boolean
27 #include <windows.h>
28 #undef UINT8
29 #undef UINT16
30 #undef boolean
31 #endif
32
33
34
35 #include "Game.h"
36 extern "C" {
37         #include "zlib.h"
38         #include "png.h"
39    #ifdef WIN32
40                 #define INT32 INT32_jpeg
41                 #include "jpeglib.h"
42                 #undef INT32
43         #else
44                 #include "jpeglib.h"
45         #endif
46 }
47
48 static bool load_image(const char * fname, TGAImageRec & tex);
49 static bool load_png(const char * fname, TGAImageRec & tex);
50 static bool load_jpg(const char * fname, TGAImageRec & tex);
51 bool save_image(const char * fname);
52 static bool save_png(const char * fname);
53
54
55 #include "openal_wrapper.h"
56
57 // ADDED GWC
58 #ifdef _MSC_VER
59 #pragma comment(lib, "opengl32.lib")
60 #pragma comment(lib, "glu32.lib")
61 #pragma comment(lib, "glaux.lib")
62 #endif
63
64 extern float multiplier;
65 extern float sps;
66 extern float realmultiplier;
67 extern int slomo;
68 extern bool cellophane;
69 extern float terraindetail;
70 extern float texdetail;
71
72 extern bool osx;
73 extern int numplayers;
74 extern bool freeze;
75 extern Person player[maxplayers];
76 extern bool stillloading;
77 extern int mainmenu;
78 /*extern*/ bool gameFocused;
79
80 extern float slomospeed;
81 extern float slomofreq;
82
83
84
85 #include <math.h>
86 #include <stdio.h>
87 #include <string.h>
88 #include <fstream>
89 #include <iostream>
90 #include "gamegl.h"
91 #include "MacCompatibility.h"
92 #include "Settings.h"
93
94 #ifdef WIN32
95 #include <shellapi.h>
96 #include "win-res/resource.h"
97 #endif
98
99 using namespace std;
100
101 SDL_Rect **resolutions = NULL;
102 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
103 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
104 static SDL_Rect rect_640_480  = { 0, 0, 640,  480 };
105 static SDL_Rect *hardcoded_resolutions[] = {
106     &rect_1024_768,
107     &rect_800_600,
108     &rect_640_480,
109     NULL
110 };
111
112 void DrawGL(Game & game);
113
114 Boolean SetUp (Game & game);
115 void DoUpdate (Game & game);
116
117 void CleanUp (void);
118
119 // statics/globals (internal only) ------------------------------------------
120
121 #ifdef _MSC_VER
122 #pragma warning(push)
123 #pragma warning(disable: 4273)
124 #endif
125
126 #define GL_FUNC(ret,fn,params,call,rt) \
127     extern "C" { \
128         static ret (GLAPIENTRY *p##fn) params = NULL; \
129         ret GLAPIENTRY fn params { rt p##fn call; } \
130     }
131 #include "glstubs.h"
132 #undef GL_FUNC
133
134 #ifdef _MSC_VER
135 #pragma warning(pop)
136 #endif
137
138 static bool lookup_glsym(const char *funcname, void **func)
139 {
140     *func = SDL_GL_GetProcAddress(funcname);
141     if (*func == NULL)
142     {
143         fprintf(stderr, "Failed to find OpenGL symbol \"%s\"\n", funcname);
144         return false;
145     }
146     return true;
147 }
148
149 static bool lookup_all_glsyms(void)
150 {
151     bool retval = true;
152     #define GL_FUNC(ret,fn,params,call,rt) \
153         if (!lookup_glsym(#fn, (void **) &p##fn)) retval = false;
154     #include "glstubs.h"
155     #undef GL_FUNC
156     return retval;
157 }
158
159 static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textures)
160 {
161     // no-op.
162 }
163
164 #ifdef MessageBox
165 #undef MessageBox
166 #endif
167 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
168
169 // Menu defs
170
171 int kContextWidth;
172 int kContextHeight;
173
174 Boolean gDone = false;
175
176 Game * pgame = 0;
177
178 #ifndef __MINGW32__
179 static int _argc = 0;
180 static char **_argv = NULL;
181 #endif
182
183 bool cmdline(const char *cmd)
184 {
185     for (int i = 1; i < _argc; i++)
186     {
187         char *arg = _argv[i];
188         while (*arg == '-')
189             arg++;
190         if (strcasecmp(arg, cmd) == 0)
191             return true;
192     }
193
194     return false;
195 }
196
197 //-----------------------------------------------------------------------------------------------------------------------
198
199 // OpenGL Drawing
200
201 static void sdlEventProc(const SDL_Event &e, Game &game)
202 {
203     switch(e.type)
204         {
205         case SDL_MOUSEMOTION:
206             game.deltah += e.motion.xrel;
207             game.deltav += e.motion.yrel;
208             return;
209
210         case SDL_KEYDOWN:
211             if ((e.key.keysym.sym == SDLK_g) &&
212                                 (e.key.keysym.mod & KMOD_CTRL) &&
213                                 !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
214                                 SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
215                         } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
216                                 SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
217             }
218             return;
219     }
220 }
221
222
223 // --------------------------------------------------------------------------
224
225 static Point gMidPoint;
226
227 Boolean SetUp (Game & game)
228 {
229         char string[10];
230
231         LOGFUNC;
232
233         osx = 0;
234         cellophane=0;
235         texdetail=4;
236         terraindetail=2;
237         slomospeed=0.25;
238         slomofreq=8012;
239         numplayers=1;
240         
241         DefaultSettings(game);
242
243     if (!SDL_WasInit(SDL_INIT_VIDEO))
244         if (SDL_Init(SDL_INIT_VIDEO) == -1)
245         {
246             fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
247             return false;
248         }
249         if(!LoadSettings(game)) {
250                 fprintf(stderr, "Failed to load config, creating default\n");
251                 SaveSettings(game);
252         }
253         if(kBitsPerPixel!=32&&kBitsPerPixel!=16){
254                 kBitsPerPixel=16;
255         }
256
257         if (SDL_GL_LoadLibrary(NULL) == -1)
258         {
259                 fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
260                 SDL_Quit();
261                 return false;
262         }
263
264         SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
265         if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
266                 res = hardcoded_resolutions;
267
268         // reverse list (it was sorted biggest to smallest by SDL)...
269         int count;
270         for (count = 0; res[count]; count++)
271         {
272                 if ((res[count]->w < 640) || (res[count]->h < 480))
273                         break;   // sane lower limit.
274         }
275
276         static SDL_Rect *resolutions_block = NULL;
277         resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
278         resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
279         if ((resolutions_block == NULL) || (resolutions == NULL))
280         {
281                 SDL_Quit();
282                 fprintf(stderr, "Out of memory!\n");
283                 return false;
284         }
285
286         resolutions[count--] = NULL;
287         for (int i = 0; count >= 0; i++, count--)
288         {
289                 memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
290                 resolutions[count] = &resolutions_block[count];
291         }
292
293         if (cmdline("showresolutions"))
294         {
295                 printf("Resolutions we think are okay:\n");
296                 for (int i = 0; resolutions[i]; i++)
297                         printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
298         }
299
300     Uint32 sdlflags = SDL_OPENGL;
301     if (!cmdline("windowed"))
302         sdlflags |= SDL_FULLSCREEN;
303
304     SDL_WM_SetCaption("Lugaru", "Lugaru");
305
306     SDL_ShowCursor(0);
307
308     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
309     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
310     
311     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
312     {
313         fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
314         fprintf(stderr, "forcing 640x480...\n");
315         kContextWidth = 640;
316         kContextHeight = 480;
317         if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
318         {
319             fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
320             fprintf(stderr, "forcing 640x480 windowed mode...\n");
321             sdlflags &= ~SDL_FULLSCREEN;
322             if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
323             {
324                 fprintf(stderr, "SDL_SetVideoMode() failed: %s\n", SDL_GetError());
325                 return false;
326             }
327         }
328     }
329
330     int dblbuf = 0;
331     if ((SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &dblbuf) == -1) || (!dblbuf))
332     {
333         fprintf(stderr, "Failed to get double buffered GL context!\n");
334         SDL_Quit();
335         return false;
336     }
337
338     if (!lookup_all_glsyms())
339     {
340         SDL_Quit();
341         return false;
342     }
343
344     if (!cmdline("nomousegrab"))
345         SDL_WM_GrabInput(SDL_GRAB_ON);
346
347
348         glClear( GL_COLOR_BUFFER_BIT );
349         swap_gl_buffers();
350
351         // clear all states
352         glDisable( GL_ALPHA_TEST);
353         glDisable( GL_BLEND);
354         glDisable( GL_DEPTH_TEST);
355         //      glDisable( GL_DITHER);
356         glDisable( GL_FOG);
357         glDisable( GL_LIGHTING);
358         glDisable( GL_LOGIC_OP);
359         glDisable( GL_TEXTURE_1D);
360         glDisable( GL_TEXTURE_2D);
361         glPixelTransferi( GL_MAP_COLOR, GL_FALSE);
362         glPixelTransferi( GL_RED_SCALE, 1);
363         glPixelTransferi( GL_RED_BIAS, 0);
364         glPixelTransferi( GL_GREEN_SCALE, 1);
365         glPixelTransferi( GL_GREEN_BIAS, 0);
366         glPixelTransferi( GL_BLUE_SCALE, 1);
367         glPixelTransferi( GL_BLUE_BIAS, 0);
368         glPixelTransferi( GL_ALPHA_SCALE, 1);
369         glPixelTransferi( GL_ALPHA_BIAS, 0);
370
371         // set initial rendering states
372         glShadeModel( GL_SMOOTH);
373         glClearDepth( 1.0f);
374         glDepthFunc( GL_LEQUAL);
375         glDepthMask( GL_TRUE);
376         //      glDepthRange( FRONT_CLIP, BACK_CLIP);
377         glEnable( GL_DEPTH_TEST);
378         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
379         glCullFace( GL_FRONT);
380         glEnable( GL_CULL_FACE);
381         glEnable( GL_LIGHTING);
382 //      glEnable( GL_LIGHT_MODEL_AMBIENT);
383         glEnable( GL_DITHER);
384         glEnable( GL_COLOR_MATERIAL);
385         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
386         glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
387         glAlphaFunc( GL_GREATER, 0.5f);
388
389         GLint width = kContextWidth;
390         GLint height = kContextHeight;
391         gMidPoint.h = width / 2;
392         gMidPoint.v = height / 2;
393         screenwidth=width;
394         screenheight=height;
395
396         game.newdetail=detail;
397         game.newscreenwidth=screenwidth;
398         game.newscreenheight=screenheight;
399
400         if ( CanInitStereo(stereomode) ) {
401                 InitStereo(stereomode);
402         } else {
403                 fprintf(stderr, "Failed to initialize stereo, disabling.\n");
404                 stereomode = stereoNone;
405         }
406
407         game.InitGame();
408
409         return true;
410 }
411
412
413 static void DoMouse(Game & game)
414 {
415
416         if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
417         {
418                 game.deltah *= usermousesensitivity;
419                 game.deltav *= usermousesensitivity;
420                 game.mousecoordh += game.deltah;
421                 game.mousecoordv += game.deltav;
422         if (game.mousecoordh < 0)
423             game.mousecoordh = 0;
424         else if (game.mousecoordh >= kContextWidth)
425             game.mousecoordh = kContextWidth - 1;
426         if (game.mousecoordv < 0)
427             game.mousecoordv = 0;
428         else if (game.mousecoordv >= kContextHeight)
429             game.mousecoordv = kContextHeight - 1;
430         }
431
432 }
433
434 void DoFrameRate (int update)
435 {       
436         static long frames = 0;
437
438         static AbsoluteTime time = {0,0};
439         static AbsoluteTime frametime = {0,0};
440         AbsoluteTime currTime = UpTime ();
441         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, frametime);
442
443         if (0 > deltaTime)      // if negative microseconds
444                 deltaTime /= -1000000.0;
445         else                            // else milliseconds
446                 deltaTime /= 1000.0;
447
448         multiplier=deltaTime;
449         if(multiplier<.001) multiplier=.001;
450         if(multiplier>10) multiplier=10;
451         if(update) frametime = currTime;        // reset for next time interval
452
453         deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
454
455         if (0 > deltaTime)      // if negative microseconds
456                 deltaTime /= -1000000.0;
457         else                            // else milliseconds
458                 deltaTime /= 1000.0;
459         frames++;
460         if (0.001 <= deltaTime) // has update interval passed
461         {
462                 if(update){
463                         time = currTime;        // reset for next time interval
464                         frames = 0;
465                 }
466         }
467 }
468
469
470 void DoUpdate (Game & game)
471 {
472         static float sps=200;
473         static int count;
474         static float oldmult;
475
476         DoFrameRate(1);
477         if(multiplier>.6)multiplier=.6;
478
479         game.fps=1/multiplier;
480
481         count = multiplier*sps;
482         if(count<2)count=2;
483
484         realmultiplier=multiplier;
485         multiplier*=gamespeed;
486         if(difficulty==1)multiplier*=.9;
487         if(difficulty==0)multiplier*=.8;
488
489         if(game.loading==4)multiplier*=.00001;
490         if(slomo&&!mainmenu)multiplier*=slomospeed;
491         oldmult=multiplier;
492         multiplier/=(float)count;
493
494         DoMouse(game);
495
496         game.TickOnce();
497
498         for(int i=0;i<count;i++)
499         {
500                 game.Tick();
501         }
502         multiplier=oldmult;
503
504         game.TickOnceAfter();
505 /* - Debug code to test how many channels were active on average per frame
506         static long frames = 0;
507
508         static AbsoluteTime start = {0,0};
509         AbsoluteTime currTime = UpTime ();
510         static int num_channels = 0;
511         
512         num_channels += OPENAL_GetChannelsPlaying();
513         double deltaTime = (float) AbsoluteDeltaToDuration (currTime, start);
514
515         if (0 > deltaTime)      // if negative microseconds
516                 deltaTime /= -1000000.0;
517         else                            // else milliseconds
518                 deltaTime /= 1000.0;
519
520         ++frames;
521
522         if (deltaTime >= 1)
523         {
524                 start = currTime;
525                 float avg_channels = (float)num_channels / (float)frames;
526
527                 ofstream opstream("log.txt",ios::app); 
528                 opstream << "Average frame count: ";
529                 opstream << frames;
530                 opstream << " frames - ";
531                 opstream << avg_channels;
532                 opstream << " per frame.\n";
533                 opstream.close();
534
535                 frames = 0;
536                 num_channels = 0;
537         }
538 */
539         game.DrawGL();
540 }
541
542 // --------------------------------------------------------------------------
543
544
545 void CleanUp (void)
546 {
547         LOGFUNC;
548
549     SDL_Quit();
550     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
551     #include "glstubs.h"
552     #undef GL_FUNC
553     // cheat here...static destructors are calling glDeleteTexture() after
554     //  the context is destroyed and libGL unloaded by SDL_Quit().
555     pglDeleteTextures = glDeleteTextures_doNothing;
556
557 }
558
559 // --------------------------------------------------------------------------
560
561 static bool IsFocused()
562 {
563     return ((SDL_GetAppState() & SDL_APPINPUTFOCUS) != 0);
564 }
565
566
567 static void launch_web_browser(const char *url)
568 {
569 #ifdef WIN32
570     ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
571
572 #elif (defined(__APPLE__) && defined(__MACH__))
573     const char *fmt = "open '%s'";
574     const size_t len = strlen(fmt) + strlen(url) + 16;
575     char *buf = new char[len];
576     snprintf(buf, len, fmt, url);
577     system(buf);
578     delete[] buf;
579
580 #elif PLATFORM_LINUX
581     const char *fmt = "PATH=$PATH:. xdg-open '%s'";
582     const size_t len = strlen(fmt) + strlen(url) + 16;
583     char *buf = new char[len];
584     snprintf(buf, len, fmt, url);
585     system(buf);
586     delete[] buf;
587 #endif
588 }
589
590
591 #ifndef WIN32
592 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
593 static char *findBinaryInPath(const char *bin, char *envr)
594 {
595     size_t alloc_size = 0;
596     char *exe = NULL;
597     char *start = envr;
598     char *ptr;
599
600     do
601     {
602         size_t size;
603         ptr = strchr(start, ':');  /* find next $PATH separator. */
604         if (ptr)
605             *ptr = '\0';
606
607         size = strlen(start) + strlen(bin) + 2;
608         if (size > alloc_size)
609         {
610             char *x = (char *) realloc(exe, size);
611             if (x == NULL)
612             {
613                 if (exe != NULL)
614                     free(exe);
615                 return(NULL);
616             } /* if */
617
618             alloc_size = size;
619             exe = x;
620         } /* if */
621
622         /* build full binary path... */
623         strcpy(exe, start);
624         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
625             strcat(exe, "/");
626         strcat(exe, bin);
627
628         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
629         {
630             strcpy(exe, start);  /* i'm lazy. piss off. */
631             return(exe);
632         } /* if */
633
634         start = ptr + 1;  /* start points to beginning of next element. */
635     } while (ptr != NULL);
636
637     if (exe != NULL)
638         free(exe);
639
640     return(NULL);  /* doesn't exist in path. */
641 } /* findBinaryInPath */
642
643
644 char *calcBaseDir(const char *argv0)
645 {
646     /* If there isn't a path on argv0, then look through the $PATH for it. */
647     char *retval;
648     char *envr;
649
650     const char *ptr = strrchr((char *)argv0, '/');
651     if (strchr(argv0, '/'))
652     {
653         retval = strdup(argv0);
654         if (retval)
655             *((char *) strrchr(retval, '/')) = '\0';
656         return(retval);
657     }
658
659     envr = getenv("PATH");
660     if (!envr) return NULL;
661     envr = strdup(envr);
662     if (!envr) return NULL;
663     retval = findBinaryInPath(argv0, envr);
664     free(envr);
665     return(retval);
666 }
667
668 static inline void chdirToAppPath(const char *argv0)
669 {
670     char *dir = calcBaseDir(argv0);
671     if (dir)
672     {
673         #if (defined(__APPLE__) && defined(__MACH__))
674         // Chop off /Contents/MacOS if it's at the end of the string, so we
675         //  land in the base of the app bundle.
676         const size_t len = strlen(dir);
677         const char *bundledirs = "/Contents/MacOS";
678         const size_t bundledirslen = strlen(bundledirs);
679         if (len > bundledirslen)
680         {
681             char *ptr = (dir + len) - bundledirslen;
682             if (strcasecmp(ptr, bundledirs) == 0)
683                 *ptr = '\0';
684         }
685         #endif
686         chdir(dir);
687         free(dir);
688     }
689 }
690 #endif
691
692
693 int main(int argc, char **argv)
694 {
695 #ifndef __MINGW32__
696     _argc = argc;
697     _argv = argv;
698 #endif
699
700     // !!! FIXME: we could use a Win32 API for this.  --ryan.
701 #ifndef WIN32
702     chdirToAppPath(argv[0]);
703 #endif
704
705         LOGFUNC;
706
707         try
708         {
709                 bool regnow = false;
710                 {
711                         Game game;
712                         pgame = &game;
713
714                         //ofstream os("error.txt");
715                         //os.close();
716                         //ofstream os("log.txt");
717                         //os.close();
718
719                         if (!SetUp (game))
720                 return 42;
721
722                         while (!gDone&&!game.quit&&(!game.tryquit))
723                         {
724                                 if (IsFocused())
725                                 {
726                                         gameFocused = true;
727
728                                         // check windows messages
729                         
730                                         game.deltah = 0;
731                                         game.deltav = 0;
732                                         SDL_Event e;
733                                         if(!game.isWaiting()) {
734                                                 // message pump
735                                                 while( SDL_PollEvent( &e ) )
736                                                 {
737                                                         if( e.type == SDL_QUIT )
738                                                         {
739                                                                 gDone=true;
740                                                                 break;
741                                                         }
742                                                         sdlEventProc(e, game);
743                                                 }
744                                         }
745
746                                         // game
747                                         DoUpdate(game);
748                                 }
749                                 else
750                                 {
751                                         if (gameFocused)
752                                         {
753                                                 // allow game chance to pause
754                                                 gameFocused = false;
755                                                 DoUpdate(game);
756                                         }
757
758                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
759                                         SDL_ActiveEvent evt;
760                                         SDL_WaitEvent((SDL_Event*)&evt);
761                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
762                                                 gameFocused = true;
763                                         else if (evt.type == SDL_QUIT)
764                                                 gDone = true;
765                                 }
766                         }
767
768                         regnow = game.registernow;
769                 }
770                 pgame = 0;
771
772                 CleanUp ();
773
774                 return 0;
775         }
776         catch (const std::exception& error)
777         {
778                 CleanUp();
779
780                 std::string e = "Caught exception: ";
781                 e += error.what();
782
783                 LOG(e);
784
785                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
786         }
787
788         CleanUp();
789
790         return -1;
791 }
792
793
794
795 // --------------------------------------------------------------------------
796
797 extern int channels[100];
798 extern OPENAL_SAMPLE * samp[100];
799 extern OPENAL_STREAM * strm[20];
800
801 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
802 {
803         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
804         if (currSample && currSample == samp[chan])
805         {
806                 if (OPENAL_GetPaused(channels[chan]))
807                 {
808                         OPENAL_StopSound(channels[chan]);
809                         channels[chan] = OPENAL_FREE;
810                 }
811                 else if (OPENAL_IsPlaying(channels[chan]))
812                 {
813                         int loop_mode = OPENAL_GetLoopMode(channels[chan]);
814                         if (loop_mode & OPENAL_LOOP_OFF)
815                         {
816                                 channels[chan] = OPENAL_FREE;
817                         }
818                 }
819         }
820         else
821         {
822                 channels[chan] = OPENAL_FREE;
823         }
824
825         channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
826         if (channels[chan] < 0)
827         {
828                 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
829         }
830 }
831
832 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
833 {
834         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
835         if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
836         {
837                         OPENAL_StopSound(channels[chan]);
838                         OPENAL_Stream_Stop(sptr);
839         }
840         else
841         {
842                 OPENAL_Stream_Stop(sptr);
843                 channels[chan] = OPENAL_FREE;
844         }
845
846         channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
847         if (channels[chan] < 0)
848         {
849                 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
850         }
851 }
852
853
854 bool LoadImage(const char * fname, TGAImageRec & tex)
855 {
856         if ( tex.data == NULL )
857                 return false;
858         else
859                 return load_image(fname, tex);
860 }
861
862 void ScreenShot(const char * fname)
863 {
864         
865 }
866
867
868
869 static bool load_image(const char *file_name, TGAImageRec &tex)
870 {
871     const char *ptr = strrchr((char *)file_name, '.');
872     if (ptr)
873     {
874         if (strcasecmp(ptr+1, "png") == 0)
875             return load_png(file_name, tex);
876         else if (strcasecmp(ptr+1, "jpg") == 0)
877             return load_jpg(file_name, tex);
878     }
879
880     STUBBED("Unsupported image type");
881     return false;
882 }
883
884
885 struct my_error_mgr {
886   struct jpeg_error_mgr pub;    /* "public" fields */
887   jmp_buf setjmp_buffer;        /* for return to caller */
888 };
889 typedef struct my_error_mgr * my_error_ptr;
890
891
892 static void my_error_exit(j_common_ptr cinfo)
893 {
894         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
895         longjmp(err->setjmp_buffer, 1);
896 }
897
898 /* stolen from public domain example.c code in libjpg distribution. */
899 static bool load_jpg(const char *file_name, TGAImageRec &tex)
900 {
901     struct jpeg_decompress_struct cinfo;
902     struct my_error_mgr jerr;
903     JSAMPROW buffer[1];         /* Output row buffer */
904     int row_stride;             /* physical row width in output buffer */
905     FILE *infile = fopen(file_name, "rb");
906
907     if (infile == NULL)
908         return false;
909
910     cinfo.err = jpeg_std_error(&jerr.pub);
911     jerr.pub.error_exit = my_error_exit;
912     if (setjmp(jerr.setjmp_buffer)) {
913         jpeg_destroy_decompress(&cinfo);
914         fclose(infile);
915         return false;
916     }
917
918     jpeg_create_decompress(&cinfo);
919     jpeg_stdio_src(&cinfo, infile);
920     (void) jpeg_read_header(&cinfo, TRUE);
921
922     cinfo.out_color_space = JCS_RGB;
923     cinfo.quantize_colors = 0;
924     (void) jpeg_calc_output_dimensions(&cinfo);
925     (void) jpeg_start_decompress(&cinfo);
926
927     row_stride = cinfo.output_width * cinfo.output_components;
928     tex.sizeX = cinfo.output_width;
929     tex.sizeY = cinfo.output_height;
930     tex.bpp = 24;
931
932     while (cinfo.output_scanline < cinfo.output_height) {
933         buffer[0] = (JSAMPROW)(char *)tex.data +
934                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
935         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
936     }
937
938     (void) jpeg_finish_decompress(&cinfo);
939     jpeg_destroy_decompress(&cinfo);
940     fclose(infile);
941
942     return true;
943 }
944
945
946 /* stolen from public domain example.c code in libpng distribution. */
947 static bool load_png(const char *file_name, TGAImageRec &tex)
948 {
949     bool hasalpha = false;
950     png_structp png_ptr = NULL;
951     png_infop info_ptr = NULL;
952     png_uint_32 width, height;
953     int bit_depth, color_type, interlace_type;
954     png_byte **rows = NULL;
955     bool retval = false;
956     png_byte **row_pointers = NULL;
957     FILE *fp = fopen(file_name, "rb");
958
959     if (fp == NULL)
960         return(NULL);
961
962     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
963     if (png_ptr == NULL)
964         goto png_done;
965
966     info_ptr = png_create_info_struct(png_ptr);
967     if (info_ptr == NULL)
968         goto png_done;
969
970     if (setjmp(png_jmpbuf(png_ptr)))
971         goto png_done;
972
973     png_init_io(png_ptr, fp);
974     png_read_png(png_ptr, info_ptr,
975                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
976                  NULL);
977     png_get_IHDR(png_ptr, info_ptr, &width, &height,
978                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
979
980     if (bit_depth != 8)  // transform SHOULD handle this...
981         goto png_done;
982
983     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
984         goto png_done;
985
986     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
987         goto png_done;
988
989     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
990     row_pointers = png_get_rows(png_ptr, info_ptr);
991     if (!row_pointers)
992         goto png_done;
993
994     if (!hasalpha)
995     {
996         png_byte *dst = tex.data;
997         for (int i = height-1; i >= 0; i--)
998         {
999             png_byte *src = row_pointers[i];
1000             for (int j = 0; j < width; j++)
1001             {
1002                 dst[0] = src[0];
1003                 dst[1] = src[1];
1004                 dst[2] = src[2];
1005                 dst[3] = 0xFF;
1006                 src += 3;
1007                 dst += 4;
1008             }
1009         }
1010     }
1011
1012     else
1013     {
1014         png_byte *dst = tex.data;
1015         int pitch = width * 4;
1016         for (int i = height-1; i >= 0; i--, dst += pitch)
1017             memcpy(dst, row_pointers[i], pitch);
1018     }
1019
1020     tex.sizeX = width;
1021     tex.sizeY = height;
1022     tex.bpp = 32;
1023     retval = true;
1024
1025 png_done:
1026     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1027     if (fp)
1028         fclose(fp);
1029     return (retval);
1030 }
1031
1032
1033 bool save_image(const char *file_name)
1034 {
1035     const char *ptr = strrchr((char *)file_name, '.');
1036     if (ptr)
1037     {
1038         if (strcasecmp(ptr+1, "png") == 0)
1039             return save_png(file_name);
1040     }
1041
1042     STUBBED("Unsupported image type");
1043     return false;
1044 }
1045
1046
1047 static bool save_png(const char *file_name)
1048 {
1049     FILE *fp = NULL;
1050     png_structp png_ptr = NULL;
1051     png_infop info_ptr = NULL;
1052     bool retval = false;
1053
1054     fp = fopen(file_name, "wb");
1055     if (fp == NULL)
1056         return false;
1057
1058     png_bytep *row_pointers = new png_bytep[kContextHeight];
1059     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1060     if ((!screenshot) || (!row_pointers))
1061         goto save_png_done;
1062
1063     glGetError();
1064     glReadPixels(0, 0, kContextWidth, kContextHeight,
1065                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1066     if (glGetError() != GL_NO_ERROR)
1067         goto save_png_done;
1068
1069     for (int i = 0; i < kContextHeight; i++)
1070         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1071
1072     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1073     if (png_ptr == NULL)
1074         goto save_png_done;
1075
1076     info_ptr = png_create_info_struct(png_ptr);
1077     if (info_ptr == NULL)
1078         goto save_png_done;
1079
1080     if (setjmp(png_jmpbuf(png_ptr)))
1081         goto save_png_done;
1082
1083     png_init_io(png_ptr, fp);
1084
1085     if (setjmp(png_jmpbuf(png_ptr)))
1086         goto save_png_done;
1087
1088     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1089                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1090                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1091
1092     png_write_info(png_ptr, info_ptr);
1093
1094     if (setjmp(png_jmpbuf(png_ptr)))
1095         goto save_png_done;
1096
1097         png_write_image(png_ptr, row_pointers);
1098
1099         if (setjmp(png_jmpbuf(png_ptr)))
1100         goto save_png_done;
1101
1102     png_write_end(png_ptr, NULL);
1103     retval = true;
1104
1105 save_png_done:
1106     png_destroy_write_struct(&png_ptr, &info_ptr);
1107     delete[] screenshot;
1108     delete[] row_pointers;
1109     if (fp)
1110         fclose(fp);
1111     if (!retval)
1112         unlink(ConvertFileName(file_name));
1113     return retval;
1114 }
1115
1116
1117