Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/mac_osx/src/orxonox/sound/SoundManager.cc @ 8128

Last change on this file since 8128 was 8128, checked in by rgrieder, 13 years ago

Fix

  • Property svn:eol-style set to native
File size: 23.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *       Erwin 'vaiursch' Herrsche
24 *       Kevin Young
25 *       Reto Grieder
26 *   Co-authors:
27 *      ...
28 *
29 */
30
31#include "SoundManager.h"
32
33#include <utility>
34#include <alut.h>
35#include <loki/ScopeGuard.h>
36
37#include "util/Exception.h"
38#include "util/Math.h"
39#include "util/Clock.h"
40#include "util/ScopedSingletonManager.h"
41#include "core/ConfigValueIncludes.h"
42#include "core/CoreIncludes.h"
43#include "core/GameMode.h"
44#include "core/Resource.h"
45#include "SoundBuffer.h"
46#include "BaseSound.h"
47#include "AmbientSound.h"
48#include "WorldSound.h"
49
50namespace orxonox
51{
52    ManageScopedSingleton(SoundManager, ScopeID::Graphics, true);
53
54    std::string SoundManager::getALErrorString(ALenum code)
55    {
56        switch (code)
57        {
58        case AL_NO_ERROR:          return "No error";
59        case AL_INVALID_NAME:      return "Invalid AL parameter name";
60        case AL_INVALID_ENUM:      return "Invalid AL enum";
61        case AL_INVALID_VALUE:     return "Invalid AL value";
62        case AL_INVALID_OPERATION: return "Invalid AL operation";
63        case AL_OUT_OF_MEMORY:     return "AL reports out of memory";
64        default:                   return "Unknown AL error";
65        }
66    }
67
68    SoundManager::SoundManager()
69        : effectsPoolSize_(0)
70    {
71        RegisterRootObject(SoundManager);
72
73        // Clear error messages (might be problematic on some systems)
74        alGetError();
75        alutGetError();
76
77        // See whether we even want to load
78        bool bDisableSound_ = false;
79        SetConfigValue(bDisableSound_, false);
80        if (bDisableSound_)
81            ThrowException(InitialisationAborted, "Sound: Not loading at all");
82        if (!alutInitWithoutContext(NULL, NULL))
83            ThrowException(InitialisationFailed, "Sound Error: ALUT initialisation failed: " << alutGetErrorString(alutGetError()));
84        Loki::ScopeGuard alutExitGuard = Loki::MakeGuard(&alutExit);
85
86/*
87        // Get list of available sound devices and display them
88        const char* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
89        char* device = new char[strlen(devices)+1];
90        strcpy(device, devices);
91        std::string renderDevice;
92        SetConfigValue(renderDevice, std::string(device)).description("Sound device used for rendering");
93        COUT(4) << "Sound: Available devices: ";
94        while (true)
95        {
96            this->deviceNames_.push_back(devices);
97            COUT(4) << '"' << devices << "\", ";
98            devices += strlen(devices) + 1;
99            if (*devices == '\0')
100                break;
101        }
102        COUT(4) << std::endl;
103
104        // Open the selected device
105        COUT(3) << "Sound: Opening device \"" << renderDevice << '\' << std::endl;
106        this->device_ = alcOpenDevice(renderDevice.c_str());
107*/
108        this->device_ = alcOpenDevice(NULL);
109        if (this->device_ == NULL)
110        {
111            COUT(1) << "Sound: Could not open sound device. Have you installed OpenAL?" << std::endl;
112#ifdef ORXONOX_PLATFORM_WINDOWS
113            COUT(1) << "Sound: Just getting the DLL with the dependencies is not enough for Windows (esp. Windows 7)!" << std::endl;
114#endif
115            ThrowException(InitialisationFailed, "Sound Error: Could not open sound device.");
116        }
117        Loki::ScopeGuard closeDeviceGuard = Loki::MakeGuard(&alcCloseDevice, this->device_);
118
119        // Create sound context and make it the currently used one
120        this->context_ = alcCreateContext(this->device_, NULL);
121        if (this->context_ == NULL)
122            ThrowException(InitialisationFailed, "Sound Error: Could not create ALC context");
123        Loki::ScopeGuard desroyContextGuard = Loki::MakeGuard(&alcDestroyContext, this->context_);
124        if (!alcMakeContextCurrent(this->context_))
125            ThrowException(InitialisationFailed, "Sound Error: Could not use ALC context");
126
127        GameMode::setPlaysSound(true);
128        Loki::ScopeGuard resetPlaysSoundGuard = Loki::MakeGuard(&GameMode::setPlaysSound, false);
129
130        // Get some information about the sound
131        if (const char* version = alGetString(AL_VERSION))
132            COUT(4) << "Sound: --- OpenAL Version: " << version << std::endl;
133        if (const char* vendor = alGetString(AL_VENDOR))
134            COUT(4) << "Sound: --- OpenAL Vendor : " << vendor << std::endl;
135        if (const char* types = alutGetMIMETypes(ALUT_LOADER_BUFFER))
136            COUT(4) << "Sound: --- Supported MIME Types: " << types << std::endl;
137        else
138            COUT(2) << "Sound Warning: MIME Type retrieval failed: " << alutGetErrorString(alutGetError()) << std::endl;
139
140        this->mute_[SoundType::All]     = 1.0f;
141        this->mute_[SoundType::Music]   = 1.0f;
142        this->mute_[SoundType::Effects] = 1.0f;
143
144        this->setConfigValues();
145
146        // Try to get at least one source
147        ALuint source;
148        alGenSources(1, &source);
149        if (!alGetError() && alIsSource(source))
150            this->availableSoundSources_.push_back(source);
151        else
152            ThrowException(InitialisationFailed, "Sound Error: Could not create even a single source");
153        // Create a few initial sources
154        this->createSoundSources(this->minSources_ - 1);
155
156        // Disarm guards
157        alutExitGuard.Dismiss();
158        closeDeviceGuard.Dismiss();
159        desroyContextGuard.Dismiss();
160        resetPlaysSoundGuard.Dismiss();
161
162        COUT(4) << "Sound: Initialisation complete" << std::endl;
163    }
164
165    SoundManager::~SoundManager()
166    {
167        // Erase fade lists because of the smart pointers
168        this->fadeInList_.clear();
169        this->fadeOutList_.clear();
170
171        // If there are still used buffers around, well, that's just very bad...
172        if (this->soundBuffers_.size() != this->effectsPool_.size())
173            COUT(1) << "Sound Error: Some sound buffers are still in use but OpenAL is about to shut down. Fix this!" << std::endl;
174        // Empty buffer pool and buffer list
175        this->effectsPool_.clear();
176        this->soundBuffers_.clear();
177
178        // There should not be any sources in use anymore
179        if (!this->usedSoundSources_.empty())
180            COUT(1) << "Sound Error: Some sound sources are still in use but OpenAL is about to shut down. Fix this!" << std::endl;
181        while (!this->availableSoundSources_.empty())
182        {
183            alDeleteSources(1, &this->availableSoundSources_.back());
184            this->availableSoundSources_.pop_back();
185        }
186
187        GameMode::setPlaysSound(false);
188
189        // Relieve context to destroy it
190        if (!alcMakeContextCurrent(NULL))
191            COUT(1) << "Sound Error: Could not unset ALC context" << std::endl;
192        alcDestroyContext(this->context_);
193        if (ALCenum error = alcGetError(this->device_))
194        {
195            if (error == AL_INVALID_OPERATION)
196                COUT(1) << "Sound Error: Could not destroy ALC context because it is the current one" << std::endl;
197            else
198                COUT(1) << "Sound Error: Could not destroy ALC context because it is invalid" << std::endl;
199        }
200#ifdef AL_VERSION_1_1
201        if (!alcCloseDevice(this->device_))
202            COUT(1) << "Sound Error: Could not destroy ALC device. This might be because there are still buffers in use!" << std::endl;
203#else
204        alcCloseDevice(this->device_);
205#endif
206        if (!alutExit())
207            COUT(1) << "Sound Error: Closing ALUT failed: " << alutGetErrorString(alutGetError()) << std::endl;
208    }
209
210    void SoundManager::setConfigValues()
211    {
212        SetConfigValue(crossFadeStep_, 0.2f)
213            .description("Determines how fast sounds should fade, per second.")
214            .callback(this, &SoundManager::checkFadeStepValidity);
215
216        SetConfigValueAlias(volume_[SoundType::All], "soundVolume_", 1.0f)
217            .description("Defines the overall volume.")
218            .callback(this, &SoundManager::checkSoundVolumeValidity);
219        SetConfigValueAlias(volume_[SoundType::Music], "ambientVolume_", 1.0f)
220            .description("Defines the ambient volume.")
221            .callback(this, &SoundManager::checkAmbientVolumeValidity);
222        SetConfigValueAlias(volume_[SoundType::Effects], "effectsVolume_", 1.0f)
223            .description("Defines the effects volume.")
224            .callback(this, &SoundManager::checkEffectsVolumeValidity);
225
226        SetConfigValue(minSources_, 16)
227            .description("Minimum number of sources being generated (if possible)");
228        SetConfigValue(maxSources_, 1024)
229            .description("Maximum number of sources to be made available");
230    }
231
232    void SoundManager::preUpdate(const Clock& time)
233    {
234        this->processCrossFading(time.getDeltaTime());
235
236        // Check whether a sound object has stopped playing
237        for (unsigned int i = 0; i < this->usedSoundSources_.size(); ++i)
238        {
239            ALint state;
240            alGetSourcei(this->usedSoundSources_[i].first, AL_SOURCE_STATE, &state);
241            if (state == AL_STOPPED)
242            {
243                this->usedSoundSources_[i].second->stop();
244                --i;
245            }
246        }
247    }
248
249    void SoundManager::checkFadeStepValidity()
250    {
251        if (crossFadeStep_ <= 0.0 || crossFadeStep_ >= 1.0 )
252        {
253            COUT(2) << "Sound warning: fade step out of range, ignoring change." << std::endl;
254            ResetConfigValue(crossFadeStep_);
255        }
256    }
257
258    void SoundManager::checkVolumeValidity(SoundType::Value type)
259    {
260        float clampedVolume = clamp(this->volume_[type], 0.0f, 1.0f);
261        if (clampedVolume != this->volume_[type])
262            COUT(2) << "Sound warning: Volume setting (" << type << ") out of range, clamping." << std::endl;
263        this->updateVolume(type);
264    }
265
266    void SoundManager::setVolume(float vol, SoundType::Value type)
267    {
268        if (type < 0 || type > SoundType::Effects)
269            return;
270        this->volume_[type] = vol;
271        this->checkVolumeValidity(type);
272    }
273
274    float SoundManager::getVolume(SoundType::Value type)
275    {
276        if (type < 0 || type > SoundType::Effects)
277            return 0.0f;
278        return this->volume_[type];
279    }
280
281    float SoundManager::getRealVolume(SoundType::Value type)
282    {
283        if (type != SoundType::Music && type != SoundType::Effects)
284            return 0.0f;
285        return this->volume_[SoundType::All] * this->mute_[SoundType::All] * this->volume_[type] * this->mute_[type];
286    }
287
288    void SoundManager::updateVolume(SoundType::Value type)
289    {
290        switch(type)
291        {
292        case SoundType::All:
293            for (ObjectList<BaseSound>::iterator it = ObjectList<BaseSound>::begin(); it != ObjectList<BaseSound>::end(); ++it)
294                (*it)->updateVolume();
295            break;
296        case SoundType::Music:
297            for (ObjectList<AmbientSound>::iterator it = ObjectList<AmbientSound>::begin(); it != ObjectList<AmbientSound>::end(); ++it)
298                (*it)->updateVolume();
299            break;
300        case SoundType::Effects:
301            for (ObjectList<WorldSound>::iterator it = ObjectList<WorldSound>::begin(); it != ObjectList<WorldSound>::end(); ++it)
302                (*it)->updateVolume();
303            break;
304        default:
305            assert(false);
306        }
307    }
308
309    void SoundManager::toggleMute(SoundType::Value type)
310    {
311        if (type < 0 || type > SoundType::Effects)
312            return;
313        this->mute_[type] = (this->mute_[type] == 0) ? 1.0f : 0.0f;
314        this->updateVolume(type);
315    }
316
317    bool SoundManager::getMute(SoundType::Value type)
318    {
319        if (type < 0 || type > SoundType::Effects)
320            return true;
321        return (this->mute_[type] == 0);
322    }
323
324    void SoundManager::setListenerPosition(const Vector3& position)
325    {
326        alListener3f(AL_POSITION, position.x, position.y, position.z);
327        ALenum error = alGetError();
328        if (error == AL_INVALID_VALUE)
329            // @TODO: Follow this constantly appearing, nerve-racking warning
330            COUT(2) << "Sound: OpenAL: Invalid listener position" << std::endl;
331    }
332
333    void SoundManager::setListenerOrientation(const Quaternion& orientation)
334    {
335        // update listener orientation
336        const Vector3& direction = -orientation.zAxis();
337        const Vector3& up = orientation.yAxis();
338
339        ALfloat orient[6] = { direction.x, direction.y, direction.z, up.x, up.y, up.z };
340
341        alListenerfv(AL_ORIENTATION, orient);
342        ALenum error = alGetError();
343        if (error == AL_INVALID_VALUE)
344            COUT(2) << "Sound: OpenAL: Invalid listener orientation" << std::endl;
345    }
346
347    void SoundManager::registerAmbientSound(AmbientSound* newAmbient)
348    {
349        if (newAmbient != NULL)
350        {
351            for (AmbientList::const_iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
352            {
353                if (it->first == newAmbient)
354                {
355                    COUT(2) << "Sound warning: Will not play an AmbientSound twice." << std::endl;
356                    return;
357                }
358            }
359
360            if (!this->ambientSounds_.empty())
361            {
362                this->fadeOut(ambientSounds_.front().first);
363            }
364            this->ambientSounds_.push_front(std::make_pair(newAmbient, false));
365            newAmbient->doPlay();
366            this->fadeIn(newAmbient);
367        }
368    }
369
370    void SoundManager::unregisterAmbientSound(AmbientSound* oldAmbient)
371    {
372        if (oldAmbient == NULL || ambientSounds_.empty())
373            return;
374
375        if (this->ambientSounds_.front().first == oldAmbient)
376        {
377            this->fadeOut(oldAmbient);
378            this->ambientSounds_.pop_front();
379            if (!this->ambientSounds_.empty())
380            {
381                if (!this->ambientSounds_.front().second) // Not paused before
382                {
383                    this->ambientSounds_.front().first->doPlay();
384                }
385                this->fadeIn(this->ambientSounds_.front().first);
386            }
387        }
388        else
389        {
390            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
391            {
392                if (it->first == oldAmbient)
393                {
394                    this->fadeOut(oldAmbient);
395                    this->ambientSounds_.erase(it);
396                    break;
397                }
398            }
399        }
400    }
401
402    void SoundManager::pauseAmbientSound(AmbientSound* ambient)
403    {
404        if (ambient != NULL)
405        {
406            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
407            {
408                if (it->first == ambient)
409                {
410                    it->second = true;
411                    this->fadeOut(it->first);
412                    return;
413                }
414            }
415        }
416    }
417
418    void SoundManager::fadeIn(const SmartPtr<AmbientSound>& sound)
419    {
420        // If we're already fading out --> remove that
421        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); it++)
422        {
423            if (*it == sound)
424            {
425                this->fadeOutList_.erase(it);
426                break;
427            }
428        }
429        // No duplicate entries
430        if (std::find(this->fadeInList_.begin(), this->fadeInList_.end(), sound) == this->fadeInList_.end())
431            this->fadeInList_.push_back(sound);
432    }
433
434    void SoundManager::fadeOut(const SmartPtr<AmbientSound>& sound)
435    {
436        // If we're already fading in --> remove that
437        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeInList_.begin(); it != this->fadeInList_.end(); it++)
438        {
439            if (*it == sound)
440            {
441                this->fadeInList_.erase(it);
442                break;
443            }
444        }
445        // No duplicate entries
446        if (std::find(this->fadeOutList_.begin(), this->fadeOutList_.end(), sound) == this->fadeOutList_.end())
447            this->fadeOutList_.push_back(sound);
448    }
449
450    void SoundManager::processCrossFading(float dt)
451    {
452
453        // Hacky solution to the fade delay while loading a level.
454        if(dt > 0.2)
455        {
456            return;
457        }
458
459        // FADE IN
460        for (std::list<SmartPtr<AmbientSound> >::iterator it= this->fadeInList_.begin(); it != this->fadeInList_.end(); )
461        {
462            if ((*it)->getVolume() + this->crossFadeStep_*dt > 1.0f)
463            {
464                (*it)->setVolume(1.0f);
465                this->fadeInList_.erase(it++);
466            }
467            else
468            {
469                (*it)->setVolume((*it)->getVolume() + this->crossFadeStep_*dt);
470                ++it;
471            }
472        }
473
474        // FADE OUT
475        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); )
476        {
477            if ((*it)->getVolume() - this->crossFadeStep_*dt < 0.0f)
478            {
479                (*it)->setVolume(0.0f);
480
481                // If sound is in the ambient list --> pause
482                for (AmbientList::const_iterator it2 = this->ambientSounds_.begin(); it2 != this->ambientSounds_.end(); ++it2)
483                {
484                    if (it2->first == *it)
485                    {
486                        (*it)->doPause();
487                        break;
488                    }
489                }
490                // If not pause (by loop above for instance) --> stop
491                if (!(*it)->isPaused())
492                    (*it)->doStop();
493
494                this->fadeOutList_.erase(it++);
495            }
496            else
497            {
498                (*it)->setVolume((*it)->getVolume() - this->crossFadeStep_*dt);
499                ++it;
500            }
501        }
502    }
503
504    shared_ptr<SoundBuffer> SoundManager::getSoundBuffer(const std::string& filename)
505    {
506        shared_ptr<SoundBuffer> buffer;
507        // Check active or pooled buffers
508        SoundBufferMap::const_iterator it = this->soundBuffers_.find(filename);
509        if (it != this->soundBuffers_.end())
510        {
511            buffer = it->second;
512
513            // Remove from effects pool if not active used before
514            if (buffer->poolIterator_ != this->effectsPool_.end())
515            {
516                this->effectsPoolSize_ -= buffer->getSize();
517                this->effectsPool_.erase(buffer->poolIterator_);
518                buffer->poolIterator_ = this->effectsPool_.end();
519            }
520        }
521        else
522        {
523            try
524            {
525                buffer.reset(new SoundBuffer(filename, this->effectsPool_.end()));
526            }
527            catch (const std::exception& ex)
528            {
529                COUT(1) << ex.what() << std::endl;
530                return buffer;
531            }
532            this->soundBuffers_[filename] = buffer;
533        }
534        return buffer;
535    }
536
537    void SoundManager::releaseSoundBuffer(const shared_ptr<SoundBuffer>& buffer, bool bPoolBuffer)
538    {
539        // Check if others are still using the buffer
540        if (buffer.use_count() != 2)
541            return;
542        SoundBufferMap::iterator it = this->soundBuffers_.find(buffer->getFilename());
543        if (it != this->soundBuffers_.end())
544        {
545            if (bPoolBuffer)
546            {
547                // Pool already too large?
548                while (this->effectsPoolSize_ + it->second->getSize() > this->maxEffectsPoolSize_s && !this->effectsPool_.empty())
549                {
550                    shared_ptr<SoundBuffer> bufferDel = this->effectsPool_.back();
551                    this->effectsPoolSize_ -= bufferDel->getSize();
552                    bufferDel->poolIterator_ = this->effectsPool_.end();
553                    this->effectsPool_.pop_back();
554                    // Remove from buffer map too
555                    SoundBufferMap::iterator itDel = this->soundBuffers_.find(bufferDel->getFilename());
556                    if (itDel != this->soundBuffers_.end())
557                        this->soundBuffers_.erase(itDel);
558                }
559                // Put buffer into the pool
560                this->effectsPoolSize_ += it->second->getSize();
561                this->effectsPool_.push_front(it->second);
562                it->second->poolIterator_ = this->effectsPool_.begin();
563            }
564            else
565                this->soundBuffers_.erase(it);
566        }
567    }
568
569    ALuint SoundManager::getSoundSource(BaseSound* object)
570    {
571        if (!this->availableSoundSources_.empty())
572        {
573            ALuint source = this->availableSoundSources_.back();
574            this->availableSoundSources_.pop_back();
575            this->usedSoundSources_.push_back(std::make_pair(source, object));
576            return source;
577        }
578        else
579        {
580            if (this->usedSoundSources_.size() < this->maxSources_)
581            {
582                ALuint source;
583                alGenSources(1, &source);
584                // Try to create new sources (50% more, but at least one)
585                if (alIsSource(source) && !alGetError())
586                {
587                    this->usedSoundSources_.push_back(std::make_pair(source, object));
588                    return source;
589                }
590            }
591            // Return no source ID
592            ALuint source = 123456789;
593            while (alIsSource(++source));
594            return source;
595        }
596    }
597
598    void SoundManager::releaseSoundSource(ALuint source)
599    {
600#ifndef NDEBUG
601        for (std::vector<ALuint>::const_iterator it = this->availableSoundSources_.begin(); it != this->availableSoundSources_.end(); ++it)
602            assert((*it) != source);
603#endif
604        this->availableSoundSources_.push_back(source);
605        for (std::vector<std::pair<ALuint, BaseSound*> >::iterator it = this->usedSoundSources_.begin();
606            it != this->usedSoundSources_.end(); ++it)
607        {
608            if (it->first == source)
609            {
610                this->usedSoundSources_.erase(it);
611                break;
612            }
613        }
614        int used = std::max((unsigned int)(this->usedSoundSources_.size()), this->minSources_);
615        // Subtract those we added in the statement above trough std::max
616        int available = (int)this->availableSoundSources_.size() - (used - (int)this->usedSoundSources_.size());
617        // Delete sources again to free resources if appropriate (more than 50% more available than used)
618        int toDelete = available - used / 2;
619        while (toDelete-- > 0)
620        {
621            alDeleteSources(1, &this->availableSoundSources_.back());
622            if (alGetError())
623                COUT(1) << "Sound Error: Failed to delete a source --> lost forever" << std::endl;
624            this->availableSoundSources_.pop_back();
625        }
626    }
627
628    unsigned int SoundManager::createSoundSources(unsigned int n)
629    {
630        unsigned int count = this->availableSoundSources_.size() + this->usedSoundSources_.size();
631        while (count < this->maxSources_ && count <= n)
632        {
633            ALuint source;
634            alGenSources(1, &source);
635            if (alIsSource(source) && !alGetError())
636                this->availableSoundSources_.push_back(source);
637            else
638                break;
639            ++count;
640        }
641        return count - this->availableSoundSources_.size() - this->usedSoundSources_.size();
642    }
643}
Note: See TracBrowser for help on using the repository browser.