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