root/OpenSceneGraph/trunk/examples/osgspheresegment/osgspheresegment.cpp @ 4588

Revision 4588, 18.2 kB (checked in by robert, 9 years ago)

Changed the "Cessna" text so that it is sized according to OBJECT_COORDS rather
than SCREEN_COORDS as the later was causing problems with the pixel size based LOD selection.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#include <osgProducer/Viewer>
2
3#include <osg/Group>
4#include <osg/Geode>
5#include <osg/ShapeDrawable>
6#include <osg/Texture2D>
7#include <osg/PositionAttitudeTransform>
8#include <osg/MatrixTransform>
9#include <osg/Geometry>
10
11#include <osgUtil/SmoothingVisitor>
12
13#include <osgDB/ReadFile>
14
15#include <osgText/Text>
16
17#include <osgSim/SphereSegment>
18#include <osgSim/OverlayNode>
19
20#include <osgParticle/ExplosionEffect>
21#include <osgParticle/SmokeEffect>
22#include <osgParticle/FireEffect>
23#include <osgParticle/ParticleSystemUpdater>
24
25// for the grid data..
26#include "../osghangglide/terrain_coords.h"
27
28osg::AnimationPath* createAnimationPath(const osg::Vec3& center,float radius,double looptime)
29{
30    // set up the animation path
31    osg::AnimationPath* animationPath = new osg::AnimationPath;
32    animationPath->setLoopMode(osg::AnimationPath::LOOP);
33   
34    int numSamples = 40;
35    float yaw = 0.0f;
36    float yaw_delta = 2.0f*osg::PI/((float)numSamples-1.0f);
37    float roll = osg::inDegrees(30.0f);
38   
39    double time=0.0f;
40    double time_delta = looptime/(double)numSamples;
41    for(int i=0;i<numSamples;++i)
42    {
43        osg::Vec3 position(center+osg::Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0f));
44        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)));
45       
46        animationPath->insert(time,osg::AnimationPath::ControlPoint(position,rotation));
47
48        yaw += yaw_delta;
49        time += time_delta;
50
51    }
52    return animationPath;   
53}
54
55osg::Node* createMovingModel(const osg::Vec3& center, float radius)
56{
57    float animationLength = 10.0f;
58
59    osg::AnimationPath* animationPath = createAnimationPath(center,radius,animationLength);
60
61    osg::Group* model = new osg::Group;
62
63    osg::Node* glider = osgDB::readNodeFile("glider.osg");
64    if (glider)
65    {
66        const osg::BoundingSphere& bs = glider->getBound();
67
68        float size = radius/bs.radius()*0.3f;
69        osg::MatrixTransform* positioned = new osg::MatrixTransform;
70        positioned->setDataVariance(osg::Object::STATIC);
71        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
72                                     osg::Matrix::scale(size,size,size)*
73                                     osg::Matrix::rotate(osg::inDegrees(-90.0f),0.0f,0.0f,1.0f));
74   
75        positioned->addChild(glider);
76   
77        osg::PositionAttitudeTransform* xform = new osg::PositionAttitudeTransform;   
78        xform->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
79        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0,1.0));
80        xform->addChild(positioned);
81
82        model->addChild(xform);
83    }
84 
85    osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
86    if (cessna)
87    {
88        const osg::BoundingSphere& bs = cessna->getBound();
89
90        osgText::Text* text = new osgText::Text;
91        float size = radius/bs.radius()*0.3f;
92
93        text->setPosition(bs.center());
94        text->setText("Cessna");
95        text->setAlignment(osgText::Text::CENTER_CENTER);
96        text->setAxisAlignment(osgText::Text::SCREEN);
97        text->setCharacterSize(40.0f);
98        text->setCharacterSizeMode(osgText::Text::OBJECT_COORDS);
99       
100        osg::Geode* geode = new osg::Geode;
101        geode->addDrawable(text);
102   
103        osg::LOD* lod = new osg::LOD;
104        lod->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
105        lod->addChild(geode,0.0f,100.0f);
106        lod->addChild(cessna,100.0f,10000.0f);
107
108
109        osg::MatrixTransform* positioned = new osg::MatrixTransform;
110        positioned->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
111        positioned->setDataVariance(osg::Object::STATIC);
112        positioned->setMatrix(osg::Matrix::translate(-bs.center())*
113                                     osg::Matrix::scale(size,size,size)*
114                                     osg::Matrix::rotate(osg::inDegrees(180.0f),0.0f,0.0f,1.0f));
115   
116        //positioned->addChild(cessna);
117        positioned->addChild(lod);
118   
119        osg::MatrixTransform* xform = new osg::MatrixTransform;
120        xform->setUpdateCallback(new osg::AnimationPathCallback(animationPath,0.0f,2.0));
121        xform->addChild(positioned);
122
123        // add particle effects to cessna.
124        {
125            osg::PositionAttitudeTransform* positionEffects = new osg::PositionAttitudeTransform;
126            positionEffects->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
127            xform->addChild(positionEffects);
128
129            osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect;
130            osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect;
131            osgParticle::FireEffect* fire = new osgParticle::FireEffect;
132
133            positionEffects->addChild(explosion);
134            positionEffects->addChild(smoke);
135            positionEffects->addChild(fire);
136        }
137       
138        model->addChild(xform);
139    }
140   
141    return model;
142}
143
144osg::Group* createOverlay(const osg::Vec3& center, float radius)
145{
146    osg::Group* group = new osg::Group;
147   
148    // create a grid of lines.
149    {
150        osg::Geometry* geom = new osg::Geometry;
151       
152        unsigned int num_rows = 10;
153
154        osg::Vec3 left = center+osg::Vec3(-radius,-radius,0.0f);
155        osg::Vec3 right = center+osg::Vec3(radius,-radius,0.0f);
156        osg::Vec3 delta_row = osg::Vec3(0.0f,2.0f*radius/float(num_rows-1),0.0f);
157
158        osg::Vec3 top = center+osg::Vec3(-radius,radius,0.0f);
159        osg::Vec3 bottom = center+osg::Vec3(-radius,-radius,0.0f);
160        osg::Vec3 delta_column = osg::Vec3(2.0f*radius/float(num_rows-1),0.0f,0.0f);
161
162        osg::Vec3Array* vertices = new osg::Vec3Array;
163        for(unsigned int i=0; i<num_rows; ++i)
164        {
165            vertices->push_back(left);
166            vertices->push_back(right);
167            left += delta_row;
168            right += delta_row;
169
170            vertices->push_back(top);
171            vertices->push_back(bottom);
172            top += delta_column;
173            bottom += delta_column;
174        }
175       
176        geom->setVertexArray(vertices);
177
178        osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
179        color[0].set(0,0,0,255);
180        geom->setColorArray(&color);
181        geom->setColorBinding(osg::Geometry::BIND_OVERALL);
182
183        geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES,0,vertices->getNumElements()));
184
185        geom->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
186
187        osg::Geode* geode = new osg::Geode;
188        geode->addDrawable(geom);
189        group->addChild(geode);       
190    }
191   
192    return group;
193}
194
195osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
196{
197    osgUtil::IntersectVisitor iv;
198    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
199
200    const osg::BoundingSphere& bs = subgraph->getBound();
201    float zMax = bs.center().z()+bs.radius();
202    float zMin = bs.center().z()-bs.radius();
203   
204    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
205    iv.addLineSegment(segDown.get());
206
207    subgraph->accept(iv);
208
209    if (iv.hits())
210    {
211        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
212        if (!hitList.empty())
213        {
214            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
215            return  ip;
216        }
217    }
218
219    return osg::Vec3(x,y,0.0f);
220}
221
222
223//////////////////////////////////////////////////////////////////////////////
224// MAIN SCENE GRAPH BUILDING FUNCTION
225//////////////////////////////////////////////////////////////////////////////
226
227void build_world(osg::Group *root, unsigned int testCase)
228{
229
230    // create terrain
231    osg::ref_ptr<osg::Geode> terrainGeode = 0;
232    {
233        terrainGeode = new osg::Geode;
234
235        osg::StateSet* stateset = new osg::StateSet();
236        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
237        if (image)
238        {
239            osg::Texture2D* texture = new osg::Texture2D;
240            texture->setImage(image);
241            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
242        }
243
244        terrainGeode->setStateSet( stateset );
245
246       
247        {
248            unsigned int numColumns = 38;
249            unsigned int numRows = 39;
250            unsigned int r, c;
251           
252            osg::Vec3 origin(0.0f,0.0f,0.0f);
253            osg::Vec3 size(1000.0f,1000.0f,250.0f);
254
255            osg::Geometry* geometry = new osg::Geometry;
256
257            osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));
258            osg::Vec2Array& tc = *(new osg::Vec2Array(numColumns*numRows));
259            osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
260
261            color[0].set(255,255,255,255);
262
263            float rowCoordDelta = size.y()/(float)(numRows-1);
264            float columnCoordDelta = size.x()/(float)(numColumns-1);
265
266            float rowTexDelta = 1.0f/(float)(numRows-1);
267            float columnTexDelta = 1.0f/(float)(numColumns-1);
268
269            // compute z range of z values of grid data so we can scale it.
270            float min_z = FLT_MAX;
271            float max_z = -FLT_MAX;
272            for(r=0;r<numRows;++r)
273            {
274                for(c=0;c<numColumns;++c)
275                {
276                    min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);
277                    max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);
278                }
279            }
280
281            float scale_z = size.z()/(max_z-min_z);
282
283            osg::Vec3 pos = origin;
284            osg::Vec2 tex(0.0f,0.0f);
285            int vi=0;
286            for(r=0;r<numRows;++r)
287            {
288                pos.x() = origin.x();
289                tex.x() = 0.0f;
290                for(c=0;c<numColumns;++c)
291                {
292                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z);
293                    tc[vi] = tex;
294                    pos.x()+=columnCoordDelta;
295                    tex.x()+=columnTexDelta;
296                    ++vi;
297                }
298                pos.y() += rowCoordDelta;
299                tex.y() += rowTexDelta;
300            }
301
302            geometry->setVertexArray(&v);
303            geometry->setTexCoordArray(0, &tc);
304            geometry->setColorArray(&color);
305            geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
306
307            for(r=0;r<numRows-1;++r)
308            {
309                osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));
310                geometry->addPrimitiveSet(&drawElements);
311                int ei=0;
312                for(c=0;c<numColumns;++c)
313                {
314                    drawElements[ei++] = (r+1)*numColumns+c;
315                    drawElements[ei++] = (r)*numColumns+c;
316                }
317            }
318           
319            osgUtil::SmoothingVisitor smoother;
320            smoother.smooth(*geometry);
321           
322            terrainGeode->addDrawable(geometry);
323        }
324       
325    }   
326
327
328    // create sphere segment
329    osg::ref_ptr<osgSim::SphereSegment> ss = 0;
330    {
331
332        switch(testCase)
333        {
334            case(0):       
335                ss = new osgSim::SphereSegment(
336                                computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
337                                510.0f, // radius
338                                osg::DegreesToRadians(135.0f),
339                                osg::DegreesToRadians(240.0f),
340                                osg::DegreesToRadians(-10.0f),
341                                osg::DegreesToRadians(30.0f),
342                                60);
343                break;
344            case(1):       
345                ss = new osgSim::SphereSegment(
346                                computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
347                                510.0f, // radius
348                                osg::DegreesToRadians(45.0f),
349                                osg::DegreesToRadians(240.0f),
350                                osg::DegreesToRadians(-10.0f),
351                                osg::DegreesToRadians(30.0f),
352                                60);
353                break;
354            case(2):       
355                ss = new osgSim::SphereSegment(
356                                computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
357                                510.0f, // radius
358                                osg::DegreesToRadians(5.0f),
359                                osg::DegreesToRadians(355.0f),
360                                osg::DegreesToRadians(-10.0f),
361                                osg::DegreesToRadians(30.0f),
362                                60);
363                break;
364            case(3):       
365                ss = new osgSim::SphereSegment(
366                                computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
367                                510.0f, // radius
368                                osg::DegreesToRadians(0.0f),
369                                osg::DegreesToRadians(360.0f),
370                                osg::DegreesToRadians(-10.0f),
371                                osg::DegreesToRadians(30.0f),
372                                60);
373                break;
374        };
375       
376        ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
377        ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
378#if 1
379        root->addChild(ss.get());
380#endif
381    }
382   
383#if 1   
384    root->addChild(ss->computeIntersectionSubgraph(osg::Matrixd::identity(), terrainGeode.get()));
385#else
386    osgSim::SphereSegment::LineList lines = ss->computeIntersection(osg::Matrixd::identity(), terrainGeode.get());
387    if (!lines.empty())
388    {
389        osg::notify(osg::NOTICE)<<"We've found intersections!!!!"<<std::endl;
390
391        osg::Geode* geode = new osg::Geode;
392        root->addChild(geode);
393
394        geode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
395
396        for(osgSim::SphereSegment::LineList::iterator itr=lines.begin();
397           itr!=lines.end();
398           ++itr)
399        {
400            osg::Geometry* geom = new osg::Geometry;
401            geode->addDrawable(geom);
402           
403            osg::Vec3Array* vertices = itr->get();
404            geom->setVertexArray(vertices);
405            geom->addPrimitiveSet(new osg::DrawArrays(GL_LINE_STRIP, 0, vertices->getNumElements()));
406        }
407    }
408    else
409    {
410       osg::notify(osg::NOTICE)<<"No intersections found"<<std::endl;
411    }
412#endif
413
414#if 0
415
416
417    osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
418   
419    overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
420
421    const osg::BoundingSphere& bs = terrainGeode->getBound();
422    osg::Group* overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5f);
423    overlaySubgraph->addChild(ss.get());
424    overlayNode->setOverlaySubgraph(overlaySubgraph);
425    overlayNode->setOverlayTextureSizeHint(2048);
426    overlayNode->addChild(terrainGeode.get());
427
428    root->addChild(overlayNode);
429   
430#else
431    root->addChild(terrainGeode.get());
432#endif
433
434
435    // create particle effects
436    {   
437        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
438
439        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
440        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
441        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
442
443        root->addChild(explosion);
444        root->addChild(smoke);
445        root->addChild(fire);
446    }
447   
448    // create particle effects
449    {   
450        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
451
452        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
453        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
454        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
455
456        root->addChild(explosion);
457        root->addChild(smoke);
458        root->addChild(fire);
459    }
460   
461    // create the moving models.
462    {
463        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
464    }
465}
466
467
468//////////////////////////////////////////////////////////////////////////////
469// main()
470//////////////////////////////////////////////////////////////////////////////
471
472
473int main(int argc, char **argv)
474{
475    // use an ArgumentParser object to manage the program arguments.
476    osg::ArgumentParser arguments(&argc,argv);
477   
478    // set up the usage document, in case we need to print out how to use this program.
479    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
480    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
481    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
482   
483
484    // construct the viewer.
485    osgProducer::Viewer viewer(arguments);
486
487    // set up the value with sensible default event handlers.
488    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
489
490    // get details on keyboard and mouse bindings used by the viewer.
491    viewer.getUsage(*arguments.getApplicationUsage());
492
493    // if user request help write it out to cout.
494    unsigned int testCase = 0;
495    if (arguments.read("-t", testCase)) {}
496
497
498    // if user request help write it out to cout.
499    if (arguments.read("-h") || arguments.read("--help"))
500    {
501        arguments.getApplicationUsage()->write(std::cout);
502        return 1;
503    }
504
505    // any option left unread are converted into errors to write out later.
506    arguments.reportRemainingOptionsAsUnrecognized();
507
508    // report any errors if they have occured when parsing the program aguments.
509    if (arguments.errors())
510    {
511        arguments.writeErrorMessages(std::cout);
512        return 1;
513    }
514   
515    osg::Group *root = new osg::Group;
516    build_world(root, testCase);
517   
518    // add a viewport to the viewer and attach the scene graph.
519    viewer.setSceneData(root);
520       
521    // create the windows and run the threads.
522    viewer.realize();
523
524    while( !viewer.done() )
525    {
526        // wait for all cull and draw threads to complete.
527        viewer.sync();
528
529        // update the scene by traversing it with the the update visitor which will
530        // call all node update callbacks and animations.
531        viewer.update();
532         
533        // fire off the cull and draw traversals of the scene.
534        viewer.frame();
535       
536    }
537   
538    // wait for all cull and draw threads to complete before exit.
539    viewer.sync();
540
541    return 0;
542}
Note: See TracBrowser for help on using the browser.