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