Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 7286 was 7285, checked in by bensch, 19 years ago

orxonox/trunk: less output

File size: 11.2 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 *  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
58/**
59 *  the singleton reference to this class
60*/
61SoundEngine* SoundEngine::singletonRef = NULL;
62
63/**
64 *  standard deconstructor
65 */
66SoundEngine::~SoundEngine ()
67{
68  // deleting all the SoundSources
69  if(this->sourceList != NULL)
70  {
71    while (this->sourceList->size() > 0)
72      delete dynamic_cast<SoundSource*>(this->sourceList->front());
73  }
74
75  while(!this->ALSources.empty())
76  {
77    alDeleteSources(1, &this->ALSources.top());
78    this->ALSources.pop();
79  }
80
81  // deleting all the SoundBuffers
82  if (this->bufferList != NULL)
83  {
84    while(this->bufferList->size() > 0)
85      ResourceManager::getInstance()->unload(dynamic_cast<SoundBuffer*>(this->bufferList->front()));
86  }
87
88  // removing openAL from AudioResource
89  //! @todo this should be terminated through alc
90  //alutExit();
91
92  SoundEngine::singletonRef = NULL;
93}
94
95/**
96 * loads the settings of the SoundEngine from an ini-file
97 */
98void SoundEngine::loadSettings()
99{
100  MultiType channels = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_AUDIO_CHANNELS, "32");
101  this->maxSourceCount = channels.getInt();
102
103  MultiType effectsVolume = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_EFFECTS_VOLUME, "80");
104  this->effectsVolume = effectsVolume.getFloat()/100.0;
105
106  MultiType musicVolume = Preferences::getInstance()->getString(CONFIG_SECTION_AUDIO, CONFIG_NAME_MUSIC_VOLUME, "75");
107  this->musicVolume = musicVolume.getFloat()/100.0;
108}
109
110/**
111 *  creates a new SoundSource.
112 * @param fileName The Name to load the SoundBuffer from
113 * @param sourceNode The sourceNode to bind this SoundSource to.
114 * @returns The newly created SoundSource
115
116   acctualy this is nothing more than a wrapper around the ResourceManager.
117*/
118SoundSource* SoundEngine::createSource(const std::string& fileName, PNode* sourceNode)
119{
120  return new SoundSource(sourceNode, (SoundBuffer*)ResourceManager::getInstance()->load(fileName, WAV, RP_LEVEL));
121}
122
123/**
124 *  Sets the doppler values of openAL
125 * @param dopplerFactor the extent of the doppler-effect
126 * @param dopplerVelocity the Speed the sound travels
127*/
128void SoundEngine::setDopplerValues(ALfloat dopplerFactor, ALfloat dopplerVelocity)
129{
130  alDopplerFactor(dopplerFactor);
131  this->checkError("Setting Doppler Factor", __LINE__);
132
133  alDopplerVelocity(dopplerVelocity);
134  this->checkError("Setting Doppler Velocity", __LINE__);
135}
136
137
138void SoundEngine::popALSource(ALuint& source)
139{
140  assert (source == 0);
141
142  /// @TODO try to create more sources if needed
143  if (!this->ALSources.empty())
144  {
145    source = this->ALSources.top();
146    this->ALSources.pop();
147  }
148
149}
150
151
152/**
153 *  updates all The positions, Directions and Velocities of all Sounds
154*/
155void SoundEngine::update()
156{
157
158  // updating the Listeners Position
159  if (likely(this->listener != NULL))
160  {
161    alListener3f(AL_POSITION,
162                 this->listener->getAbsCoor().x,
163                 this->listener->getAbsCoor().y,
164                 this->listener->getAbsCoor().z);
165    alListener3f(AL_VELOCITY,
166                 this->listener->getVelocity().x,
167                 this->listener->getVelocity().y,
168                 this->listener->getVelocity().z);
169    Vector absDirV = this->listener->getAbsDirV();
170    ALfloat orientation [6] = {1,0,0, absDirV.x, absDirV.y, absDirV.z};
171    alListenerfv(AL_ORIENTATION, orientation);
172  }
173  else
174    PRINTF(2)("no listener defined\n");
175
176  // updating all the Sources positions
177  if (likely(this->sourceList != NULL || (this->sourceList = ClassList::getList(CL_SOUND_SOURCE)) != NULL))
178  {
179    list<BaseObject*>::const_iterator sourceIT;
180    SoundSource* source;
181    for (sourceIT = this->sourceList->begin(); sourceIT != this->sourceList->end(); sourceIT++)
182    {
183      source = static_cast<SoundSource*>(*sourceIT);
184      if (source->isPlaying())
185      {
186        int play = 0x000;
187        alGetSourcei(source->getID(), AL_SOURCE_STATE, &play);
188        if(play == AL_PLAYING)
189        {
190          if (likely(source->getNode() != NULL))
191          {
192            alSource3f(source->getID(), AL_POSITION,
193                       source->getNode()->getAbsCoor().x,
194                       source->getNode()->getAbsCoor().y,
195                       source->getNode()->getAbsCoor().z);
196            alSource3f(source->getID(), AL_VELOCITY,
197                       source->getNode()->getVelocity().x,
198                       source->getNode()->getVelocity().y,
199                       source->getNode()->getVelocity().z);
200          }
201
202        }
203        else
204        {
205          source->stop();
206        }
207      }
208    }
209  }
210}
211
212/**
213 *  Removes all the Buffers that are not anymore needed by any Sources
214*/
215void SoundEngine::flushUnusedBuffers()
216{
217  /// FIXME
218  /*  if(this->sourceList && this->bufferList)
219    {
220      tIterator<BaseObject>* bufferIterator = this->bufferList->getIterator();
221      SoundBuffer* enumBuffer = (SoundBuffer*)bufferIterator->firstElement();
222      while (enumBuffer)
223      {
224        tIterator<BaseObject>* sourceIterator = this->sourceList->getIterator();
225        SoundSource* enumSource = (SoundSource*)sourceIterator->firstElement();
226        while (enumSource)
227        {
228          if (enumBuffer == enumSource->getBuffer())
229            break;
230          enumSource = (SoundSource*)sourceIterator->nextElement();
231        }
232        delete sourceIterator;
233        if (enumSource == NULL)
234          ResourceManager::getInstance()->unload(enumBuffer);
235        enumBuffer = (SoundBuffer*)bufferIterator->nextElement();
236      }
237      delete bufferIterator;
238  }*/ /// FIXME
239}
240
241/**
242 * flushes all the Buffers
243 * deletes them from the BufferList, and also removes them via the ResourceManager.
244 */
245void SoundEngine::flushAllBuffers()
246{
247  if (this->bufferList)
248  {
249    while (this->bufferList->size() > 0)
250      ResourceManager::getInstance()->unload(static_cast<SoundBuffer*>(this->bufferList->front()), RP_LEVEL);
251  }
252}
253
254/**
255 * deletes all the Sources.
256 */
257void SoundEngine::flushAllSources()
258{
259  if (this->sourceList)
260  {
261    while(this->sourceList->size() > 0)
262      delete this->sourceList->front();
263  }
264}
265
266/**
267 *  initializes Audio in general
268*/
269bool SoundEngine::initAudio()
270{
271  //   ALenum result;
272  //   PRINTF(3)("Initialisazing openAL sound engine\n");
273  //   const char* defaultDevice =(const char*) alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
274  //   const char* deviceList = (const char*)alcGetString(NULL,ALC_DEVICE_SPECIFIER);
275  //   const char* devWalk = deviceList;
276  //   //  if (alcIsExtensionPresent(NULL, (const ALCchar*)"ALC_ENUMERATION_EXT") == AL_TRUE)
277  //   { // try out enumeration extension
278  //     PRINTF(3)("Enumeration-extension found\n");
279  //
280  //     PRINTF(3)("Default device: %s\n", defaultDevice);
281  //     do
282  //     {
283  //       PRINTF(3)("%s\n", devWalk);
284  //       devWalk += strlen(devWalk)+1;
285  //     }
286  //     while (devWalk[0] != '\0');
287  //  }
288
289  // INITIALIZING THE DEVICE:
290  //   char deviceName[] =
291  //   #ifdef __WIN32__
292  //     "Direct3D";
293  //   #else
294  //     "'( ( devices '( native null ) ) )";
295  //   #endif
296
297  this->device = alcOpenDevice(NULL);
298  this->checkALCError("opening Device", __LINE__);
299
300  PRINTF(4)("Audio-Specifier: %s\n", (const char*)alcGetString(this->device, ALC_DEVICE_SPECIFIER));
301  PRINTF(4)("Audio-Extensions: %s\n", (const char*)alcGetString(this->device, ALC_EXTENSIONS));
302
303
304  this->context = alcCreateContext(this->device, NULL);
305  this->checkALCError("creating Context", __LINE__);
306
307  alcMakeContextCurrent(this->context);
308  this->checkALCError("making Context Current", __LINE__);
309  // #endif
310
311  printf ("===== SOURCECOUNT: %d\n", this->maxSourceCount);
312  this->setDopplerValues(SOUND_DOPPLER_FACTOR, SOUND_DOPPLER_VELOCITY);
313  this->allocateSources(this->maxSourceCount);
314}
315
316
317/**
318 * Allocates openAL sources
319 * @param count how many sources to allocate
320 * @returns true on success, false if at least one source could not be allocated
321 */
322bool SoundEngine::allocateSources(unsigned int count)
323{
324  unsigned int failCount = 0;
325  for (unsigned int i = 0; i < count; i++)
326  {
327    ALuint source = 0;
328
329    alGenSources(1, &source);
330    this->checkError("allocate Source", __LINE__);
331    if (!alIsSource(source))
332    {
333      PRINTF(5)("not allocated Source\n");
334      failCount++;
335      continue;
336    }
337
338    alSourcef (source, AL_PITCH,    1.0      );
339    alSourcef (source, AL_GAIN,     this->getEffectsVolume() );
340    alSourcei (source, AL_LOOPING,  AL_FALSE );
341    this->ALSources.push(source);
342  }
343  if (failCount == 0)
344    return true;
345  else
346  {
347    PRINTF(2)("Failed to allocate %d of %d SoundSources\n", failCount, count);
348  }
349}
350
351bool SoundEngine::checkError(const std::string& error, unsigned int line)
352{
353  ALenum errorCode;
354  if ((errorCode = alGetError()) != AL_NO_ERROR)
355  {
356    PRINTF(1)("Error %s (line:%d): '%s'\n", error.c_str(), line, SoundEngine::getALErrorString(errorCode));
357    return false;
358  }
359  else
360    return true;
361}
362
363bool SoundEngine::checkALCError(const std::string& error, unsigned int line)
364{
365  ALenum errorCode;
366  if ((errorCode = alcGetError(this->device)) != ALC_NO_ERROR)
367  {
368    PRINTF(1)("Error %s (line:%d): '%s'\n", error.c_str(), line, SoundEngine::getALCErrorString(errorCode));
369    return false;
370  }
371  else
372    return true;
373}
374
375
376
377void SoundEngine::listDevices()
378{
379  printf("%s\n",(const char*)alcGetString(NULL, ALC_DEVICE_SPECIFIER));
380}
381
382/**
383 *  Transforms AL-errors into something readable
384 * @param err The error found
385*/
386const char* SoundEngine::getALErrorString(ALenum err)
387{
388  switch(err)
389  {
390    case AL_NO_ERROR:
391      return ("AL_NO_ERROR");
392    case AL_INVALID_NAME:
393      return ("AL_INVALID_NAME");
394    case AL_INVALID_ENUM:
395      return ("AL_INVALID_ENUM");
396    case AL_INVALID_VALUE:
397      return ("AL_INVALID_VALUE");
398    case AL_INVALID_OPERATION:
399      return ("AL_INVALID_OPERATION");
400    case AL_OUT_OF_MEMORY:
401      return ("AL_OUT_OF_MEMORY");
402  };
403}
404
405
406const char* SoundEngine::getALCErrorString(ALenum err)
407{
408  switch(err)
409  {
410    case ALC_NO_ERROR:
411      return ("AL_NO_ERROR");
412    case ALC_INVALID_DEVICE:
413      return ("ALC_INVALID_DEVICE");
414    case ALC_INVALID_CONTEXT:
415      return("ALC_INVALID_CONTEXT");
416    case ALC_INVALID_ENUM:
417      return("ALC_INVALID_ENUM");
418    case ALC_INVALID_VALUE:
419      return ("ALC_INVALID_VALUE");
420    case ALC_OUT_OF_MEMORY:
421      return("ALC_OUT_OF_MEMORY");
422  };
423}
424
Note: See TracBrowser for help on using the repository browser.