File: osgalmultiple.cpp

package info (click to toggle)
osgal-cvs 20060903-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 3,836 kB
  • ctags: 424
  • sloc: sh: 8,806; cpp: 1,815; makefile: 86
file content (402 lines) | stat: -rwxr-xr-x 14,015 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/* -*-c++-*- $Id$ */
/**
 * OsgAL - OpenSceneGraph Audio Library
 * Copyright (C) 2004 VRlab, Ume University
 
 * This application is a copy of the osganimation demonstration, with added sound support to
 * demonstrate the osgAL toolkit.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */

#include "osgAL/SoundNode"
#include "osgAL/SoundRoot"
#include "osgAL/SoundManager"
#include "osgAL/SoundState"

#include <osg/Notify>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/Geometry>
#include <osg/Geode>

#include <osgUtil/Optimizer>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>

#include <osg/ShapeDrawable>


#include <osgProducer/Viewer>
#include "osgAL/Version"


osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
{
    // set up the animation path 
    osg::AnimationPath* animationPath = new osg::AnimationPath;
    animationPath->setLoopMode(osg::AnimationPath::LOOP);
    
    int numSamples = 40;
    float yaw = 0.0f;
    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
    float roll = osg::inDegrees(30.0f);
    
    double time=0.0f;
    double time_delta = looptime/(double)numSamples;
    for(int i=0;i<numSamples;++i)
    {
        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
        osg::Quat rotation(osg::Quat(roll,osg::Vec3(0.0,1.0,0.0))*osg::Quat(-(yaw+osg::inDegrees(90.0f)),osg::Vec3(0.0,0.0,1.0)));
        
        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));

        yaw += yaw_delta;
        time += time_delta;

    }
    return animationPath;    
}

osg::Node* createBase(const osg::Vec3& center,float radius)
{

    int numTilesX = 10;
    int numTilesY = 10;
    
    float width = 2*radius;
    float height = 2*radius;
    
    osg::Vec3 v000(center - osg::Vec3(width*0.5f,height*0.5f,0.0f));
    osg::Vec3 dx(osg::Vec3(width/((float)numTilesX),0.0,0.0f));
    osg::Vec3 dy(osg::Vec3(0.0f,height/((float)numTilesY),0.0f));
    
    // fill in vertices for grid, note numTilesX+1 * numTilesY+1...
    osg::Vec3Array* coords = new osg::Vec3Array;
    int iy;
    for(iy=0;iy<=numTilesY;++iy)
    {
        for(int ix=0;ix<=numTilesX;++ix)
        {
            coords->push_back(v000+dx*(float)ix+dy*(float)iy);
        }
    }
    
    //Just two colours - black and white.
    osg::Vec4Array* colors = new osg::Vec4Array;
    colors->push_back(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); // white
    colors->push_back(osg::Vec4(0.0f,0.0f,0.0f,1.0f)); // black
    int numColors=colors->size();
    
    
    int numIndicesPerRow=numTilesX+1;
    osg::UByteArray* coordIndices = new osg::UByteArray; // assumes we are using less than 256 points...
    osg::UByteArray* colorIndices = new osg::UByteArray;
    for(iy=0;iy<numTilesY;++iy)
    {
        for(int ix=0;ix<numTilesX;++ix)
        {
            // four vertices per quad.
            coordIndices->push_back(ix    +(iy+1)*numIndicesPerRow);
            coordIndices->push_back(ix    +iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+iy*numIndicesPerRow);
            coordIndices->push_back((ix+1)+(iy+1)*numIndicesPerRow);
            
            // one color per quad
            colorIndices->push_back((ix+iy)%numColors);
        }
    }
    

    // set up a single normal
    osg::Vec3Array* normals = new osg::Vec3Array;
    normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
    

    osg::Geometry* geom = new osg::Geometry;
    geom->setVertexArray(coords);
    geom->setVertexIndices(coordIndices);
    
    geom->setColorArray(colors);
    geom->setColorIndices(colorIndices);
    geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
    
    geom->setNormalArray(normals);
    geom->setNormalBinding(osg::Geometry::BIND_OVERALL);
    
    geom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::QUADS,0,coordIndices->size()));
    
    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(geom);
    
    return geode;
}

osg::Node* createMovingModel(const osg::Vec3& center, float radius)
{
    float animationLength = 10.0f;

    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);

    osg::Group* model = new osg::Group;

    osg::Node* glider = osgDB::readNodeFile("glider.osg");
    if (glider)
    {
        const osg::BoundingSphere& bs = glider->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
    
        positioned->addChild(glider);
        
        // Create a sound node
        //osg::ref_ptr<osgAL::SoundNode> sound_node = createSound("bee.wav");

        // Add the sound node
        //positioned->addChild(sound_node.get());

        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;    
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }
 
    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
    if (cessna)
    {
        const osg::BoundingSphere& bs = cessna->getBound();

        float size = radius/bs.radius()*0.3f;
        osg::MatrixTransform* positioned = new osg::MatrixTransform;
        positioned->setDataVariance(osg::Object::STATIC);
        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
                                     osg::Matrix::scale(size,size,size)*
                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
    
        positioned->addChild(cessna);
    
        osg::MatrixTransform* xform = new osg::MatrixTransform;
        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
        xform->addChild(positioned);

        model->addChild(xform);
    }
    
    return model;
}


osg::Node* createModel()
{
    osg::Vec3 center(0.0f,0.0f,0.0f);
    float radius = 100.0f;

    osg::Group* root = new osg::Group;

    root->addChild(createMovingModel(center,radius*0.8f));

    root->addChild(createBase(center-osg::Vec3(0.0f,0.0f,radius*0.5),radius));

    return root;
}


