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