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