]> git.mxchange.org Git - simgear.git/blob - simgear/sound/xmlsound.cxx
88bef7657f580a501c38e67d3e62a3732a8c5a3c
[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)+1e-9); }
45 static double _snd_log(double v)   { return log(fabs(v)+1e-9); }
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         {"inv", _snd_inv},
54         {"abs", _snd_abs},
55         {"sqrt", _snd_sqrt},
56         {"log", _snd_log10},
57         {"ln", _snd_log},
58         {"", NULL}
59 };
60
61 SGXmlSound::SGXmlSound()
62   : _sample(NULL),
63     _active(false),
64     _name(""),
65     _mode(SGXmlSound::ONCE),
66     _prev_value(0),
67     _dt_play(0.0),
68     _dt_stop(0.0),
69     _delay(0.0),
70     _stopping(0.0)
71 {
72 }
73
74 SGXmlSound::~SGXmlSound()
75 {
76     if (_sample)
77         _sample->stop();
78
79     _volume.clear();
80     _pitch.clear();
81 }
82
83 void
84 SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node,
85                  SGSampleGroup *sgrp, SGSampleGroup *avionics,
86                  const string &path)
87 {
88
89    //
90    // set global sound properties
91    //
92
93    _name = node->getStringValue("name", "");
94    SG_LOG(SG_GENERAL, SG_DEBUG, "Loading sound information for: " << _name );
95
96    const char *mode_str = node->getStringValue("mode", "");
97    if ( !strcmp(mode_str, "looped") ) {
98        _mode = SGXmlSound::LOOPED;
99
100    } else if ( !strcmp(mode_str, "in-transit") ) {
101        _mode = SGXmlSound::IN_TRANSIT;
102
103    } else {
104       _mode = SGXmlSound::ONCE;
105    }
106
107    bool is_avionics = false;
108    const char *type_str = node->getStringValue("type", "fx");
109    if ( !strcmp(type_str, "avionics") )
110       is_avionics = true;
111
112    _property = root->getNode(node->getStringValue("property", ""), true);
113    SGPropertyNode *condition = node->getChild("condition");
114    if (condition != NULL)
115       _condition = sgReadCondition(root, condition);
116
117    if (!_property && !_condition)
118       SG_LOG(SG_GENERAL, SG_WARN,
119              "  Neither a condition nor a property specified");
120
121    _delay = node->getDoubleValue("delay-sec", 0.0);
122
123    //
124    // set volume properties
125    //
126    unsigned int i;
127    float v = 0.0;
128    std::vector<SGPropertyNode_ptr> kids = node->getChildren("volume");
129    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
130       _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false};
131
132       if (strcmp(kids[i]->getStringValue("property"), ""))
133          volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
134
135       const char *intern_str = kids[i]->getStringValue("internal", "");
136       if (!strcmp(intern_str, "dt_play"))
137          volume.intern = &_dt_play;
138       else if (!strcmp(intern_str, "dt_stop"))
139          volume.intern = &_dt_stop;
140
141       if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
142          if (volume.factor < 0.0) {
143             volume.factor = -volume.factor;
144             volume.subtract = true;
145          }
146
147       const char *type_str = kids[i]->getStringValue("type", "");
148       if ( strcmp(type_str, "") ) {
149
150          for (int j=0; __sound_fn[j].fn; j++)
151            if ( !strcmp(type_str, __sound_fn[j].name) ) {
152                volume.fn = __sound_fn[j].fn;
153                break;
154             }
155
156          if (!volume.fn)
157             SG_LOG(SG_GENERAL,SG_INFO,
158                    "  Unknown volume type, default to 'lin'");
159       }
160
161       volume.offset = kids[i]->getDoubleValue("offset", 0.0);
162
163       if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
164          SG_LOG( SG_GENERAL, SG_WARN,
165           "Volume minimum value below 0. Forced to 0.");
166
167       volume.max = kids[i]->getDoubleValue("max", 0.0);
168       if (volume.max && (volume.max < volume.min) )
169          SG_LOG(SG_GENERAL,SG_ALERT,
170                 "  Volume maximum below minimum. Neglected.");
171
172       _volume.push_back(volume);
173       v += volume.offset;
174
175    }
176
177    float reference_dist = node->getDoubleValue("reference-dist", 500.0);
178    float max_dist = node->getDoubleValue("max-dist", 3000.0);
179  
180    //
181    // set pitch properties
182    //
183    float p = 0.0;
184    kids = node->getChildren("pitch");
185    for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) {
186       _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false};
187
188       if (strcmp(kids[i]->getStringValue("property", ""), ""))
189          pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true);
190
191       const char *intern_str = kids[i]->getStringValue("internal", "");
192       if (!strcmp(intern_str, "dt_play"))
193          pitch.intern = &_dt_play;
194       else if (!strcmp(intern_str, "dt_stop"))
195          pitch.intern = &_dt_stop;
196
197       if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0)
198          if (pitch.factor < 0.0) {
199             pitch.factor = -pitch.factor;
200             pitch.subtract = true;
201          }
202
203       const char *type_str = kids[i]->getStringValue("type", "");
204       if ( strcmp(type_str, "") ) {
205
206          for (int j=0; __sound_fn[j].fn; j++) 
207             if ( !strcmp(type_str, __sound_fn[j].name) ) {
208                pitch.fn = __sound_fn[j].fn;
209                break;
210             }
211
212          if (!pitch.fn)
213             SG_LOG(SG_GENERAL,SG_INFO,
214                    "  Unknown pitch type, default to 'lin'");
215       }
216      
217       pitch.offset = kids[i]->getDoubleValue("offset", 1.0);
218
219       if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0)
220          SG_LOG(SG_GENERAL,SG_WARN,
221                 "  Pitch minimum value below 0. Forced to 0.");
222
223       pitch.max = kids[i]->getDoubleValue("max", 0.0);
224       if (pitch.max && (pitch.max < pitch.min) )
225          SG_LOG(SG_GENERAL,SG_ALERT,
226                 "  Pitch maximum below minimum. Neglected");
227
228       _pitch.push_back(pitch);
229       p += pitch.offset;
230    }
231
232    //
233    // Relative position
234    //
235    SGVec3f offset_pos = SGVec3f::zeros();
236    SGPropertyNode_ptr prop = node->getChild("position");
237    if ( prop != NULL ) {
238        offset_pos[0] = prop->getDoubleValue("z", 0.0);
239        offset_pos[1] = prop->getDoubleValue("y", 0.0);
240        offset_pos[2] = prop->getDoubleValue("x", 0.0);
241    }
242
243    //
244    // Orientation
245    //
246    SGVec3f dir = SGVec3f::zeros();
247    float inner = 360.0;
248    float outer = 360.0;
249    float outer_gain = 0.0;
250    prop = node->getChild("orientation");
251    if ( prop != NULL ) {
252       dir = SGVec3f(prop->getFloatValue("z", 0.0),
253                     prop->getFloatValue("y", 0.0),
254                     prop->getFloatValue("x", 0.0));
255       inner = prop->getFloatValue("inner-angle", 360.0);
256       outer = prop->getFloatValue("outer-angle", 360.0);
257       outer_gain = prop->getFloatValue("outer-gain", 0.0);
258    }
259
260    //
261    // Initialize the sample
262    //
263    if (is_avionics) {
264       _sgrp = avionics;
265    } else {
266       _sgrp = sgrp;
267    }
268    _sample = new SGSoundSample( path.c_str(), node->getStringValue("path", ""));
269    _sample->set_relative_position( offset_pos );
270    _sample->set_direction( dir );
271    _sample->set_audio_cone( inner, outer, outer_gain );
272    _sample->set_reference_dist( reference_dist );
273    _sample->set_max_dist( max_dist );
274    _sample->set_volume( v );
275    _sample->set_pitch( p );
276    _sgrp->add( _sample, _name );
277 }
278
279 void
280 SGXmlSound::update (double dt)
281 {
282    double curr_value = 0.0;
283
284    //
285    // If the state changes to false, stop playing.
286    //
287    if (_property)
288        curr_value = _property->getDoubleValue();
289
290    // If a condition is defined, test whether it is FALSE,
291    // else
292    //   if a property is defined then test if it's value is FALSE
293    //      or if the mode is IN_TRANSIT then
294    //            test whether the current value matches the previous value.
295    if (                                                 // Lisp, anyone?
296        (_condition && !_condition->test()) ||
297        (!_condition && _property &&
298         (
299          !curr_value ||
300          ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) )
301          )
302         )
303        )
304    {
305        if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME))
306        {
307            if (_sample->is_playing()) {
308                SG_LOG(SG_GENERAL, SG_DEBUG, "Stopping audio after " << _dt_play
309                       << " sec: " << _name );
310
311                _sample->stop();
312            }
313
314            _active = false;
315            _dt_stop += dt;
316            _dt_play = 0.0;
317        } else {
318            _stopping += dt;
319        }
320
321        return;
322    }
323
324    //
325    // mode is ONCE and the sound is still playing?
326    //
327    if (_active && (_mode == SGXmlSound::ONCE)) {
328
329       if (!_sample->is_playing()) {
330          _dt_stop += dt;
331          _dt_play = 0.0;
332       } else {
333          _dt_play += dt;
334       }
335
336    } else {
337
338       //
339       // Update the playing time, cache the current value and
340       // clear the delay timer.
341       //
342       _dt_play += dt;
343       _prev_value = curr_value;
344       _stopping = 0.0;
345    }
346
347    if (_dt_play < _delay)
348       return;
349
350    //
351    // Update the volume
352    //
353    int i;
354    int max = _volume.size();
355    double volume = 1.0;
356    double volume_offset = 0.0;
357
358    for(i = 0; i < max; i++) {
359       double v = 1.0;
360
361       if (_volume[i].prop)
362          v = _volume[i].prop->getDoubleValue();
363
364       else if (_volume[i].intern)
365          v = *_volume[i].intern;
366
367       if (_volume[i].fn)
368          v = _volume[i].fn(v);
369
370       v *= _volume[i].factor;
371
372       if (_volume[i].max && (v > _volume[i].max))
373          v = _volume[i].max;
374
375       else if (v < _volume[i].min)
376          v = _volume[i].min;
377
378       if (_volume[i].subtract)                          // Hack!
379          volume = _volume[i].offset - v;
380
381       else {
382          volume_offset += _volume[i].offset;
383          volume *= v;
384       }
385    }
386
387    //
388    // Update the pitch
389    //
390    max = _pitch.size();
391    double pitch = 1.0;
392    double pitch_offset = 0.0;
393
394    for(i = 0; i < max; i++) {
395       double p = 1.0;
396
397       if (_pitch[i].prop)
398          p = _pitch[i].prop->getDoubleValue();
399
400       else if (_pitch[i].intern)
401          p = *_pitch[i].intern;
402
403       if (_pitch[i].fn)
404          p = _pitch[i].fn(p);
405
406       p *= _pitch[i].factor;
407
408       if (_pitch[i].max && (p > _pitch[i].max))
409          p = _pitch[i].max;
410
411       else if (p < _pitch[i].min)
412          p = _pitch[i].min;
413
414       if (_pitch[i].subtract)                           // Hack!
415          pitch = _pitch[i].offset - p;
416
417       else {
418          pitch_offset += _pitch[i].offset;
419          pitch *= p;
420       }
421    }
422
423    //
424    // Change sample state
425    //
426
427    double vol = volume_offset + volume;
428    if (vol > 1.0) {
429       SG_LOG(SG_GENERAL, SG_DEBUG, "Sound volume too large for '"
430               << _name << "':  " << vol << "  ->  clipping to 1.0");
431       vol = 1.0;
432    }
433    _sample->set_volume(vol);
434    _sample->set_pitch( pitch_offset + pitch );
435
436
437    //
438    // Do we need to start playing the sample?
439    //
440    if (!_active) {
441
442       if (_mode == SGXmlSound::ONCE)
443          _sample->play(false);
444
445       else
446          _sample->play(true);
447
448       SG_LOG(SG_GENERAL, SG_DEBUG, "Playing audio after " << _dt_stop 
449                                    << " sec: " << _name);
450       SG_LOG(SG_GENERAL, SG_DEBUG,
451                          "Playing " << ((_mode == ONCE) ? "once" : "looped"));
452
453       _active = true;
454       _dt_stop = 0.0;
455    }
456 }