]> git.mxchange.org Git - simgear.git/blob - simgear/sound/sample_group.cxx
fix mingw
[simgear.git] / simgear / sound / sample_group.cxx
1 // sample_group.cxx -- Manage a group of samples relative to a base position
2 //
3 // Written for the new SoundSystem by Erik Hofman, October 2009
4 //
5 // Copyright (C) 2009 Erik Hofman <erik@ehofman.com>
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software Foundation,
19 // Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <simgear_config.h>
25 #endif
26
27 #include <cassert>
28 #include <simgear/compiler.h>
29 #include <simgear/sg_inlines.h>
30 #include <simgear/debug/logstream.hxx>
31
32 #include "soundmgr_openal.hxx"
33 #include "soundmgr_openal_private.hxx"
34 #include "sample_group.hxx"
35
36 using std::string;
37 using std::isnan;
38
39 bool isNaN(float *v) {
40    return (isnan(v[0]) || isnan(v[1]) || isnan(v[2]));
41 }
42
43 SGSampleGroup::SGSampleGroup () :
44     _smgr(NULL),
45     _refname(""),
46     _active(false),
47     _changed(false),
48     _pause(false),
49     _volume(1.0),
50     _tied_to_listener(false),
51     _velocity(SGVec3d::zeros()),
52     _orientation(SGQuatd::zeros())
53 {
54     _samples.clear();
55 }
56
57 SGSampleGroup::SGSampleGroup ( SGSoundMgr *smgr, const string &refname ) :
58     _smgr(smgr),
59     _refname(refname),
60     _active(false), 
61     _changed(false),
62     _pause(false),
63     _volume(1.0),
64     _tied_to_listener(false),
65     _velocity(SGVec3d::zeros()),
66     _orientation(SGQuatd::zeros())
67 {
68     _smgr->add(this, refname);
69     _samples.clear();
70 }
71
72 SGSampleGroup::~SGSampleGroup ()
73 {
74     _active = false;
75     stop();
76     _smgr = 0;
77 }
78
79 static bool is_sample_stopped(SGSoundSample *sample)
80 {
81 #ifdef ENABLE_SOUND
82     assert(sample->is_valid_source());
83     unsigned int source = sample->get_source();
84     int result;
85     alGetSourcei( source, AL_SOURCE_STATE, &result );
86     return (result == AL_STOPPED);
87 #else
88     return true;
89 #endif
90 }
91
92 void SGSampleGroup::cleanup_removed_samples()
93 {
94     // Delete any OpenAL buffers that might still be in use.
95     unsigned int size = _removed_samples.size();
96     for (unsigned int i=0; i<size; ) {
97         SGSoundSample *sample = _removed_samples[i];
98         bool stopped = is_sample_stopped(sample);
99         
100         if ( sample->is_valid_source() ) {
101             int source = sample->get_source();
102             
103             if ( sample->is_looping() && !stopped) {
104 #ifdef ENABLE_SOUND
105                 alSourceStop( source );
106 #endif
107                 stopped = is_sample_stopped(sample);
108             }
109             
110             if ( stopped ) {
111                 sample->no_valid_source();
112                 _smgr->release_source( source );
113             }
114         }
115         
116         if ( stopped ) {
117             sample->stop();
118             if (( !sample->is_queue() )&&
119                 (sample->is_valid_buffer()))
120             {
121                 _smgr->release_buffer(sample);
122             }
123             _removed_samples.erase( _removed_samples.begin()+i );
124             size--;
125             continue;
126         }
127         i++;
128     }
129 }
130
131 void SGSampleGroup::start_playing_sample(SGSoundSample *sample)
132 {
133 #ifdef ENABLE_SOUND
134     //
135     // a request to start playing a sound has been filed.
136     //
137     ALuint source = _smgr->request_source();
138     if (alIsSource(source) == AL_FALSE ) {
139         return;
140     }
141     
142     sample->set_source( source );
143     update_sample_config( sample );
144     ALboolean looping = sample->is_looping() ? AL_TRUE : AL_FALSE;
145     
146     if ( !sample->is_queue() )
147     {
148         ALuint buffer = _smgr->request_buffer(sample);
149         if (buffer == SGSoundMgr::FAILED_BUFFER ||
150             buffer == SGSoundMgr::NO_BUFFER)
151         {
152             _smgr->release_source(source);
153             return;
154         }
155         
156         // start playing the sample
157         buffer = sample->get_buffer();
158         if ( alIsBuffer(buffer) == AL_TRUE )
159         {
160             alSourcei( source, AL_BUFFER, buffer );
161             testForALError("assign buffer to source");
162         } else
163             SG_LOG( SG_SOUND, SG_ALERT, "No such buffer!");
164     }
165     
166     alSourcef( source, AL_ROLLOFF_FACTOR, 0.3 );
167     alSourcei( source, AL_LOOPING, looping );
168     alSourcei( source, AL_SOURCE_RELATIVE, AL_FALSE );
169     alSourcePlay( source );
170     testForALError("sample play");
171 #endif
172 }
173
174 void SGSampleGroup::check_playing_sample(SGSoundSample *sample)
175 {
176     // check if the sound has stopped by itself
177     
178     if (is_sample_stopped(sample)) {
179         // sample is stopped because it wasn't looping
180         sample->stop();
181         sample->no_valid_source();
182         _smgr->release_source( sample->get_source() );
183         _smgr->release_buffer( sample );
184         remove( sample->get_sample_name() );
185     } else if ( sample->has_changed() ) {
186         if ( !sample->is_playing() ) {
187             // a request to stop playing the sound has been filed.
188             sample->stop();
189             sample->no_valid_source();
190             _smgr->release_source( sample->get_source() );
191         } else if ( _smgr->has_changed() ) {
192             update_sample_config( sample );
193         }
194     }
195 }
196
197 void SGSampleGroup::update( double dt ) {
198
199     if ( !_active || _pause ) return;
200
201     testForALError("start of update!!\n");
202
203     cleanup_removed_samples();
204     
205     // Update the position and orientation information for all samples.
206     if ( _changed || _smgr->has_changed() ) {
207         update_pos_and_orientation();
208         _changed = false;
209     }
210
211     sample_map_iterator sample_current = _samples.begin();
212     sample_map_iterator sample_end = _samples.end();
213     for ( ; sample_current != sample_end; ++sample_current ) {
214         SGSoundSample *sample = sample_current->second;
215
216         if ( !sample->is_valid_source() && sample->is_playing() && !sample->test_out_of_range()) {
217             start_playing_sample(sample);
218
219         } else if ( sample->is_valid_source() ) {
220             check_playing_sample(sample);
221         }
222         testForALError("update");
223     }
224 }
225
226 // add a sound effect, return true if successful
227 bool SGSampleGroup::add( SGSharedPtr<SGSoundSample> sound, const string& refname ) {
228
229     sample_map_iterator sample_it = _samples.find( refname );
230     if ( sample_it != _samples.end() ) {
231         // sample name already exists
232         return false;
233     }
234
235     _samples[refname] = sound;
236     return true;
237 }
238
239
240 // remove a sound effect, return true if successful
241 bool SGSampleGroup::remove( const string &refname ) {
242
243     sample_map_iterator sample_it = _samples.find( refname );
244     if ( sample_it == _samples.end() ) {
245         // sample was not found
246         return false;
247     }
248
249     if ( sample_it->second->is_valid_buffer() )
250         _removed_samples.push_back( sample_it->second );
251
252     _samples.erase( sample_it );
253
254     return true;
255 }
256
257
258 // return true of the specified sound exists in the sound manager system
259 bool SGSampleGroup::exists( const string &refname ) {
260     sample_map_iterator sample_it = _samples.find( refname );
261     if ( sample_it == _samples.end() ) {
262         // sample was not found
263         return false;
264     }
265
266     return true;
267 }
268
269
270 // return a pointer to the SGSoundSample if the specified sound exists
271 // in the sound manager system, otherwise return NULL
272 SGSoundSample *SGSampleGroup::find( const string &refname ) {
273     sample_map_iterator sample_it = _samples.find( refname );
274     if ( sample_it == _samples.end() ) {
275         // sample was not found
276         return NULL;
277     }
278
279     return sample_it->second;
280 }
281
282
283 void
284 SGSampleGroup::stop ()
285 {
286     _pause = true;
287     sample_map_iterator sample_current = _samples.begin();
288     sample_map_iterator sample_end = _samples.end();
289     for ( ; sample_current != sample_end; ++sample_current ) {
290         SGSoundSample *sample = sample_current->second;
291
292         if ( sample->is_valid_source() ) {
293 #ifdef ENABLE_SOUND
294             ALint source = sample->get_source();
295             if ( sample->is_playing() ) {
296                 alSourceStop( source );
297                 testForALError("stop");
298             }
299             _smgr->release_source( source );
300 #endif
301             sample->no_valid_source();
302         }
303
304         if ( sample->is_valid_buffer() ) {
305             _smgr->release_buffer( sample );
306             sample->no_valid_buffer();
307         }
308     }
309 }
310
311 // stop playing all associated samples
312 void
313 SGSampleGroup::suspend ()
314 {
315     if (_active && _pause == false) {
316         _pause = true;
317         sample_map_iterator sample_current = _samples.begin();
318         sample_map_iterator sample_end = _samples.end();
319         for ( ; sample_current != sample_end; ++sample_current ) {
320 #ifdef ENABLE_SOUND
321             SGSoundSample *sample = sample_current->second;
322             if ( sample->is_valid_source() && sample->is_playing() ) {
323                 alSourcePause( sample->get_source() );
324             }
325 #endif
326         }
327         testForALError("suspend");
328     }
329 }
330
331 // resume playing all associated samples
332 void
333 SGSampleGroup::resume ()
334 {
335     if (_active && _pause == true) {
336 #ifdef ENABLE_SOUND
337         sample_map_iterator sample_current = _samples.begin();
338         sample_map_iterator sample_end = _samples.end();
339         for ( ; sample_current != sample_end; ++sample_current ) {
340             SGSoundSample *sample = sample_current->second;
341             if ( sample->is_valid_source() && sample->is_playing() ) {
342                 alSourcePlay( sample->get_source() );
343             }
344         }
345         testForALError("resume");
346 #endif
347         _pause = false;
348     }
349 }
350
351
352 // tell the scheduler to play the indexed sample in a continuous loop
353 bool SGSampleGroup::play( const string &refname, bool looping = false ) {
354     SGSoundSample *sample = find( refname );
355
356     if ( sample == NULL ) {
357         return false;
358     }
359
360     sample->play( looping );
361     return true;
362 }
363
364
365 // return true of the specified sound is currently being played
366 bool SGSampleGroup::is_playing( const string& refname ) {
367     SGSoundSample *sample = find( refname );
368
369     if ( sample == NULL ) {
370         return false;
371     }
372
373     return ( sample->is_playing() ) ? true : false;
374 }
375
376 // immediate stop playing the sound
377 bool SGSampleGroup::stop( const string& refname ) {
378     SGSoundSample *sample  = find( refname );
379
380     if ( sample == NULL ) {
381         return false;
382     }
383
384     sample->stop();
385     return true;
386 }
387
388 void SGSampleGroup::set_volume( float vol )
389 {
390     if (vol > _volume*1.01 || vol < _volume*0.99) {
391         _volume = vol;
392         SG_CLAMP_RANGE(_volume, 0.0f, 1.0f);
393         _changed = true;
394     }
395 }
396
397 // set the source position and orientation of all managed sounds
398 void SGSampleGroup::update_pos_and_orientation() {
399  
400     SGVec3d position = SGVec3d::fromGeod(_base_pos) - _smgr->get_position();
401     SGQuatd hlOr = SGQuatd::fromLonLat(_base_pos);
402     SGQuatd ec2body = hlOr*_orientation;
403
404     SGVec3f velocity = SGVec3f::zeros();
405     if ( _velocity[0] || _velocity[1] || _velocity[2] ) {
406        velocity = toVec3f( hlOr.backTransform(_velocity*SG_FEET_TO_METER) );
407     }
408
409     sample_map_iterator sample_current = _samples.begin();
410     sample_map_iterator sample_end = _samples.end();
411     for ( ; sample_current != sample_end; ++sample_current ) {
412         SGSoundSample *sample = sample_current->second;
413         sample->set_master_volume( _volume );
414         sample->set_orientation( _orientation );
415         sample->set_rotation( ec2body );
416         sample->set_position( position );
417         sample->set_velocity( velocity );
418
419         // Test if a sample is farther away than max distance, if so
420         // stop the sound playback and free it's source.
421         if (!_tied_to_listener) {
422             float max2 = sample->get_max_dist() * sample->get_max_dist();
423             float dist2 = position[0]*position[0]
424                           + position[1]*position[1] + position[2]*position[2];
425             if ((dist2 > max2) && !sample->test_out_of_range()) {
426                 sample->set_out_of_range(true);
427             } else if ((dist2 < max2) && sample->test_out_of_range()) {
428                 sample->set_out_of_range(false);
429             }
430         }
431     }
432 }
433
434 void SGSampleGroup::update_sample_config( SGSoundSample *sample )
435 {
436 #ifdef ENABLE_SOUND
437     SGVec3f orientation, velocity;
438     SGVec3d position;
439
440     if ( _tied_to_listener ) {
441         orientation = _smgr->get_direction();
442         position = SGVec3d::zeros();
443         velocity = _smgr->get_velocity();
444     } else {
445         sample->update_pos_and_orientation();
446         orientation = sample->get_orientation();
447         position = sample->get_position();
448         velocity = sample->get_velocity();
449     }
450
451     if (_smgr->bad_doppler_effect()) {
452         velocity *= 100.0f;
453     }
454
455 #if 0
456     if (length(position) > 20000)
457         printf("%s source and listener distance greater than 20km!\n",
458                _refname.c_str());
459     if (isNaN(toVec3f(position).data())) printf("NaN in source position\n");
460     if (isNaN(orientation.data())) printf("NaN in source orientation\n");
461     if (isNaN(velocity.data())) printf("NaN in source velocity\n");
462 #endif
463
464     unsigned int source = sample->get_source();
465     alSourcefv( source, AL_POSITION, toVec3f(position).data() );
466     alSourcefv( source, AL_VELOCITY, velocity.data() );
467     alSourcefv( source, AL_DIRECTION, orientation.data() );
468     testForALError("position and orientation");
469
470     alSourcef( source, AL_PITCH, sample->get_pitch() );
471     alSourcef( source, AL_GAIN, sample->get_volume() );
472     testForALError("pitch and gain");
473
474     if ( sample->has_static_data_changed() ) {
475         alSourcef( source, AL_CONE_INNER_ANGLE, sample->get_innerangle() );
476         alSourcef( source, AL_CONE_OUTER_ANGLE, sample->get_outerangle() );
477         alSourcef( source, AL_CONE_OUTER_GAIN, sample->get_outergain() );
478         testForALError("audio cone");
479
480         alSourcef( source, AL_MAX_DISTANCE, sample->get_max_dist() );
481         alSourcef( source, AL_REFERENCE_DISTANCE,
482                            sample->get_reference_dist() );
483         testForALError("distance rolloff");
484     }
485 #endif
486 }
487
488 bool SGSampleGroup::testForError(void *p, string s)
489 {
490    if (p == NULL) {
491       SG_LOG( SG_SOUND, SG_ALERT, "Error (sample group): " << s);
492       return true;
493    }
494    return false;
495 }
496
497 bool SGSampleGroup::testForALError(string s)
498 {
499 #ifdef SG_C
500     ALenum error = alGetError();
501     if (error != AL_NO_ERROR)  {
502        SG_LOG( SG_SOUND, SG_ALERT, "AL Error (" << _refname << "): "
503                                       << alGetString(error) << " at " << s);
504        return true;
505     }
506 #endif
507     return false;
508 }
509