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