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