]> git.jsancho.org Git - lugaru.git/blob - Source/OpenGL_Windows.cpp
c0f061cf2a56a89dc545d991894c26ea24456901
[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
568 #ifndef WIN32
569 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
570 static char *findBinaryInPath(const char *bin, char *envr)
571 {
572     size_t alloc_size = 0;
573     char *exe = NULL;
574     char *start = envr;
575     char *ptr;
576
577     do
578     {
579         size_t size;
580         ptr = strchr(start, ':');  /* find next $PATH separator. */
581         if (ptr)
582             *ptr = '\0';
583
584         size = strlen(start) + strlen(bin) + 2;
585         if (size > alloc_size)
586         {
587             char *x = (char *) realloc(exe, size);
588             if (x == NULL)
589             {
590                 if (exe != NULL)
591                     free(exe);
592                 return(NULL);
593             } /* if */
594
595             alloc_size = size;
596             exe = x;
597         } /* if */
598
599         /* build full binary path... */
600         strcpy(exe, start);
601         if ((exe[0] == '\0') || (exe[strlen(exe) - 1] != '/'))
602             strcat(exe, "/");
603         strcat(exe, bin);
604
605         if (access(exe, X_OK) == 0)  /* Exists as executable? We're done. */
606         {
607             strcpy(exe, start);  /* i'm lazy. piss off. */
608             return(exe);
609         } /* if */
610
611         start = ptr + 1;  /* start points to beginning of next element. */
612     } while (ptr != NULL);
613
614     if (exe != NULL)
615         free(exe);
616
617     return(NULL);  /* doesn't exist in path. */
618 } /* findBinaryInPath */
619
620
621 char *calcBaseDir(const char *argv0)
622 {
623     /* If there isn't a path on argv0, then look through the $PATH for it. */
624     char *retval;
625     char *envr;
626
627     const char *ptr = strrchr((char *)argv0, '/');
628     if (strchr(argv0, '/'))
629     {
630         retval = strdup(argv0);
631         if (retval)
632             *((char *) strrchr(retval, '/')) = '\0';
633         return(retval);
634     }
635
636     envr = getenv("PATH");
637     if (!envr) return NULL;
638     envr = strdup(envr);
639     if (!envr) return NULL;
640     retval = findBinaryInPath(argv0, envr);
641     free(envr);
642     return(retval);
643 }
644
645 static inline void chdirToAppPath(const char *argv0)
646 {
647     char *dir = calcBaseDir(argv0);
648     if (dir)
649     {
650         #if (defined(__APPLE__) && defined(__MACH__))
651         // Chop off /Contents/MacOS if it's at the end of the string, so we
652         //  land in the base of the app bundle.
653         const size_t len = strlen(dir);
654         const char *bundledirs = "/Contents/MacOS";
655         const size_t bundledirslen = strlen(bundledirs);
656         if (len > bundledirslen)
657         {
658             char *ptr = (dir + len) - bundledirslen;
659             if (strcasecmp(ptr, bundledirs) == 0)
660                 *ptr = '\0';
661         }
662         #endif
663         chdir(dir);
664         free(dir);
665     }
666 }
667 #endif
668
669
670 int main(int argc, char **argv)
671 {
672 #ifndef __MINGW32__
673     _argc = argc;
674     _argv = argv;
675 #endif
676
677     // !!! FIXME: we could use a Win32 API for this.  --ryan.
678 #ifndef WIN32
679     chdirToAppPath(argv[0]);
680 #endif
681
682         LOGFUNC;
683
684         try
685         {
686                 bool regnow = false;
687                 {
688                         Game game;
689                         pgame = &game;
690
691                         //ofstream os("error.txt");
692                         //os.close();
693                         //ofstream os("log.txt");
694                         //os.close();
695
696                         if (!SetUp (game))
697                 return 42;
698
699                         while (!gDone&&!game.quit&&(!game.tryquit))
700                         {
701                                 if (IsFocused())
702                                 {
703                                         gameFocused = true;
704
705                                         // check windows messages
706                         
707                                         game.deltah = 0;
708                                         game.deltav = 0;
709                                         SDL_Event e;
710                                         if(!game.isWaiting()) {
711                                                 // message pump
712                                                 while( SDL_PollEvent( &e ) )
713                                                 {
714                                                         if( e.type == SDL_QUIT )
715                                                         {
716                                                                 gDone=true;
717                                                                 break;
718                                                         }
719                                                         sdlEventProc(e, game);
720                                                 }
721                                         }
722
723                                         // game
724                                         DoUpdate(game);
725                                 }
726                                 else
727                                 {
728                                         if (gameFocused)
729                                         {
730                                                 // allow game chance to pause
731                                                 gameFocused = false;
732                                                 DoUpdate(game);
733                                         }
734
735                                         // game is not in focus, give CPU time to other apps by waiting for messages instead of 'peeking'
736                                         SDL_ActiveEvent evt;
737                                         SDL_WaitEvent((SDL_Event*)&evt);
738                                         if (evt.type == SDL_ACTIVEEVENT && evt.gain == 1)
739                                                 gameFocused = true;
740                                         else if (evt.type == SDL_QUIT)
741                                                 gDone = true;
742                                 }
743                         }
744
745                         regnow = game.registernow;
746                 }
747                 pgame = 0;
748
749                 CleanUp ();
750
751                 return 0;
752         }
753         catch (const std::exception& error)
754         {
755                 CleanUp();
756
757                 std::string e = "Caught exception: ";
758                 e += error.what();
759
760                 LOG(e);
761
762                 MessageBox(g_windowHandle, error.what(), "ERROR", MB_OK | MB_ICONEXCLAMATION);
763         }
764
765         CleanUp();
766
767         return -1;
768 }
769
770
771
772 // --------------------------------------------------------------------------
773
774 extern int channels[100];
775 extern OPENAL_SAMPLE * samp[100];
776 extern OPENAL_STREAM * strm[20];
777
778 extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
779 {
780         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
781         if (currSample && currSample == samp[chan])
782         {
783                 if (OPENAL_GetPaused(channels[chan]))
784                 {
785                         OPENAL_StopSound(channels[chan]);
786                         channels[chan] = OPENAL_FREE;
787                 }
788                 else if (OPENAL_IsPlaying(channels[chan]))
789                 {
790                         int loop_mode = OPENAL_GetLoopMode(channels[chan]);
791                         if (loop_mode & OPENAL_LOOP_OFF)
792                         {
793                                 channels[chan] = OPENAL_FREE;
794                         }
795                 }
796         }
797         else
798         {
799                 channels[chan] = OPENAL_FREE;
800         }
801
802         channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
803         if (channels[chan] < 0)
804         {
805                 channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
806         }
807 }
808
809 extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
810 {
811         const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
812         if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
813         {
814                         OPENAL_StopSound(channels[chan]);
815                         OPENAL_Stream_Stop(sptr);
816         }
817         else
818         {
819                 OPENAL_Stream_Stop(sptr);
820                 channels[chan] = OPENAL_FREE;
821         }
822
823         channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
824         if (channels[chan] < 0)
825         {
826                 channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
827         }
828 }
829
830
831 bool LoadImage(const char * fname, TGAImageRec & tex)
832 {
833         if ( tex.data == NULL )
834                 return false;
835         else
836                 return load_image(fname, tex);
837 }
838
839 void ScreenShot(const char * fname)
840 {
841         
842 }
843
844
845
846 static bool load_image(const char *file_name, TGAImageRec &tex)
847 {
848     const char *ptr = strrchr((char *)file_name, '.');
849     if (ptr)
850     {
851         if (strcasecmp(ptr+1, "png") == 0)
852             return load_png(file_name, tex);
853         else if (strcasecmp(ptr+1, "jpg") == 0)
854             return load_jpg(file_name, tex);
855     }
856
857     STUBBED("Unsupported image type");
858     return false;
859 }
860
861
862 struct my_error_mgr {
863   struct jpeg_error_mgr pub;    /* "public" fields */
864   jmp_buf setjmp_buffer;        /* for return to caller */
865 };
866 typedef struct my_error_mgr * my_error_ptr;
867
868
869 static void my_error_exit(j_common_ptr cinfo)
870 {
871         struct my_error_mgr *err = (struct my_error_mgr *)cinfo->err;
872         longjmp(err->setjmp_buffer, 1);
873 }
874
875 /* stolen from public domain example.c code in libjpg distribution. */
876 static bool load_jpg(const char *file_name, TGAImageRec &tex)
877 {
878     struct jpeg_decompress_struct cinfo;
879     struct my_error_mgr jerr;
880     JSAMPROW buffer[1];         /* Output row buffer */
881     int row_stride;             /* physical row width in output buffer */
882     FILE *infile = fopen(file_name, "rb");
883
884     if (infile == NULL)
885         return false;
886
887     cinfo.err = jpeg_std_error(&jerr.pub);
888     jerr.pub.error_exit = my_error_exit;
889     if (setjmp(jerr.setjmp_buffer)) {
890         jpeg_destroy_decompress(&cinfo);
891         fclose(infile);
892         return false;
893     }
894
895     jpeg_create_decompress(&cinfo);
896     jpeg_stdio_src(&cinfo, infile);
897     (void) jpeg_read_header(&cinfo, TRUE);
898
899     cinfo.out_color_space = JCS_RGB;
900     cinfo.quantize_colors = 0;
901     (void) jpeg_calc_output_dimensions(&cinfo);
902     (void) jpeg_start_decompress(&cinfo);
903
904     row_stride = cinfo.output_width * cinfo.output_components;
905     tex.sizeX = cinfo.output_width;
906     tex.sizeY = cinfo.output_height;
907     tex.bpp = 24;
908
909     while (cinfo.output_scanline < cinfo.output_height) {
910         buffer[0] = (JSAMPROW)(char *)tex.data +
911                         ((cinfo.output_height-1) - cinfo.output_scanline) * row_stride;
912         (void) jpeg_read_scanlines(&cinfo, buffer, 1);
913     }
914
915     (void) jpeg_finish_decompress(&cinfo);
916     jpeg_destroy_decompress(&cinfo);
917     fclose(infile);
918
919     return true;
920 }
921
922
923 /* stolen from public domain example.c code in libpng distribution. */
924 static bool load_png(const char *file_name, TGAImageRec &tex)
925 {
926     bool hasalpha = false;
927     png_structp png_ptr = NULL;
928     png_infop info_ptr = NULL;
929     png_uint_32 width, height;
930     int bit_depth, color_type, interlace_type;
931     png_byte **rows = NULL;
932     bool retval = false;
933     png_byte **row_pointers = NULL;
934     FILE *fp = fopen(file_name, "rb");
935
936     if (fp == NULL)
937         return(NULL);
938
939     png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
940     if (png_ptr == NULL)
941         goto png_done;
942
943     info_ptr = png_create_info_struct(png_ptr);
944     if (info_ptr == NULL)
945         goto png_done;
946
947     if (setjmp(png_jmpbuf(png_ptr)))
948         goto png_done;
949
950     png_init_io(png_ptr, fp);
951     png_read_png(png_ptr, info_ptr,
952                  PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_PACKING,
953                  NULL);
954     png_get_IHDR(png_ptr, info_ptr, &width, &height,
955                  &bit_depth, &color_type, &interlace_type, NULL, NULL);
956
957     if (bit_depth != 8)  // transform SHOULD handle this...
958         goto png_done;
959
960     if (color_type & PNG_COLOR_MASK_PALETTE)  // !!! FIXME?
961         goto png_done;
962
963     if ((color_type & PNG_COLOR_MASK_COLOR) == 0)  // !!! FIXME?
964         goto png_done;
965
966     hasalpha = ((color_type & PNG_COLOR_MASK_ALPHA) != 0);
967     row_pointers = png_get_rows(png_ptr, info_ptr);
968     if (!row_pointers)
969         goto png_done;
970
971     if (!hasalpha)
972     {
973         png_byte *dst = tex.data;
974         for (int i = height-1; i >= 0; i--)
975         {
976             png_byte *src = row_pointers[i];
977             for (int j = 0; j < width; j++)
978             {
979                 dst[0] = src[0];
980                 dst[1] = src[1];
981                 dst[2] = src[2];
982                 dst[3] = 0xFF;
983                 src += 3;
984                 dst += 4;
985             }
986         }
987     }
988
989     else
990     {
991         png_byte *dst = tex.data;
992         int pitch = width * 4;
993         for (int i = height-1; i >= 0; i--, dst += pitch)
994             memcpy(dst, row_pointers[i], pitch);
995     }
996
997     tex.sizeX = width;
998     tex.sizeY = height;
999     tex.bpp = 32;
1000     retval = true;
1001
1002 png_done:
1003     png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
1004     if (fp)
1005         fclose(fp);
1006     return (retval);
1007 }
1008
1009
1010 bool save_image(const char *file_name)
1011 {
1012     const char *ptr = strrchr((char *)file_name, '.');
1013     if (ptr)
1014     {
1015         if (strcasecmp(ptr+1, "png") == 0)
1016             return save_png(file_name);
1017     }
1018
1019     STUBBED("Unsupported image type");
1020     return false;
1021 }
1022
1023
1024 static bool save_png(const char *file_name)
1025 {
1026     FILE *fp = NULL;
1027     png_structp png_ptr = NULL;
1028     png_infop info_ptr = NULL;
1029     bool retval = false;
1030
1031     fp = fopen(file_name, "wb");
1032     if (fp == NULL)
1033         return false;
1034
1035     png_bytep *row_pointers = new png_bytep[kContextHeight];
1036     png_bytep screenshot = new png_byte[kContextWidth * kContextHeight * 3];
1037     if ((!screenshot) || (!row_pointers))
1038         goto save_png_done;
1039
1040     glGetError();
1041     glReadPixels(0, 0, kContextWidth, kContextHeight,
1042                  GL_RGB, GL_UNSIGNED_BYTE, screenshot);
1043     if (glGetError() != GL_NO_ERROR)
1044         goto save_png_done;
1045
1046     for (int i = 0; i < kContextHeight; i++)
1047         row_pointers[i] = screenshot + ((kContextWidth * ((kContextHeight-1) - i)) * 3);
1048
1049     png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1050     if (png_ptr == NULL)
1051         goto save_png_done;
1052
1053     info_ptr = png_create_info_struct(png_ptr);
1054     if (info_ptr == NULL)
1055         goto save_png_done;
1056
1057     if (setjmp(png_jmpbuf(png_ptr)))
1058         goto save_png_done;
1059
1060     png_init_io(png_ptr, fp);
1061
1062     if (setjmp(png_jmpbuf(png_ptr)))
1063         goto save_png_done;
1064
1065     png_set_IHDR(png_ptr, info_ptr, kContextWidth, kContextHeight,
1066                  8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
1067                  PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
1068
1069     png_write_info(png_ptr, info_ptr);
1070
1071     if (setjmp(png_jmpbuf(png_ptr)))
1072         goto save_png_done;
1073
1074         png_write_image(png_ptr, row_pointers);
1075
1076         if (setjmp(png_jmpbuf(png_ptr)))
1077         goto save_png_done;
1078
1079     png_write_end(png_ptr, NULL);
1080     retval = true;
1081
1082 save_png_done:
1083     png_destroy_write_struct(&png_ptr, &info_ptr);
1084     delete[] screenshot;
1085     delete[] row_pointers;
1086     if (fp)
1087         fclose(fp);
1088     if (!retval)
1089         unlink(ConvertFileName(file_name));
1090     return retval;
1091 }
1092
1093
1094