]> git.jsancho.org Git - lugaru.git/blob - Source/openal_wrapper.cpp
Drop MinMaxDistance
[lugaru.git] / Source / openal_wrapper.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 #if USE_OPENAL
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include "openal_wrapper.h"
29
30 // NOTE:
31 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
32 //  one...so we just need to flip the sign on the Z axis when appropriate.
33
34 #define DYNAMIC_LOAD_OPENAL 0
35
36 #if DYNAMIC_LOAD_OPENAL
37
38 #include <dlfcn.h>
39
40 #define AL_FUNC(t,ret,fn,params,call,rt) \
41     extern "C" { \
42         static ret ALAPIENTRY (*p##fn) params = NULL; \
43         ret ALAPIENTRY fn params { rt p##fn call; } \
44     }
45 #include "alstubs.h"
46 #undef AL_FUNC
47
48 static void *aldlhandle = NULL;
49
50 static bool lookup_alsym(const char *funcname, void **func, const char *libname)
51 {
52     if (!aldlhandle)
53         return false;
54
55     *func = dlsym(aldlhandle, funcname);
56     if (*func == NULL)
57     {
58         fprintf(stderr, "Failed to find OpenAL symbol \"%s\" in \"%s\"\n",
59                  funcname, libname);
60         return false;
61     }
62     return true;
63 }
64
65 static void unload_alsyms(void)
66 {
67     #define AL_FUNC(t,ret,fn,params,call,rt) p##fn = NULL;
68     #include "alstubs.h"
69     #undef AL_FUNC
70     if (aldlhandle)
71     {
72         dlclose(aldlhandle);
73         aldlhandle = NULL;
74     }
75 }
76
77 static bool lookup_all_alsyms(const char *libname)
78 {
79     if (!aldlhandle)
80     {
81         if ( (aldlhandle = dlopen(libname, RTLD_GLOBAL | RTLD_NOW)) == NULL )
82             return false;
83     }
84
85     bool retval = true;
86     #define AL_FUNC(t,ret,fn,params,call,rt) \
87         if (!lookup_alsym(#fn, (void **) &p##fn, libname)) retval = false;
88     #include "alstubs.h"
89     #undef AL_FUNC
90
91     if (!retval)
92         unload_alsyms();
93
94     return retval;
95 }
96 #else
97 #define lookup_all_alsyms(x) (true)
98 #define unload_alsyms()
99 #endif
100
101 typedef struct
102 {
103     ALuint sid;
104     OPENAL_SAMPLE *sample;
105     bool startpaused;
106     float position[3];
107 } OPENAL_Channels;
108
109 typedef struct OPENAL_SAMPLE
110 {
111     char *name;
112     ALuint bid;  // buffer id.
113     int mode;
114     int is2d;
115 } OPENAL_SAMPLE;
116
117 typedef struct OPENAL_STREAM
118 {
119     char *name;
120     ALuint bid;  // buffer id.
121     int mode;
122     int is2d;
123 } OPENAL_STREAM;
124
125 static size_t num_channels = 0;
126 static OPENAL_Channels *channels = NULL;
127 static bool initialized = false;
128 static float listener_position[3];
129
130 static void set_channel_position(const int channel, const float x,
131                                  const float y, const float z)
132 {
133     OPENAL_Channels *chan = &channels[channel];
134
135     chan->position[0] = x;
136     chan->position[1] = y;
137     chan->position[2] = z;
138
139     OPENAL_SAMPLE *sptr = chan->sample;
140     if (sptr == NULL)
141         return;
142
143     const ALuint sid = chan->sid;
144     const bool no_attenuate = sptr->is2d;
145
146     if (no_attenuate)
147     {
148         alSourcei(sid, AL_SOURCE_RELATIVE, AL_TRUE);
149         alSource3f(sid, AL_POSITION, 0.0f, 0.0f, 0.0f);
150     }
151     else
152     {
153         alSourcei(sid, AL_SOURCE_RELATIVE, AL_FALSE);
154         alSource3f(sid, AL_POSITION, x, y, z);
155     }
156 }
157
158
159 AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz)
160 {
161     if (!initialized) return;
162     if (pos != NULL)
163     {
164         alListener3f(AL_POSITION, pos[0], pos[1], -pos[2]);
165         listener_position[0] = pos[0];
166         listener_position[1] = pos[1];
167         listener_position[2] = -pos[2];
168     }
169
170     ALfloat vec[6] = { fx, fy, -fz, tz, ty, -tz };
171     alListenerfv(AL_ORIENTATION, vec);
172
173     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
174
175     // adjust existing positions...
176     for (int i = 0; i < num_channels; i++)
177     {
178         const float *p = channels[i].position;
179         set_channel_position(i, p[0], p[1], p[2]);
180     }
181 }
182
183 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel)
184 {
185     if (!initialized) return false;
186     if ((channel < 0) || (channel >= num_channels)) return false;
187
188     if (pos != NULL)
189         set_channel_position(channel, pos[0], pos[1], -pos[2]);
190
191     // we ignore velocity, since doppler's broken in the Linux AL at the moment...
192
193     return true;
194 }
195
196 AL_API void OPENAL_3D_SetDopplerFactor(float scale)
197 {
198     if (!initialized) return;
199     // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
200 }
201
202 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
203 {
204     if (initialized) return false;
205     if (maxsoftwarechannels == 0) return false;
206
207     if (flags != 0)  // unsupported.
208         return false;
209
210     if (!lookup_all_alsyms("./openal.so"))  // !!! FIXME: linux specific lib name
211     {
212         if (!lookup_all_alsyms("openal.so.1"))  // !!! FIXME: linux specific lib name
213         {
214             if (!lookup_all_alsyms("openal.so"))  // !!! FIXME: linux specific lib name
215                 return false;
216         }
217     }
218
219     ALCdevice *dev = alcOpenDevice(NULL);
220     if (!dev)
221         return false;
222
223     ALint caps[] = { ALC_FREQUENCY, mixrate, 0 };
224     ALCcontext *ctx = alcCreateContext(dev, caps);
225     if (!ctx)
226     {
227         alcCloseDevice(dev);
228         return false;
229     }
230
231     alcMakeContextCurrent(ctx);
232     alcProcessContext(ctx);
233
234     bool cmdline(const char *cmd);
235     if (cmdline("openalinfo"))
236     {
237         printf("AL_VENDOR: %s\n", (char *) alGetString(AL_VENDOR));
238         printf("AL_RENDERER: %s\n", (char *) alGetString(AL_RENDERER));
239         printf("AL_VERSION: %s\n", (char *) alGetString(AL_VERSION));
240         printf("AL_EXTENSIONS: %s\n", (char *) alGetString(AL_EXTENSIONS));
241     }
242
243     num_channels = maxsoftwarechannels;
244     channels = new OPENAL_Channels[maxsoftwarechannels];
245     memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
246     for (int i = 0; i < num_channels; i++)
247         alGenSources(1, &channels[i].sid);  // !!! FIXME: verify this didn't fail!
248
249     initialized = true;
250     return true;
251 }
252
253 AL_API void OPENAL_Close()
254 {
255     if (!initialized) return;
256
257     ALCcontext *ctx = alcGetCurrentContext();
258     if (ctx)
259     {
260         for (int i = 0; i < num_channels; i++)
261         {
262             alSourceStop(channels[i].sid);
263             alSourcei(channels[i].sid, AL_BUFFER, 0);
264             alDeleteSources(1, &channels[i].sid);
265         }
266         ALCdevice *dev = alcGetContextsDevice(ctx);
267         alcMakeContextCurrent(NULL);
268         alcSuspendContext(ctx);
269         alcDestroyContext(ctx);
270         alcCloseDevice(dev);
271     }
272
273     num_channels = 0;
274     delete[] channels;
275     channels = NULL;
276
277     unload_alsyms();
278     initialized = false;
279 }
280
281 AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
282 {
283     if (!initialized) return NULL;
284     if ((channel < 0) || (channel >= num_channels)) return NULL;
285     return channels[channel].sample;
286 }
287
288 AL_API signed char OPENAL_GetPaused(int channel)
289 {
290     if (!initialized) return false;
291     if ((channel < 0) || (channel >= num_channels)) return false;
292     if (channels[channel].startpaused)
293         return(true);
294
295     ALint state = 0;
296     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
297     return((state == AL_PAUSED) ? true : false);
298 }
299
300 AL_API unsigned int OPENAL_GetLoopMode(int channel)
301 {
302     if (!initialized) return 0;
303     if ((channel < 0) || (channel >= num_channels)) return 0;
304     ALint loop = 0;
305     alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
306     if (loop)
307         return(OPENAL_LOOP_NORMAL);
308     return OPENAL_LOOP_OFF;
309 }
310
311 AL_API signed char OPENAL_IsPlaying(int channel)
312 {
313     if (!initialized) return false;
314     if ((channel < 0) || (channel >= num_channels)) return false;
315     ALint state = 0;
316     alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
317     return((state == AL_PLAYING) ? true : false);
318 }
319
320 AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
321 {
322     if (!initialized) return -1;
323     if (sptr == NULL) return -1;
324     if (dsp != NULL) return -1;
325     if (channel == OPENAL_FREE)
326     {
327         for (int i = 0; i < num_channels; i++)
328         {
329             ALint state = 0;
330             alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
331             if ((state != AL_PLAYING) && (state != AL_PAUSED))
332             {
333                 channel = i;
334                 break;
335             }
336         }
337     }
338
339     if ((channel < 0) || (channel >= num_channels)) return -1;
340     alSourceStop(channels[channel].sid);
341     channels[channel].sample = sptr;
342     alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
343     alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
344     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
345
346     channels[channel].startpaused = ((startpaused) ? true : false);
347     if (!startpaused)
348         alSourcePlay(channels[channel].sid);
349     return channel;
350 }
351
352
353 static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, ALuint &freq)
354 {
355 #ifdef __POWERPC__
356     const int bigendian = 1;
357 #else
358     const int bigendian = 0;
359 #endif
360
361     // !!! FIXME: if it's not Ogg, we don't have a decoder. I'm lazy.  :/
362     char *fname = (char *) alloca(strlen(_fname) + 16);
363     strcpy(fname, _fname);
364     char *ptr = strchr(fname, '.');
365     if (ptr) *ptr = '\0';
366     strcat(fname, ".ogg");
367
368     // just in case...
369     #undef fopen
370     FILE *io = fopen(fname, "rb");
371     if (io == NULL)
372         return NULL;
373
374     ALubyte *retval = NULL;
375
376     #if 0  // untested, so disable this!
377     // Can we just feed it to the AL compressed?
378     if (alIsExtensionPresent((const ALubyte *) "AL_EXT_vorbis"))
379     {
380         format = alGetEnumValue((const ALubyte *) "AL_FORMAT_VORBIS_EXT");
381         freq = 44100;
382         fseek(io, 0, SEEK_END);
383         size = ftell(io);
384         fseek(io, 0, SEEK_SET);
385         retval = (ALubyte *) malloc(size);
386         size_t rc = fread(retval, size, 1, io);
387         fclose(io);
388         if (rc != 1)
389         {
390             free(retval);
391             return NULL;
392         }
393         return retval;
394     }
395     #endif
396
397     // Uncompress and feed to the AL.
398     OggVorbis_File vf;
399     memset(&vf, '\0', sizeof (vf));
400     if (ov_open(io, &vf, NULL, 0) == 0)
401     {
402         int bitstream = 0;
403         vorbis_info *info = ov_info(&vf, -1);
404         size = 0;
405         format = (info->channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
406         freq = info->rate;
407
408         if ((info->channels != 1) && (info->channels != 2))
409         {
410             ov_clear(&vf);
411             return NULL;
412         }
413
414         char buf[1024 * 16];
415         long rc = 0;
416         size_t allocated = 64 * 1024;
417         retval = (ALubyte *) malloc(allocated);
418         while ( (rc = ov_read(&vf, buf, sizeof (buf), bigendian, 2, 1, &bitstream)) != 0 )
419         {
420             if (rc > 0)
421             {
422                 size += rc;
423                 if (size >= allocated)
424                 {
425                     allocated *= 2;
426                     ALubyte *tmp = (ALubyte *) realloc(retval, allocated);
427                     if (tmp == NULL)
428                     {
429                         free(retval);
430                         retval = NULL;
431                         break;
432                     }
433                     retval = tmp;
434                 }
435                 memcpy(retval + (size - rc), buf, rc);
436             }
437         }
438         ov_clear(&vf);
439         return retval;
440     }
441
442     fclose(io);
443     return NULL;
444 }
445
446
447 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length)
448 {
449     if (!initialized) return NULL;
450     if (index != OPENAL_FREE) return NULL;  // this is all the game does...
451     if (offset != 0) return NULL;  // this is all the game does...
452     if (length != 0) return NULL;  // this is all the game does...
453     if ((mode != OPENAL_HW3D) && (mode != OPENAL_2D)) return NULL;  // this is all the game does...
454
455     OPENAL_SAMPLE *retval = NULL;
456     ALuint bufferName = 0;
457     ALenum format = AL_NONE;
458     ALsizei size = 0;
459     ALuint frequency = 0;
460     void *data = decode_to_pcm(name_or_data, format, size, frequency);
461     if (data == NULL)
462         return NULL;
463
464     ALuint bid = 0;
465     alGetError();
466     alGenBuffers(1, &bid);
467     if (alGetError() == AL_NO_ERROR)
468     {
469         alBufferData(bid, format, data, size, frequency);
470         retval = new OPENAL_SAMPLE;
471         retval->bid = bid;
472         retval->mode = OPENAL_LOOP_OFF;
473         retval->is2d = (mode == OPENAL_2D);
474         retval->name = new char[strlen(name_or_data) + 1];
475         if (retval->name)
476             strcpy(retval->name, name_or_data);
477     }
478
479     free(data);
480     return(retval);
481 }
482
483 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
484 {
485     if (!initialized) return;
486     if (sptr)
487     {
488         for (int i = 0; i < num_channels; i++)
489         {
490             if (channels[i].sample == sptr)
491             {
492                 alSourceStop(channels[i].sid);
493                 alSourcei(channels[i].sid, AL_BUFFER, 0);
494                 channels[i].sample = NULL;
495             }
496         }
497         alDeleteBuffers(1, &sptr->bid);
498         delete[] sptr->name;
499         delete sptr;
500     }
501 }
502
503 AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
504 {
505     if (!initialized) return false;
506     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
507     if (!sptr) return false;
508     sptr->mode = mode;
509     return true;
510 }
511
512 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
513 {
514     if (!initialized) return false;
515     if (channel == OPENAL_ALL)
516     {
517         for (int i = 0; i < num_channels; i++)
518             OPENAL_SetFrequency(i, freq);
519         return true;
520     }
521
522     if ((channel < 0) || (channel >= num_channels)) return false;
523     if (freq == 8012)  // hack
524         alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
525     else
526         alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
527     return true;
528 }
529
530 AL_API signed char OPENAL_SetVolume(int channel, int vol)
531 {
532     if (!initialized) return false;
533
534     if (channel == OPENAL_ALL)
535     {
536         for (int i = 0; i < num_channels; i++)
537             OPENAL_SetVolume(i, vol);
538         return true;
539     }
540
541     if ((channel < 0) || (channel >= num_channels)) return false;
542
543     if (vol < 0) vol = 0;
544     else if (vol > 255) vol = 255;
545     ALfloat gain = ((ALfloat) vol) / 255.0f;
546     alSourcef(channels[channel].sid, AL_GAIN, gain);
547     return true;
548 }
549
550 AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
551 {
552     if (!initialized) return false;
553
554     if (channel == OPENAL_ALL)
555     {
556         for (int i = 0; i < num_channels; i++)
557             OPENAL_SetPaused(i, paused);
558         return true;
559     }
560
561     if ((channel < 0) || (channel >= num_channels)) return false;
562
563     ALint state = 0;
564     if (channels[channel].startpaused)
565         state = AL_PAUSED;
566     else
567         alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
568
569     if ((paused) && (state == AL_PLAYING))
570         alSourcePause(channels[channel].sid);
571     else if ((!paused) && (state == AL_PAUSED))
572     {
573         alSourcePlay(channels[channel].sid);
574         channels[channel].startpaused = false;
575     }
576     return true;
577 }
578
579 AL_API void OPENAL_SetSFXMasterVolume(int volume)
580 {
581     if (!initialized) return;
582     ALfloat gain = ((ALfloat) volume) / 255.0f;
583     alListenerf(AL_GAIN, gain);
584 }
585
586 AL_API signed char OPENAL_StopSound(int channel)
587 {
588     if (!initialized) return false;
589
590     if (channel == OPENAL_ALL)
591     {
592         for (int i = 0; i < num_channels; i++)
593             OPENAL_StopSound(i);
594         return true;
595     }
596
597     if ((channel < 0) || (channel >= num_channels)) return false;
598     alSourceStop(channels[channel].sid);
599     channels[channel].startpaused = false;
600     return true;
601 }
602
603 AL_API OPENAL_STREAM *OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
604 {
605     return (OPENAL_STREAM *) OPENAL_Sample_Load(OPENAL_FREE, name_or_data, mode, offset, length);
606 }
607
608 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
609 {
610     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
611 }
612
613 AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
614 {
615     if (!initialized) return NULL;
616     return (OPENAL_SAMPLE *) stream;
617 }
618
619 AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
620 {
621     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
622 }
623
624 AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
625 {
626     if (!initialized) return false;
627     for (int i = 0; i < num_channels; i++)
628     {
629         if (channels[i].sample == (OPENAL_SAMPLE *) stream)
630         {
631             alSourceStop(channels[i].sid);
632             channels[i].startpaused = false;
633         }
634     }
635     return true;
636 }
637
638 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode)
639 {
640     return OPENAL_Sample_SetMode((OPENAL_SAMPLE *) stream, mode);
641 }
642
643 AL_API void OPENAL_Update()
644 {
645     if (!initialized) return;
646     alcProcessContext(alcGetCurrentContext());
647 }
648
649 AL_API signed char OPENAL_SetOutput(int outputtype)
650 {
651     return true;
652 }
653
654 #endif
655