]> git.mxchange.org Git - simgear.git/blob - simgear/sound/soundmgr_openal.cxx
Correct (and verrified) position, orientation and velocity vector. Todo: proper sound...
[simgear.git] / simgear / sound / soundmgr_openal.cxx
1 // soundmgr.cxx -- Sound effect management class
2 //
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
5 //
6 // C++-ified by Curtis Olson, started March 2001.
7 //
8 // Copyright (C) 2001  Curtis L. Olson - http://www.flightgear.org/~curt
9 //
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
14 //
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 // General Public License for more details.
19 //
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software Foundation,
22 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
23 //
24 // $Id$
25
26 #ifdef HAVE_CONFIG_H
27 #  include <simgear_config.h>
28 #endif
29
30 #if defined( __APPLE__ )
31 # include <OpenAL/alut.h>
32 #else
33 # include <AL/alut.h>
34 #endif
35
36 #include <iostream>
37 #include <algorithm>
38
39 #include "soundmgr_openal.hxx"
40
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/math/SGMath.hxx>
45
46
47 #define MAX_SOURCES     128
48
49 //
50 // Sound Manager
51 //
52
53 int SGSoundMgr::_alut_init = 0;
54
55 // constructor
56 SGSoundMgr::SGSoundMgr() :
57     _working(false),
58     _changed(true),
59     _volume(0.0),
60     _device(NULL),
61     _context(NULL),
62     _position(SGVec3d::zeros().data()),
63     _velocity(SGVec3f::zeros().data()),
64     _devname(NULL)
65 {
66 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
67     if (_alut_init == 0) {
68         if ( !alutInitWithoutContext(NULL, NULL) ) {
69             testForALUTError("alut initialization");
70             return;
71         }
72         _alut_init++;
73     }
74     _alut_init++;
75 #endif
76 }
77
78 // destructor
79
80 SGSoundMgr::~SGSoundMgr() {
81
82     stop();
83 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
84     _alut_init--;
85     if (_alut_init == 0) {
86         alutExit ();
87     }
88 #endif
89 }
90
91 // initialize the sound manager
92 void SGSoundMgr::init() {
93
94     SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
95
96     ALCdevice *device = alcOpenDevice(_devname);
97     if ( testForError(device, "No default audio device available.") ) {
98         return;
99     }
100
101     ALCcontext *context = alcCreateContext(device, NULL);
102     if ( testForError(context, "Unable to create a valid context.") ) {
103         return;
104     }
105
106     if ( !alcMakeContextCurrent(context) ) {
107         testForALCError("context initialization");
108         return;
109     }
110
111     _context = context;
112     _working = true;
113
114     _orientation[0] = 0.0; _orientation[1] = 0.0; _orientation[2] = -1.0;
115     _orientation[3] = 0.0; _orientation[4] = 1.0; _orientation[5] = 0.0;
116
117     alListenerf( AL_GAIN, 0.2f );
118     alListenerfv( AL_POSITION, toVec3f(_position).data() );
119     alListenerfv( AL_ORIENTATION, _orientation );
120     alListenerfv( AL_VELOCITY, _velocity.data() );
121
122     alDopplerFactor(0.5);
123     alDopplerVelocity(340.3);   // speed of sound in meters per second.
124
125     if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
126         alDistanceModel(AL_EXPONENT_DISTANCE);
127     } else {
128         alDistanceModel(AL_INVERSE_DISTANCE);
129     }
130
131     testForALError("listener initialization");
132
133     alGetError(); // clear any undetetced error, just to be sure
134
135     // get a free source one at a time
136     // if an error is returned no more (hardware) sources are available
137     for (unsigned int i=0; i<MAX_SOURCES; i++) {
138         ALuint source;
139         ALenum error;
140
141         alGetError();
142         alGenSources(1, &source);
143         error = alGetError();
144         if ( error == AL_NO_ERROR ) {
145             _free_sources.push_back( source );
146         }
147         else break;
148     }
149 }
150
151 // suspend the sound manager
152 void SGSoundMgr::stop() {
153     if (_working) {
154         _working = false;
155
156         // clear any OpenAL buffers before shutting down
157         buffer_map_iterator buffers_current = _buffers.begin();
158         buffer_map_iterator buffers_end = _buffers.end();
159         for ( ; buffers_current != buffers_end; ++buffers_current ) {
160             refUint ref = buffers_current->second;
161             ALuint buffer = ref.id;
162             alDeleteBuffers(1, &buffer);
163             _buffers.erase( buffers_current );
164         }
165
166         _context = alcGetCurrentContext();
167         _device = alcGetContextsDevice(_context);
168         alcMakeContextCurrent(NULL);
169         alcDestroyContext(_context);
170         alcCloseDevice(_device);
171     }
172 }
173
174 void SGSoundMgr::suspend() {
175     if (_working) {
176         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
177         sample_group_map_iterator sample_grp_end = _sample_groups.end();
178         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
179             SGSampleGroup *sgrp = sample_grp_current->second;
180             sgrp->suspend();
181         }
182     }
183 }
184
185
186 void SGSoundMgr::bind ()
187 {
188     _free_sources.clear();
189     _free_sources.reserve( MAX_SOURCES );
190     _sources_in_use.clear();
191     _sources_in_use.reserve( MAX_SOURCES );
192 }
193
194
195 void SGSoundMgr::unbind ()
196 {
197     _sample_groups.clear();
198
199     // delete free sources
200     for (unsigned int i=0; i<_free_sources.size(); i++) {
201         ALuint source = _free_sources.at( i );
202         alDeleteSources( 1 , &source );
203     }
204
205     _free_sources.clear();
206     _sources_in_use.clear();
207 }
208
209 void SGSoundMgr::update( double dt )
210 {
211     // nothing to do in the regular update, everything is done on the following
212     // function
213 }
214
215
216 // run the audio scheduler
217 void SGSoundMgr::update_late( double dt ) {
218     if (_working) {
219         alcSuspendContext(_context);
220
221         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
222         sample_group_map_iterator sample_grp_end = _sample_groups.end();
223         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
224             SGSampleGroup *sgrp = sample_grp_current->second;
225             sgrp->update(dt);
226         }
227
228         if (_changed) {
229             alListenerf( AL_GAIN, _volume );
230             alListenerfv( AL_VELOCITY, _velocity.data() );
231             alListenerfv( AL_ORIENTATION, _orientation );
232             alListenerfv( AL_POSITION, toVec3f(_position).data() );
233             // alDopplerVelocity(340.3);        // TODO: altitude dependent
234             testForALError("update");
235             _changed = false;
236         }
237         alcProcessContext(_context);
238     }
239 }
240
241
242 void
243 SGSoundMgr::resume ()
244 {
245     if (_working) {
246         sample_group_map_iterator sample_grp_current = _sample_groups.begin();
247         sample_group_map_iterator sample_grp_end = _sample_groups.end();
248         for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
249             SGSampleGroup *sgrp = sample_grp_current->second;
250             sgrp->resume();
251         }
252     }
253 }
254
255
256 // add a sampel group, return true if successful
257 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
258 {
259     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
260     if ( sample_grp_it != _sample_groups.end() ) {
261         // sample group already exists
262         return false;
263     }
264
265     _sample_groups[refname] = sgrp;
266
267     return true;
268 }
269
270
271 // remove a sound effect, return true if successful
272 bool SGSoundMgr::remove( const string &refname )
273 {
274     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
275     if ( sample_grp_it == _sample_groups.end() ) {
276         // sample group was not found.
277         return false;
278     }
279
280     _sample_groups.erase( refname );
281
282     return true;
283 }
284
285
286 // return true of the specified sound exists in the sound manager system
287 bool SGSoundMgr::exists( const string &refname ) {
288     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
289     if ( sample_grp_it == _sample_groups.end() ) {
290         // sample group was not found.
291         return false;
292     }
293
294     return true;
295 }
296
297
298 // return a pointer to the SGSampleGroup if the specified sound exists
299 // in the sound manager system, otherwise return NULL
300 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
301     sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
302     if ( sample_grp_it == _sample_groups.end() ) {
303         // sample group was not found.
304         if (create) {
305             SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
306             return sgrp;
307         }
308         else 
309             return NULL;
310     }
311
312     return sample_grp_it->second;
313 }
314
315
316 void SGSoundMgr::set_volume( float v )
317 {
318     _volume = v;
319     if (_volume > 1.0) _volume = 1.0;
320     if (_volume < 0.0) _volume = 0.0;
321     _changed = true;
322 }
323
324 /**
325  * set the orientation of the listener (in opengl coordinates)
326  *
327  * Description: ORIENTATION is a pair of 3-tuples representing the
328  * 'at' direction vector and 'up' direction of the Object in
329  * Cartesian space. AL expects two vectors that are orthogonal to
330  * each other. These vectors are not expected to be normalized. If
331  * one or more vectors have zero length, implementation behavior
332  * is undefined. If the two vectors are linearly dependent,
333  * behavior is undefined.
334  */
335 void SGSoundMgr::set_orientation( SGQuatd ori )
336 {
337     SGVec3d sgv_up = ori.rotate(SGVec3d::e2());
338     SGVec3d sgv_at = ori.rotate(SGVec3d::e3());
339     _orientation[0] = sgv_at[0];
340     _orientation[1] = sgv_at[1];
341     _orientation[2] = sgv_at[2];
342     _orientation[3] = sgv_up[0];
343     _orientation[4] = sgv_up[1];
344     _orientation[5] = sgv_up[2];
345     _changed = true;
346 }
347
348 // Get an unused source id
349 //
350 // The Sound Manager should keep track of the sources in use, the distance
351 // of these sources to the listener and the volume (also based on audio cone
352 // and hence orientation) of the sources.
353 //
354 // The Sound Manager is (and should be) the only one knowing about source
355 // management. Sources further away should be suspendped to free resources for
356 // newly added sounds close by.
357 unsigned int SGSoundMgr::request_source()
358 {
359     unsigned int source = NO_SOURCE;
360
361     if (_free_sources.size() > 0) {
362        source = _free_sources.back();
363        _free_sources.pop_back();
364        _sources_in_use.push_back(source);
365     }
366
367     return source;
368 }
369
370 // Free up a source id for further use
371 void SGSoundMgr::release_source( unsigned int source )
372 {
373     vector<ALuint>::iterator it;
374
375     it = std::find(_sources_in_use.begin(), _sources_in_use.end(), source);
376     if ( it != _sources_in_use.end() ) {
377         ALint result;
378
379         alGetSourcei( source, AL_SOURCE_STATE, &result );
380         if ( result == AL_PLAYING )
381             alSourceStop( source );
382         testForALError("release source");
383
384         _free_sources.push_back(source);
385         _sources_in_use.erase(it, it+1);
386     }
387 }
388
389 unsigned int SGSoundMgr::request_buffer(SGSoundSample *sample)
390 {
391     ALuint buffer = NO_BUFFER;
392
393     if ( !sample->is_valid_buffer() ) {
394         // sample was not yet loaded or removed again
395         string sample_name = sample->get_sample_name();
396
397         // see if the sample name is already cached
398         buffer_map_iterator buffer_it = _buffers.find( sample_name );
399         if ( buffer_it != _buffers.end() ) {
400             buffer_it->second.refctr++;
401             buffer = buffer_it->second.id;
402             sample->set_buffer( buffer );
403             return buffer;
404         }
405
406         // sample name was not found in the buffer cache.
407         if ( sample->is_file() ) {
408             unsigned int size;
409             int freq, format;
410             void *data;
411
412             load(sample_name, &data, &format, &size, &freq);
413             sample->set_data( (unsigned char *)data );
414             sample->set_frequency( freq );
415             sample->set_format( format );
416             sample->set_size( size );
417         }
418
419         // create an OpenAL buffer handle
420         alGenBuffers(1, &buffer);
421         if ( !testForALError("generate buffer") ) {
422             // Copy data to the internal OpenAL buffer
423
424             const ALvoid *data = sample->get_data();
425             ALenum format = sample->get_format();
426             ALsizei size = sample->get_size();
427             ALsizei freq = sample->get_frequency();
428             alBufferData( buffer, format, data, size, freq );
429             sample->free_data();
430
431             if ( !testForALError("buffer add data") ) {
432                 sample->set_buffer(buffer);
433                 _buffers[sample_name] = refUint(buffer);
434             }
435         }
436     }
437     else
438         buffer = sample->get_buffer();
439
440     return buffer;
441 }
442
443 void SGSoundMgr::release_buffer(SGSoundSample *sample)
444 {
445     string sample_name = sample->get_sample_name();
446
447     buffer_map_iterator buffer_it = _buffers.find( sample_name );
448     if ( buffer_it == _buffers.end() ) {
449         // buffer was not found
450         return;
451     }
452
453     sample->no_valid_buffer();
454     buffer_it->second.refctr--;
455     if (buffer_it->second.refctr == 0) {
456         ALuint buffer = buffer_it->second.id;
457         _buffers.erase( buffer_it );
458         alDeleteBuffers(1, &buffer);
459         testForALError("release buffer");
460     }
461 }
462
463 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
464                                           unsigned int *sz, int *frq )
465 {
466     ALenum format = (ALenum)*fmt;
467     ALsizei size = (ALsizei)*sz;
468     ALsizei freq = (ALsizei)*frq;
469     ALvoid *data;
470
471 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
472     ALfloat freqf;
473     data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
474     freq = (ALsizei)freqf;
475     if (data == NULL) {
476         int error = alutGetError();
477         string msg = "Failed to load wav file: ";
478         msg.append(alutGetErrorString(error));
479         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
480         return false;
481     }
482
483 #else
484     ALbyte *fname = (ALbyte *)samplepath.c_str();
485 # if defined (__APPLE__)
486     alutLoadWAVFile( fname, &format, &data, &size, &freq );
487 # else
488     ALboolean loop;
489     alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
490 # endif
491     ALenum error =  alutGetError();
492     if ( error != ALUT_ERROR_NO_ERROR ) {
493         string msg = "Failed to load wav file: ";
494         msg.append(alutGetErrorString(error));
495         throw sg_io_exception(msg.c_str(), sg_location(samplepath));
496         return false;
497     }
498 #endif
499
500     *dbuf = (void *)data;
501     *fmt = (int)format;
502     *sz = (unsigned int)size;
503     *frq = (int)freq;
504
505     return true;
506 }
507
508
509 bool SGSoundMgr::testForError(void *p, string s)
510 {
511    if (p == NULL) {
512       SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
513       return true;
514    }
515    return false;
516 }
517
518
519 bool SGSoundMgr::testForALError(string s)
520 {
521     ALenum error = alGetError();
522     if (error != AL_NO_ERROR)  {
523        SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
524                                       << alGetString(error) << " at " << s);
525        return true;
526     }
527     return false;
528 }
529
530 bool SGSoundMgr::testForALCError(string s)
531 {
532     ALCenum error;
533     error = alcGetError(_device);
534     if (error != ALC_NO_ERROR) {
535         SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
536                                        << alcGetString(_device, error) << " at "
537                                        << s);
538         return true;
539     }
540     return false;
541 }
542
543 bool SGSoundMgr::testForALUTError(string s)
544 {
545 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
546     ALenum error;
547     error =  alutGetError ();
548     if (error != ALUT_ERROR_NO_ERROR) {
549         SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
550                                        << alutGetErrorString(error) << " at "
551                                        << s);
552         return true;
553     }
554 #endif
555     return false;
556 }