1 // soundmgr.cxx -- Sound effect management class
3 // Sound manager initially written by David Findlay
4 // <david_j_findlay@yahoo.com.au> 2001
6 // C++-ified by Curtis Olson, started March 2001.
8 // Copyright (C) 2001 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
27 # include <simgear_config.h>
30 #if defined( __APPLE__ )
31 # include <OpenAL/alut.h>
38 #include "soundmgr_openal.hxx"
40 #include <simgear/structure/exception.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/misc/sg_path.hxx>
43 #include <simgear/math/SGMath.hxx>
46 #define MAX_SOURCES 128
52 int SGSoundMgr::_alut_init = 0;
55 SGSoundMgr::SGSoundMgr() :
61 _listener_pos(SGVec3d::zeros().data()),
62 _listener_vel(SGVec3f::zeros().data()),
65 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
66 if (_alut_init == 0) {
67 if ( !alutInitWithoutContext(NULL, NULL) ) {
68 testForALUTError("alut initialization");
79 SGSoundMgr::~SGSoundMgr() {
81 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
83 if (_alut_init == 0) {
89 // initialize the sound manager
90 void SGSoundMgr::init() {
92 SG_LOG( SG_GENERAL, SG_INFO, "Initializing OpenAL sound manager" );
94 ALCdevice *device = alcOpenDevice(_devname);
95 if ( testForError(device, "No default audio device available.") ) {
99 ALCcontext *context = alcCreateContext(device, NULL);
100 if ( testForError(context, "Unable to create a valid context.") ) {
104 if ( !alcMakeContextCurrent(context) ) {
105 testForALCError("context initialization");
112 _listener_ori[0] = 0.0; _listener_ori[1] = 0.0; _listener_ori[2] = -1.0;
113 _listener_ori[3] = 0.0; _listener_ori[4] = 1.0; _listener_ori[5] = 0.0;
115 alListenerf( AL_GAIN, 0.2f );
116 alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
117 alListenerfv( AL_ORIENTATION, _listener_ori );
118 alListenerfv( AL_VELOCITY, _listener_vel.data() );
120 alDopplerFactor(1.0);
121 alDopplerVelocity(340.3); // speed of sound in meters per second.
123 if ( alIsExtensionPresent((const ALchar*)"EXT_exponent_distance") ) {
124 alDistanceModel(AL_EXPONENT_DISTANCE);
126 alDistanceModel(AL_INVERSE_DISTANCE);
129 testForALError("listener initialization");
131 alGetError(); // clear any undetetced error, just to be sure
133 // get a free source one at a time
134 // if an error is returned no more (hardware) sources are available
135 for (unsigned int i=0; i<MAX_SOURCES; i++) {
140 alGenSources(1, &source);
141 error = alGetError();
142 if ( error == AL_NO_ERROR ) {
143 _free_sources.push_back( source );
149 // suspend the sound manager
150 void SGSoundMgr::stop() {
154 _context = alcGetCurrentContext();
155 _device = alcGetContextsDevice(_context);
156 alcMakeContextCurrent(NULL);
157 alcDestroyContext(_context);
158 alcCloseDevice(_device);
162 void SGSoundMgr::suspend() {
164 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
165 sample_group_map_iterator sample_grp_end = _sample_groups.end();
166 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
167 SGSampleGroup *sgrp = sample_grp_current->second;
174 void SGSoundMgr::bind ()
176 _free_sources.clear();
177 _free_sources.reserve( MAX_SOURCES );
178 _sources_in_use.clear();
179 _sources_in_use.reserve( MAX_SOURCES );
183 void SGSoundMgr::unbind ()
185 _sample_groups.clear();
187 // delete free sources
188 for (unsigned int i=0; i<_free_sources.size(); i++) {
189 ALuint source = _free_sources.at( i );
190 alDeleteSources( 1 , &source );
193 _free_sources.clear();
194 _sources_in_use.clear();
197 void SGSoundMgr::update( double dt )
199 // nothing to do in the regular update,e verything is done on the following
204 // run the audio scheduler
205 void SGSoundMgr::update_late( double dt ) {
207 // alcSuspendContext(_context);
209 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
210 sample_group_map_iterator sample_grp_end = _sample_groups.end();
211 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
212 SGSampleGroup *sgrp = sample_grp_current->second;
217 alListenerf( AL_GAIN, _volume );
218 alListenerfv( AL_VELOCITY, _listener_vel.data() );
219 alListenerfv( AL_ORIENTATION, _listener_ori );
220 alListenerfv( AL_POSITION, toVec3f(_listener_pos).data() );
221 // alDopplerVelocity(340.3); // TODO: altitude dependent
222 testForALError("update");
225 // alcProcessContext(_context);
231 SGSoundMgr::resume ()
234 sample_group_map_iterator sample_grp_current = _sample_groups.begin();
235 sample_group_map_iterator sample_grp_end = _sample_groups.end();
236 for ( ; sample_grp_current != sample_grp_end; ++sample_grp_current ) {
237 SGSampleGroup *sgrp = sample_grp_current->second;
244 // add a sampel group, return true if successful
245 bool SGSoundMgr::add( SGSampleGroup *sgrp, const string& refname )
247 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
248 if ( sample_grp_it != _sample_groups.end() ) {
249 // sample group already exists
253 _sample_groups[refname] = sgrp;
259 // remove a sound effect, return true if successful
260 bool SGSoundMgr::remove( const string &refname )
262 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
263 if ( sample_grp_it == _sample_groups.end() ) {
264 // sample group was not found.
268 _sample_groups.erase( refname );
274 // return true of the specified sound exists in the sound manager system
275 bool SGSoundMgr::exists( const string &refname ) {
276 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
277 if ( sample_grp_it == _sample_groups.end() ) {
278 // sample group was not found.
286 // return a pointer to the SGSampleGroup if the specified sound exists
287 // in the sound manager system, otherwise return NULL
288 SGSampleGroup *SGSoundMgr::find( const string &refname, bool create ) {
289 sample_group_map_iterator sample_grp_it = _sample_groups.find( refname );
290 if ( sample_grp_it == _sample_groups.end() ) {
291 // sample group was not found.
293 SGSampleGroup* sgrp = new SGSampleGroup(this, refname);
300 return sample_grp_it->second;
304 void SGSoundMgr::set_volume( float v )
307 if (_volume > 1.0) _volume = 1.0;
308 if (_volume < 0.0) _volume = 0.0;
312 // Get an unused source id
314 // The Sound Manager should keep track of the sources in use, the distance
315 // of these sources to the listener and the volume (also based on audio cone
316 // and hence orientation) of the sources.
318 // The Sound Manager is (and should be) the only one knowing about source
319 // management. Sources further away should be suspendped to free resources for
320 // newly added sounds close by.
321 unsigned int SGSoundMgr::request_source()
323 unsigned int source = NO_SOURCE;
325 if (_free_sources.size() > 0) {
326 source = _free_sources.back();
327 _free_sources.pop_back();
329 _sources_in_use.push_back(source);
335 // Free up a source id for further use
336 void SGSoundMgr::release_source( unsigned int source )
338 for (unsigned int i = 0; i<_sources_in_use.size(); i++) {
339 if ( _sources_in_use[i] == source ) {
342 alGetSourcei( source, AL_SOURCE_STATE, &result );
343 if ( result == AL_PLAYING ) {
344 alSourceStop( source );
346 testForALError("release source");
348 _free_sources.push_back(source);
349 _sources_in_use.erase(_sources_in_use.begin()+i,
350 _sources_in_use.begin()+i+1);
356 bool SGSoundMgr::load(string &samplepath, void **dbuf, int *fmt,
357 unsigned int *sz, int *frq )
359 ALenum format = (ALenum)*fmt;
360 ALsizei size = (ALsizei)*sz;
361 ALsizei freq = (ALsizei)*frq;
364 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
366 data = alutLoadMemoryFromFile(samplepath.c_str(), &format, &size, &freqf );
367 freq = (ALsizei)freqf;
369 int error = alutGetError();
370 string msg = "Failed to load wav file: ";
371 msg.append(alutGetErrorString(error));
372 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
377 ALbyte *fname = (ALbyte *)samplepath.c_str();
378 # if defined (__APPLE__)
379 alutLoadWAVFile( fname, &format, &data, &size, &freq );
382 alutLoadWAVFile( fname, &format, &data, &size, &freq, &loop );
384 ALenum error = alutGetError();
385 if ( error != ALUT_ERROR_NO_ERROR ) {
386 string msg = "Failed to load wav file: ";
387 msg.append(alutGetErrorString(error));
388 throw sg_io_exception(msg.c_str(), sg_location(samplepath));
393 *dbuf = (void *)data;
395 *sz = (unsigned int)size;
403 * set the orientation of the listener (in opengl coordinates)
405 * Description: ORIENTATION is a pair of 3-tuples representing the
406 * 'at' direction vector and 'up' direction of the Object in
407 * Cartesian space. AL expects two vectors that are orthogonal to
408 * each other. These vectors are not expected to be normalized. If
409 * one or more vectors have zero length, implementation behavior
410 * is undefined. If the two vectors are linearly dependent,
411 * behavior is undefined.
413 void SGSoundMgr::set_orientation( SGQuatd ori )
415 SGVec3d sgv_up = ori.rotate(SGVec3d::e3());
416 SGVec3d sgv_at = ori.rotate(SGVec3d::e2());
417 for (int i=0; i<3; i++) {
418 _listener_ori[i] = sgv_at[i];
419 _listener_ori[i+3] = sgv_up[i];
425 bool SGSoundMgr::testForError(void *p, string s)
428 SG_LOG( SG_GENERAL, SG_ALERT, "Error: " << s);
435 bool SGSoundMgr::testForALError(string s)
437 ALenum error = alGetError();
438 if (error != AL_NO_ERROR) {
439 SG_LOG( SG_GENERAL, SG_ALERT, "AL Error (sound manager): "
440 << alGetString(error) << " at " << s);
446 bool SGSoundMgr::testForALCError(string s)
449 error = alcGetError(_device);
450 if (error != ALC_NO_ERROR) {
451 SG_LOG( SG_GENERAL, SG_ALERT, "ALC Error (sound manager): "
452 << alcGetString(_device, error) << " at "
459 bool SGSoundMgr::testForALUTError(string s)
461 #if defined(ALUT_API_MAJOR_VERSION) && ALUT_API_MAJOR_VERSION >= 1
463 error = alutGetError ();
464 if (error != ALUT_ERROR_NO_ERROR) {
465 SG_LOG( SG_GENERAL, SG_ALERT, "ALUT Error (sound manager): "
466 << alutGetErrorString(error) << " at "