]> git.mxchange.org Git - simgear.git/blob - simgear/sound/xmlsound.cxx
Logging - downgrade play/stop messages to debug.
[simgear.git] / simgear / sound / xmlsound.cxx
1 // sound.cxx -- Sound class implementation
2 //
3 // Started by Erik Hofman, February 2002
4 // (Reuses some code from  fg_fx.cxx created by David Megginson)
5 //
6 // Copyright (C) 2002  Curtis L. Olson - http://www.flightgear.org/~curt
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 as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // 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 // $Id$
23
24 #ifdef HAVE_CONFIG_H
25 #  include <simgear_config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <string.h>
31
32 #include <simgear/debug/logstream.hxx>
33 #include <simgear/props/condition.hxx>
34 #include <simgear/math/SGMath.hxx>
35
36
37 #include "xmlsound.hxx"
38
39
40 // static double _snd_lin(double v)   { return v; }
41 static double _snd_inv(double v)   { return (v == 0) ? 1e99 : 1/v; }
42 static double _snd_abs(double v)   { return (v >= 0) ? v : -v; }
43 static double _snd_sqrt(double v)  { return sqrt(fabs(v)); }
44 static double _snd_log10(double v) { return log10(fabs(v)); }
45 static double _snd_log(double v)   { return log(fabs(v)); }
46 // static double _snd_sqr(double v)   { return v*v; }
47 // static double _snd_pow3(double v)  { return v*v*v; }
48
49 static const struct {
50         const char *name;
51         double (*fn)(double);
52 } __sound_fn[] = {
53 //      {"lin", _snd_lin},
54         {"inv", _snd_inv},
55         {"abs", _snd_abs},
56         {"sqrt", _snd_sqrt},
57         {"log", _snd_log10},
58         {"ln", _snd_log},
59 //      {"sqr", _snd_sqr},
60 //      {"pow3", _snd_pow3},
61         {"", NULL}
62 };
63
64 SGXmlSound::SGXmlSound()
65   : _sample(NULL),
66     _active(false),
67     _name(""),
68     _mode(SGXmlSound::ONCE),
69     _prev_value(0),
70     _dt_play(0.0),
71     _dt_stop(0.0),
72     _delay(0.0),
73     _stopping(0.0)
74 {
75 }
76
77 SGXmlSound::~SGXmlSound()
78 {
79     if (_sample)
80         _sample->stop();
81
82     _volume.clear();
83     _pitch.clear();
84 }
85
86 void
87 SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr,
88                  const string &path)
89 {
90
91    //
92    // set global sound properties
93    //
94
95    if (sndmgr->is_working() == false) {
96        return;
97    }
98    
99    _name = node->getStringValue("name", "");
100    SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name );
101
102    const char *mode_str = node->getStringValue("mode", "");
103    if ( !strcmp(mode_str, "looped") ) {
104        _mode = SGXmlSound::LOOPED;
105
106    } else if ( !strcmp(mode_str, "in-transit") ) {
107        _mode = SGXmlSound::IN_TRANSIT;
108
109    } else {
110       _mode = SGXmlSound::ONCE;
111
112       if ( strcmp(mode_str, "") )
113          SG_LOG(SG_GENERAL,SG_INFO, "  Unknown sound mode, default to 'once'");
114    }
115
116    _property = root->getNode(node->getStringValue("property", ""), true);
117    SGPropertyNode *condition = node->getChild("condition");
118    if (condition != NULL)
119       _condition = sgReadCondition(root, condition);
120
121    if (!_property && !_condition)
122       SG_LOG(SG_GENERAL, SG_WARN,
123              "  Neither a condition nor a property specified");
124
125    _delay = node->getDoubleValue("delay-sec", 0.0);
126
127    //
128    // set volume properties
129    //
130    unsigned int i;
131    float v = 0.0;
132    std::vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
133    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
134       _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
135
136       if (strcmp(kids[i]->getStringValue("property"), ""))
137          volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
138
139       const char *intern_str = kids[i]->getStringValue("internal", "");
140       if (!strcmp(intern_str, "dt_play"))
141          volume.intern = &_dt_play;
142       else if (!strcmp(intern_str, "dt_stop"))
143          volume.intern = &_dt_stop;
144
145       if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
146          if (volume.factor < 0.0) {
147             volume.factor = -volume.factor;
148             volume.subtract = true;
149          }
150
151       const char *type_str = kids[i]->getStringValue("type", "");
152       if ( strcmp(type_str, "") ) {
153
154          for (int j=0; __sound_fn[j].fn; j++)
155            if ( !strcmp(type_str, __sound_fn[j].name) ) {
156                volume.fn = __sound_fn[j].fn;
157                break;
158             }
159
160          if (!volume.fn)
161             SG_LOG(SG_GENERAL,SG_INFO,
162                    "  Unknown volume type, default to 'lin'");
163       }
164
165       volume.offset = kids[i]->getDoubleValue("offset", 0.0);
166
167       if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
168          SG_LOG( SG_GENERAL, SG_WARN,
169           "Volume minimum value below 0. Forced to 0.");
170
171       volume.max = kids[i]->getDoubleValue("max", 0.0);
172       if (volume.max && (volume.max < volume.min) )
173          SG_LOG(SG_GENERAL,SG_ALERT,
174                 "  Volume maximum below minimum. Neglected.");
175
176       _volume.push_back(volume);
177       v += volume.offset;
178
179    }
180
181    float reference_dist = node->getDoubleValue("reference-dist", 500.0);
182    float max_dist = node->getDoubleValue("max-dist", 3000.0);
183  
184    //
185    // set pitch properties
186    //
187    float p = 0.0;
188    kids = node->getChildren("pitch");
189    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
190       _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
191
192       if (strcmp(kids[i]->getStringValue("property", ""), ""))
193          pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
194
195       const char *intern_str = kids[i]->getStringValue("internal", "");
196       if (!strcmp(intern_str, "dt_play"))
197          pitch.intern = &_dt_play;
198       else if (!strcmp(intern_str, "dt_stop"))
199          pitch.intern = &_dt_stop;
200
201       if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
202          if (pitch.factor < 0.0) {
203             pitch.factor = -pitch.factor;
204             pitch.subtract = true;
205          }
206
207       const char *type_str = kids[i]->getStringValue("type", "");
208       if ( strcmp(type_str, "") ) {
209
210          for (int j=0; __sound_fn[j].fn; j++) 
211             if ( !strcmp(type_str, __sound_fn[j].name) ) {
212                pitch.fn = __sound_fn[j].fn;
213                break;
214             }
215
216          if (!pitch.fn)
217             SG_LOG(SG_GENERAL,SG_INFO,
218                    "  Unknown pitch type, default to 'lin'");
219       }
220      
221       pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
222
223       if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
224          SG_LOG(SG_GENERAL,SG_WARN,
225                 "  Pitch minimum value below 0. Forced to 0.");
226
227       pitch.max = kids[i]->getDoubleValue("max", 0.0);
228       if (pitch.max && (pitch.max < pitch.min) )
229          SG_LOG(SG_GENERAL,SG_ALERT,
230                 "  Pitch maximum below minimum. Neglected");
231
232       _pitch.push_back(pitch);
233       p += pitch.offset;
234    }
235
236    //
237    // Relative position
238    //
239    sgVec3 offset_pos;
240    sgSetVec3( offset_pos, 0.0, 0.0, 0.0 );
241    SGPropertyNode_ptr pos = node->getChild("position");
242    if ( pos != NULL ) {
243        offset_pos[0] = pos->getDoubleValue("x", 0.0);
244        offset_pos[1] = -pos->getDoubleValue("y", 0.0);
245        offset_pos[2] = pos->getDoubleValue("z", 0.0);
246    }
247
248    //
249    // Orientation
250    //
251    sgVec3 dir;
252    float inner, outer, outer_gain;
253    sgSetVec3( dir, 0.0, 0.0, 0.0 );
254    inner = outer = 360.0;
255    outer_gain = 0.0;
256    pos = node->getChild("orientation");
257    if ( pos != NULL ) {
258       dir[0] = pos->getDoubleValue("x", 0.0);
259       dir[1] = -pos->getDoubleValue("y", 0.0);
260       dir[2] = pos->getDoubleValue("z", 0.0);
261       inner = pos->getDoubleValue("inner-angle", 360.0);
262       outer = pos->getDoubleValue("outer-angle", 360.0);
263       outer_gain = pos->getDoubleValue("outer-gain", 0.0);
264    }
265    
266    //
267    // Initialize the sample
268    //
269    _mgr = sndmgr;
270    if ( (_sample = _mgr->find(_name)) == NULL ) {
271        // FIXME: Does it make sense to overwrite a previous entry's
272        // configuration just because a new entry has the same name?
273        // Note that we can't match on identical "path" because we the
274        // new entry could be at a different location with different
275        // configuration so we need a new sample which creates a new
276        // "alSource".  The semantics of what is going on here seems
277        // confused and needs to be thought through more carefully.
278         _sample = new SGSoundSample( path.c_str(),
279                                     node->getStringValue("path", ""),
280                                     false );
281
282        _mgr->add( _sample, _name );
283    }
284
285    _sample->set_offset_pos( offset_pos );
286    _sample->set_orientation(dir, inner, outer, outer_gain);
287    _sample->set_volume(v);
288    _sample->set_reference_dist( reference_dist );
289    _sample->set_max_dist( max_dist );
290    _sample->set_pitch(p);
291 }
292
293 void
294 SGXmlSound::update (double dt)
295 {
296    double curr_value = 0.0;
297
298    //
299    // If the state changes to false, stop playing.
300    //
301    if (_property)
302        curr_value = _property->getDoubleValue();
303
304    // If a condition is defined, test whether it is FALSE,
305    // else
306    //   if a property is defined then test if it's value is FALSE
307    //      or if the mode is IN_TRANSIT then
308    //            test whether the current value matches the previous value.
309    if (                                                 // Lisp, anyone?
310        (_condition && !_condition->test()) ||
311        (!_condition && _property &&
312         (
313          !curr_value ||
314          ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
315          )
316         )
317        )
318    {
319        if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) {
320            if (_sample->is_playing()) {
321                SG_LOG(SG_GENERAL, SG_DEBUG, "Stopping audio after " << _dt_play
322                       << " sec: " << _name );
323
324                _sample->stop();
325            }
326
327            _active = false;
328            _dt_stop += dt;
329            _dt_play = 0.0;
330        } else {
331            _stopping += dt;
332        }
333
334        return;
335    }
336
337    //
338    // mode is ONCE and the sound is still playing?
339    //
340    if (_active && (_mode == SGXmlSound::ONCE)) {
341
342       if (!_sample->is_playing()) {
343          _dt_stop += dt;
344          _dt_play = 0.0;
345       } else {
346          _dt_play += dt;
347       }
348
349    } else {
350
351       //
352       // Update the playing time, cache the current value and
353       // clear the delay timer.
354       //
355       _dt_play += dt;
356       _prev_value = curr_value;
357       _stopping = 0.0;
358    }
359
360    if (_dt_play < _delay)
361       return;
362
363    //
364    // Update the volume
365    //
366    int i;
367    int max = _volume.size();
368    double volume = 1.0;
369    double volume_offset = 0.0;
370
371    for(i = 0; i < max; i++) {
372       double v = 1.0;
373
374       if (_volume[i].prop)
375          v = _volume[i].prop->getDoubleValue();
376
377       else if (_volume[i].intern)
378          v = *_volume[i].intern;
379
380       if (_volume[i].fn)
381          v = _volume[i].fn(v);
382
383       v *= _volume[i].factor;
384
385       if (_volume[i].max && (v > _volume[i].max))
386          v = _volume[i].max;
387
388       else if (v < _volume[i].min)
389          v = _volume[i].min;
390
391       if (_volume[i].subtract)                          // Hack!
392          volume = _volume[i].offset - v;
393
394       else {
395          volume_offset += _volume[i].offset;
396          volume *= v;
397       }
398    }
399
400    //
401    // Update the pitch
402    //
403    max = _pitch.size();
404    double pitch = 1.0;
405    double pitch_offset = 0.0;
406
407    for(i = 0; i < max; i++) {
408       double p = 1.0;
409
410       if (_pitch[i].prop)
411          p = _pitch[i].prop->getDoubleValue();
412
413       else if (_pitch[i].intern)
414          p = *_pitch[i].intern;
415
416       if (_pitch[i].fn)
417          p = _pitch[i].fn(p);
418
419       p *= _pitch[i].factor;
420
421       if (_pitch[i].max && (p > _pitch[i].max))
422          p = _pitch[i].max;
423
424       else if (p < _pitch[i].min)
425          p = _pitch[i].min;
426
427       if (_pitch[i].subtract)                           // Hack!
428          pitch = _pitch[i].offset - p;
429
430       else {
431          pitch_offset += _pitch[i].offset;
432          pitch *= p;
433       }
434    }
435
436    //
437    // Change sample state
438    //
439
440    double vol = volume_offset + volume;
441    if (vol > 1.0) {
442       SG_LOG(SG_GENERAL, SG_DEBUG, "Sound volume too large for '"
443               << _name << "':  " << vol << "  ->  clipping to 1.0");
444       vol = 1.0;
445    }
446    _sample->set_volume(vol);
447    _sample->set_pitch( pitch_offset + pitch );
448
449
450    //
451    // Do we need to start playing the sample?
452    //
453    if (!_active) {
454
455       if (_mode == SGXmlSound::ONCE)
456          _sample->play(false);
457
458       else
459          _sample->play(true);
460
461       SG_LOG(SG_GENERAL, SG_DEBUG, "Playing audio after " << _dt_stop 
462                                    << " sec: " << _name);
463       SG_LOG(SG_GENERAL, SG_DEBUG,
464                          "Playing " << ((_mode == ONCE) ? "once" : "looped"));
465
466       _active = true;
467       _dt_stop = 0.0;
468    }
469 }