Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/sound/sound_engine.cc @ 7315

Last change on this file since 7315 was 7299, checked in by bensch, 19 years ago

orxonox/trunk: some nice Class-Stuff

File size: 11.3 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14
15   code has been taken from http://www.devmaster.net/articles.php?catID=6
16   The code has been applied to our needs, and many things have been changed.
17*/
18
19#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_SOUND
20
21#include "sound_engine.h"
22
23#include "class_list.h"
24
25#include "p_node.h"
26#include "util/loading/resource_manager.h"
27#include "debug.h"
28#include "util/preferences.h"
29#include "globals.h"
30
31using namespace std;
32
33
34//////////////////
35/* SOUND-ENGINE */
36//////////////////
37/**
38 * @brief standard constructor
39*/
40SoundEngine::SoundEngine ()
41{
42  this->setClassID(CL_SOUND_ENGINE, "SoundEngine");
43  this->setName("SoundEngine");
44
45  this->listener = NULL;
46  this->bufferList = NULL;
47  this->sourceList = NULL;
48
49  this->device = NULL;
50  this->context = NULL;
51
52  this->maxSourceCount = 32;
53
54  this->effectsVolume = .80;
55  this->musicVolume = .75;
56
57  this->sourceMutex = SDL_CreateMutex();
58}
59
60/**
61 * @brief the singleton reference to this class
62*/
63SoundEngine* SoundEngine::singletonRef = NULL;
64
65/**
66 * @brief standard destructor
67 */
68SoundEngine::~SoundEngine ()
69{
70  // deleting all the SoundSources
71  if(this->sourceList != NULL)
72  {
73    while (this->sourceList->size() > 0)
74      delete static_cast<SoundSource*>(this->sourceList->front());
75  }
76
77  while(!this->ALSources.empty())
78  {
79    if (alIsSource(this->ALSources.top()))
80    {
81      alDeleteSources(1, &this->ALSources.top());
82      SoundEngine::checkError("Deleting Source", __LINE__);
83    }
84    else
85      PRINTF(1)("%d is not a Source\n", this->ALSources.top());
86
87    this->ALSources.pop();
88  }
89
90  // deleting all the SoundBuffers
91  if (this->bufferList != NULL)
92  {
93    while(this->bufferList->size() > 0)
94      ResourceManager::getInstance()->unload(static_cast<SoundBuffer*>(this->bufferList->front()));
95  }
96
97  // removing openAL from AudioResource
98  //! @todo this should be terminated through alc
99  //alutExit();
100
101  SDL_DestroyMutex(this->sourceMutex);
102
103  SoundEngine::singletonRef = NULL;
104}
105
106/**
107 * @brief loads the settings of the SoundEngine from an ini-file
108 */
109void SoundEngine::loadSettings()
110{
111  MultiType channels = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_AUDIO_CHANNELS, "32");
112  this->maxSourceCount = channels.getInt();
113
114  MultiType effectsVolume = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_EFFECTS_VOLUME, "80");
115  this->effectsVolume = effectsVolume.getFloat()/100.0;
116
117  MultiType musicVolume = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_MUSIC_VOLUME, "75");
118  this->musicVolume = musicVolume.getFloat()/100.0;
119}
120
121/**
122 * @brief creates a new SoundSource.
123 * @param fileName The Name to load the SoundBuffer from
124 * @param sourceNode The sourceNode to bind this SoundSource to.
125 * @returns The newly created SoundSource
126
127   acctualy this is nothing more than a wrapper around the ResourceManager.
128*/
129SoundSource* SoundEngine::createSource(const std::string& fileName, PNode* sourceNode)
130{
131  return new SoundSource(sourceNode, (SoundBuffer*)ResourceManager::getInstance()->load(fileName, WAV, RP_LEVEL));
132}
133
134/**
135 * @brief Sets the doppler values of openAL
136 * @param dopplerFactor the extent of the doppler-effect
137 * @param dopplerVelocity the Speed the sound travels
138*/
139void SoundEngine::setDopplerValues(ALfloat dopplerFactor, ALfloat dopplerVelocity)
140{
141  alDopplerFactor(dopplerFactor);
142  this->checkError("Setting Doppler Factor", __LINE__);
143
144  alDopplerVelocity(dopplerVelocity);
145  this->checkError("Setting Doppler Velocity", __LINE__);
146}
147
148
149/**
150 * @brief retrieves an OpenAL Source from the availiable Sources.
151 * @param source the Source to fill with the Value.
152 */
153void SoundEngine::popALSource(ALuint& source)
154{
155  assert (source == 0);
156
157  /// @TODO try to create more sources if needed
158  if (!this->ALSources.empty())
159  {
160    SDL_mutexP(this->sourceMutex);
161    source = this->ALSources.top();
162    this->ALSources.pop();
163    SDL_mutexV(this->sourceMutex);
164  }
165}
166
167
168/**
169 * @brief Pushes an OpenAL Source back into the Stack of known sources
170 * @param source the Source to push onto the top of the SourceStack
171 */
172void SoundEngine::pushALSource(ALuint& source)
173{
174  if (source != 0)
175  {
176    SDL_mutexP(this->sourceMutex);
177    this->ALSources.push(source);
178    SDL_mutexV(this->sourceMutex);
179  }
180};
181
182
183/**
184 * @brief updates all The positions, Directions and Velocities of all Sounds
185 */
186void SoundEngine::update()
187{
188  // updating the Listeners Position
189  if (likely(this->listener != NULL))
190  {
191    alListener3f(AL_POSITION,
192                 this->listener->getAbsCoor().x,
193                 this->listener->getAbsCoor().y,
194                 this->listener->getAbsCoor().z);
195    alListener3f(AL_VELOCITY,
196                 this->listener->getVelocity().x,
197                 this->listener->getVelocity().y,
198                 this->listener->getVelocity().z);
199    Vector absDirV = this->listener->getAbsDirV();
200    ALfloat orientation [6] = {1,0,0, absDirV.x, absDirV.y, absDirV.z};
201    alListenerfv(AL_ORIENTATION, orientation);
202    SoundEngine::checkError("SoundEngine::update() - Listener Error", __LINE__);
203  }
204  else
205    PRINTF(2)("no listener defined\n");
206
207  // updating all the Sources positions
208  if (likely(this->sourceList != NULL || (this->sourceList = ClassList::getList(CL_SOUND_SOURCE)) != NULL))
209  {
210    list<BaseObject*>::const_iterator sourceIT;
211    SoundSource* source;
212    for (sourceIT = this->sourceList->begin(); sourceIT != this->sourceList->end(); sourceIT++)
213    {
214      source = static_cast<SoundSource*>(*sourceIT);
215      if (source->isPlaying())
216      {
217        int play = 0x000;
218        alGetSourcei(source->getID(), AL_SOURCE_STATE, &play);
219        if (DEBUG > 2)
220          SoundEngine::checkError("SoundEngine::update() Play", __LINE__);
221        if(play == AL_PLAYING)
222        {
223          if (likely(source->getNode() != NULL))
224          {
225            alSource3f(source->getID(), AL_POSITION,
226                       source->getNode()->getAbsCoor().x,
227                       source->getNode()->getAbsCoor().y,
228                       source->getNode()->getAbsCoor().z);
229            if (DEBUG > 2)
230              SoundEngine::checkError("SoundEngine::update() Set Source Position", __LINE__);
231            alSource3f(source->getID(), AL_VELOCITY,
232                       source->getNode()->getVelocity().x,
233                       source->getNode()->getVelocity().y,
234                       source->getNode()->getVelocity().z);
235            if (DEBUG > 2)
236              SoundEngine::checkError("SoundEngine::update() Set Source Velocity", __LINE__);
237          }
238        }
239        else
240        {
241          source->stop();
242        }
243      }
244    }
245  }
246  SoundEngine::checkError("SoundEngine::update()", __LINE__);
247}
248
249
250/**
251 *  initializes Audio in general
252*/
253bool SoundEngine::initAudio()
254{
255  //   ALenum result;
256  //   PRINTF(3)("Initialisazing openAL sound engine\n");
257  //   const char* defaultDevice =(const char*) alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
258  //   const char* deviceList = (const char*)alcGetString(NULL,ALC_DEVICE_SPECIFIER);
259  //   const char* devWalk = deviceList;
260  //   //  if (alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE)
261  //   { // try out enumeration extension
262  //     PRINTF(3)("Enumeration-extension found\n");
263  //
264  //     PRINTF(3)("Default device: %s\n", defaultDevice);
265  //     do
266  //     {
267  //       PRINTF(3)("%s\n", devWalk);
268  //       devWalk += strlen(devWalk)+1;
269  //     }
270  //     while (devWalk[0] != '\0');
271  //  }
272
273  // INITIALIZING THE DEVICE:
274  //   char deviceName[] =
275  //   #ifdef __WIN32__
276  //     "Direct3D";
277  //   #else
278  //     "'( ( devices '( native null ) ) )";
279  //   #endif
280
281  this->device = alcOpenDevice(NULL);
282  this->checkALCError("opening Device", __LINE__);
283
284  PRINTF(4)("Audio-Specifier: %s\n", (const char*)alcGetString(this->device, ALC_DEVICE_SPECIFIER));
285  PRINTF(4)("Audio-Extensions: %s\n", (const char*)alcGetString(this->device, ALC_EXTENSIONS));
286
287
288  this->context = alcCreateContext(this->device, NULL);
289  this->checkALCError("creating Context", __LINE__);
290
291  alcMakeContextCurrent(this->context);
292  this->checkALCError("making Context Current", __LINE__);
293  // #endif
294
295  this->setDopplerValues(SOUND_DOPPLER_FACTOR, SOUND_DOPPLER_VELOCITY);
296  this->allocateSources(this->maxSourceCount);
297  this->checkError("Allocating Sources", __LINE__);
298}
299
300
301/**
302 * Allocates openAL sources
303 * @param count how many sources to allocate
304 * @returns true on success, false if at least one source could not be allocated
305 */
306bool SoundEngine::allocateSources(unsigned int count)
307{
308  unsigned int failCount = 0;
309  for (unsigned int i = 0; i < count; i++)
310  {
311    ALuint source = 0;
312
313    alGenSources(1, &source);
314    this->checkError("allocate Source", __LINE__);
315    if (!alIsSource(source))
316    {
317      PRINTF(5)("not allocated Source\n");
318      failCount++;
319      continue;
320    }
321
322    alSourcef (source, AL_PITCH,    1.0      );
323    alSourcef (source, AL_GAIN,     this->getEffectsVolume() );
324    alSourcei (source, AL_LOOPING,  AL_FALSE );
325    this->ALSources.push(source);
326  }
327  if (failCount == 0)
328    return true;
329  else
330  {
331    PRINTF(2)("Failed to allocate %d of %d SoundSources\n", failCount, count);
332  }
333}
334
335/**
336 * @brief checks for an OpenAL error
337 * @param error the ErrorMessage to display
338 * @param line on what line did the error occure.
339 */
340bool SoundEngine::checkError(const std::string& error, unsigned int line)
341{
342  ALenum errorCode;
343  if ((errorCode = alGetError()) != AL_NO_ERROR)
344  {
345    PRINTF(1)("Error %s (line:%d): '%s'\n", error.c_str(), line, SoundEngine::getALErrorString(errorCode));
346    return false;
347  }
348  else
349    return true;
350}
351
352/**
353 * @brief check for an ALC error.
354 * @brief error the Error-String to display
355 * @param line on that line, the error occured (debugging mode).
356 */
357bool SoundEngine::checkALCError(const std::string& error, unsigned int line)
358{
359  ALenum errorCode;
360  if ((errorCode = alcGetError(this->device)) != ALC_NO_ERROR)
361  {
362    PRINTF(1)("Error %s (line:%d): '%s'\n", error.c_str(), line, SoundEngine::getALCErrorString(errorCode));
363    return false;
364  }
365  else
366    return true;
367}
368
369
370
371void SoundEngine::listDevices()
372{
373  printf("%s\n",(const char*)alcGetString(NULL, ALC_DEVICE_SPECIFIER));
374}
375
376/**
377 *  Transforms AL-errors into something readable
378 * @param err The error found
379*/
380const char* SoundEngine::getALErrorString(ALenum err)
381{
382  switch(err)
383  {
384    case AL_NO_ERROR:
385      return ("AL_NO_ERROR");
386    case AL_INVALID_NAME:
387      return ("AL_INVALID_NAME");
388    case AL_INVALID_ENUM:
389      return ("AL_INVALID_ENUM");
390    case AL_INVALID_VALUE:
391      return ("AL_INVALID_VALUE");
392    case AL_INVALID_OPERATION:
393      return ("AL_INVALID_OPERATION");
394    case AL_OUT_OF_MEMORY:
395      return ("AL_OUT_OF_MEMORY");
396  };
397}
398
399
400const char* SoundEngine::getALCErrorString(ALenum err)
401{
402  switch(err)
403  {
404    case ALC_NO_ERROR:
405      return ("AL_NO_ERROR");
406    case ALC_INVALID_DEVICE:
407      return ("ALC_INVALID_DEVICE");
408    case ALC_INVALID_CONTEXT:
409      return("ALC_INVALID_CONTEXT");
410    case ALC_INVALID_ENUM:
411      return("ALC_INVALID_ENUM");
412    case ALC_INVALID_VALUE:
413      return ("ALC_INVALID_VALUE");
414    case ALC_OUT_OF_MEMORY:
415      return("ALC_OUT_OF_MEMORY");
416  };
417}
Note: See TracBrowser for help on using the repository browser.