int main( int argc, char **argv )
{
  
  std::cerr << "\n\n" << osgAL::getLibraryName() << " demo" << std::endl;
  std::cerr << "Version: " << osgAL::getVersion() << "\n\n" << std::endl;

  std::cerr << "Demonstrates how to create and destroy soundsources on the fly" << std::endl;


  try {
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" demonstrates the use of the OsgAL toolkit for spatial sound.");
    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");

    // initialize the viewer.
    osgProducer::Viewer viewer(arguments);

    // set up the value with sensible default event handlers.
    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);

    // get details on keyboard and mouse bindings used by the viewer.
    viewer.getUsage(*arguments.getApplicationUsage());

    // if user request help write it out to cout.
    if (arguments.read("-h") || arguments.read("--help"))
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    // any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized();

	  arguments.getApplicationUsage()->addKeyboardMouseBinding("RETURN", "Play a sound");


    // report any errors if they have occured when parsing the program aguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    osgAL::SoundManager::instance()->init(16);
    osgAL::SoundManager::instance()->getEnvironment()->setDistanceModel(openalpp::InverseDistance);
    osgAL::SoundManager::instance()->getEnvironment()->setDopplerFactor(1);

    // load the nodes from the commandline arguments.
    osg::Node* model = createModel();
    if (!model)
    {
        return 1;
    }
    
    // tilt the scene so the default eye position is looking down on the model.
    osg::MatrixTransform* rootnode = new osg::MatrixTransform;
    rootnode->setMatrix(osg::Matrix::rotate(osg::inDegrees(30.0f),1.0f,0.0f,0.0f));
    rootnode->addChild(model);


    // Make use of a few sound samples
    std::vector<std::string> wave_vector;
    wave_vector.push_back("a.wav");
    wave_vector.push_back("high-e.wav");
    wave_vector.push_back("low-e.wav");


    // Create ONE (only one, otherwise the transformation of the listener and update for SoundManager will be
    // called several times, which is not catastrophic, but unnecessary) 
    // SoundRoot that will make sure the listener is updated and
    // to keep the internal state of the SoundManager updated
    // This could also be done manually, this is just a handy way of doing it.
    osg::ref_ptr<osgAL::SoundRoot> sound_root = new osgAL::SoundRoot;
  
    
    // The position in the scenegraph of this node is not important.
    // Just as long as the cull traversal should be called after any changes to the SoundManager are made.
    rootnode->addChild(sound_root.get());


    // Create a transformation node onto we will attach a soundnode
    osg::ref_ptr<osg::PositionAttitudeTransform> sound_transform = new osg::PositionAttitudeTransform;
    rootnode->addChild(sound_transform.get());
    sound_transform->setPosition(osg::Vec3(0,-100,50));

    // Create a sphere so we can "see" the sound
    osg::ref_ptr<osg::Geode> geode = new osg::Geode;
    osg::TessellationHints* hints = new osg::TessellationHints;
    hints->setDetailRatio(0.5f);
    geode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),1),hints));
    sound_transform->addChild(geode.get());
    osg::ref_ptr<osgAL::SoundNode> sound_node = new osgAL::SoundNode;
    sound_transform->addChild(sound_node.get());

    osg::Timer_t curr, start = osg::Timer::instance()->tick();
    double interval = 2; // 2 seconds interval
    unsigned int n = 0;

    // run optimization over the scene graph
    osgUtil::Optimizer optimizer;
    optimizer.optimize(rootnode);
     
    // set the scene to render
    viewer.setSceneData(rootnode);
  
    // create the windows and run the threads.
    viewer.realize();


    while( !viewer.done() )
    {
      // wait for all cull and draw threads to complete.
      viewer.sync();
  
      // update the scene by traversing it with the the update visitor which will
      // call all node update callbacks and animations.
      viewer.update();

      // For every interval seconds, we will remove the current soundstate and create a new one,
      // with the next sample sounds
      curr = osg::Timer::instance()->tick();
      if (osg::Timer::instance()->delta_s(start, curr) > interval) 
      {
        start = curr;

        std::string file = wave_vector[n%wave_vector.size()];

        osgAL::SoundManager::instance()->removeSoundState(file);

        n++;
        // Create a sample, load a .wav file.
        file = wave_vector[n%wave_vector.size()];
        bool add_to_cache = false;
        openalpp::ref_ptr<openalpp::Sample> sample = osgAL::SoundManager::instance()->getSample(file.c_str(), add_to_cache);
        std::cerr << "Loading sample: " << file << std::endl;

        // Create a new soundstate, give it the name of the file we loaded.
        osg::ref_ptr<osgAL::SoundState> sound_state = new osgAL::SoundState(file);
        sound_state->setSample(sample.get());
        sound_state->setGain(1.0f);
        sound_state->setReferenceDistance(60);
        sound_state->setRolloffFactor(3);
        sound_state->setPlay(true);
        sound_state->setLooping(true);

        // Allocate a hardware soundsource to this soundstate (priority 10)
        sound_state->allocateSource(10, false);

        // Add the soundstate to the sound manager, so we can find it later on if we want to
        osgAL::SoundManager::instance()->addSoundState(sound_state.get());

        sound_state->apply();
        sound_node->setSoundState(sound_state.get());
      }

      // fire off the cull and draw traversals of the scene.
      viewer.frame();
    }
    
  // wait for all cull and draw threads to complete before exit.
  viewer.sync();
}
  catch (std::exception& e) {
    std::cerr << "Caught: " << e.what() << std::endl;
  }
  // Very important to call this before end of main.
  // Otherwise OpenAL will do all sorts of strange things after end of main
  // in the destructor of soundmanager.
  osgAL::SoundManager::instance()->shutdown();
  return 0;

}