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

Revision 4512, 15.2 kB (checked in by robert, 9 years ago)

Added triangle index functor to src/osgUtil/SphereSegment.cpp for computing
the intersection between an indivual geometry and the sphere segment.

Converted the terrain in osgspheresegment to be an osg::Geometry based
drawable rather than a osg::ShapeDrawable?/osg::HeightField? one to make it
more practicle to use as a test for the new SphereSegment? intersection code.

  • 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::SCREEN_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        geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES,0,vertices->getNumElements()));
178
179        osg::Geode* geode = new osg::Geode;
180        geode->addDrawable(geom);
181        group->addChild(geode);       
182    }
183   
184    return group;
185}
186
187osg::Vec3 computeTerrainIntersection(osg::Node* subgraph,float x,float y)
188{
189    osgUtil::IntersectVisitor iv;
190    osg::ref_ptr<osg::LineSegment> segDown = new osg::LineSegment;
191
192    const osg::BoundingSphere& bs = subgraph->getBound();
193    float zMax = bs.center().z()+bs.radius();
194    float zMin = bs.center().z()-bs.radius();
195   
196    segDown->set(osg::Vec3(x,y,zMin),osg::Vec3(x,y,zMax));
197    iv.addLineSegment(segDown.get());
198
199    subgraph->accept(iv);
200
201    if (iv.hits())
202    {
203        osgUtil::IntersectVisitor::HitList& hitList = iv.getHitList(segDown.get());
204        if (!hitList.empty())
205        {
206            osg::Vec3 ip = hitList.front().getWorldIntersectPoint();
207            return  ip;
208        }
209    }
210
211    return osg::Vec3(x,y,0.0f);
212}
213
214
215//////////////////////////////////////////////////////////////////////////////
216// MAIN SCENE GRAPH BUILDING FUNCTION
217//////////////////////////////////////////////////////////////////////////////
218
219void build_world(osg::Group *root)
220{
221
222    // create terrain
223    osg::ref_ptr<osg::Geode> terrainGeode = 0;
224    {
225        terrainGeode = new osg::Geode;
226
227        osg::StateSet* stateset = new osg::StateSet();
228        osg::Image* image = osgDB::readImageFile("Images/lz.rgb");
229        if (image)
230        {
231            osg::Texture2D* texture = new osg::Texture2D;
232            texture->setImage(image);
233            stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
234        }
235
236        terrainGeode->setStateSet( stateset );
237
238       
239        {
240            unsigned int numColumns = 38;
241            unsigned int numRows = 39;
242            unsigned int r, c;
243           
244            osg::Vec3 origin(0.0f,0.0f,0.0f);
245            osg::Vec3 size(1000.0f,1000.0f,250.0f);
246
247            osg::Geometry* geometry = new osg::Geometry;
248
249            osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));
250            osg::Vec2Array& tc = *(new osg::Vec2Array(numColumns*numRows));
251            osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));
252
253            color[0].set(255,255,255,255);
254
255            float rowCoordDelta = size.y()/(float)(numRows-1);
256            float columnCoordDelta = size.x()/(float)(numColumns-1);
257
258            float rowTexDelta = 1.0f/(float)(numRows-1);
259            float columnTexDelta = 1.0f/(float)(numColumns-1);
260
261            // compute z range of z values of grid data so we can scale it.
262            float min_z = FLT_MAX;
263            float max_z = -FLT_MAX;
264            for(r=0;r<numRows;++r)
265            {
266                for(c=0;c<numColumns;++c)
267                {
268                    min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);
269                    max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);
270                }
271            }
272
273            float scale_z = size.z()/(max_z-min_z);
274
275            osg::Vec3 pos = origin;
276            osg::Vec2 tex(0.0f,0.0f);
277            int vi=0;
278            for(r=0;r<numRows;++r)
279            {
280                pos.x() = origin.x();
281                tex.x() = 0.0f;
282                for(c=0;c<numColumns;++c)
283                {
284                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z);
285                    tc[vi] = tex;
286                    pos.x()+=columnCoordDelta;
287                    tex.x()+=columnTexDelta;
288                    ++vi;
289                }
290                pos.y() += rowCoordDelta;
291                tex.y() += rowTexDelta;
292            }
293
294            geometry->setVertexArray(&v);
295            geometry->setTexCoordArray(0, &tc);
296            geometry->setColorArray(&color);
297            geometry->setColorBinding(osg::Geometry::BIND_OVERALL);
298
299            for(r=0;r<numRows-1;++r)
300            {
301                osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));
302                geometry->addPrimitiveSet(&drawElements);
303                int ei=0;
304                for(c=0;c<numColumns;++c)
305                {
306                    drawElements[ei++] = (r+1)*numColumns+c;
307                    drawElements[ei++] = (r)*numColumns+c;
308                }
309            }
310           
311            osgUtil::SmoothingVisitor smoother;
312            smoother.smooth(*geometry);
313           
314            terrainGeode->addDrawable(geometry);
315        }
316       
317    }   
318
319
320    // create sphere segment
321    osg::ref_ptr<osgSim::SphereSegment> ss = 0;
322    {
323        ss = new osgSim::SphereSegment(
324                        computeTerrainIntersection(terrainGeode.get(),550.0f,780.0f), // center
325                        500.0f, // radius
326                        osg::DegreesToRadians(135.0f),
327                        osg::DegreesToRadians(245.0f),
328                        osg::DegreesToRadians(-10.0f),
329                        osg::DegreesToRadians(30.0f),
330                        60);
331        ss->setAllColors(osg::Vec4(1.0f,1.0f,1.0f,0.5f));
332        ss->setSideColor(osg::Vec4(0.0f,1.0f,1.0f,0.1f));
333
334        root->addChild(ss.get());
335    }
336
337    osgSim::SphereSegment::LineList lines = ss->computeIntersection(osg::Matrixd::identity(), terrainGeode.get());
338    if (!lines.empty())
339    {
340       osg::notify(osg::NOTICE)<<"We've found intersections!!!!"<<std::endl;
341    }
342    else
343    {
344       osg::notify(osg::NOTICE)<<"No intersections found"<<std::endl;
345    }
346
347#if 1
348
349
350    osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode;
351
352    const osg::BoundingSphere& bs = terrainGeode->getBound();
353    osg::Group* overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5f);
354    overlaySubgraph->addChild(ss.get());
355    overlayNode->setOverlaySubgraph(overlaySubgraph);
356    overlayNode->setOverlayTextureSizeHint(2048);
357    overlayNode->addChild(terrainGeode.get());
358
359    root->addChild(overlayNode);
360   
361   
362#else
363    root->addChild(terrainGeode);
364#endif
365
366
367    // create particle effects
368    {   
369        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),100.0f,100.0f);
370
371        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 10.0f);
372        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 10.0f);
373        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 10.0f);
374
375        root->addChild(explosion);
376        root->addChild(smoke);
377        root->addChild(fire);
378    }
379   
380    // create particle effects
381    {   
382        osg::Vec3 position = computeTerrainIntersection(terrainGeode.get(),200.0f,100.0f);
383
384        osgParticle::ExplosionEffect* explosion = new osgParticle::ExplosionEffect(position, 1.0f);
385        osgParticle::SmokeEffect* smoke = new osgParticle::SmokeEffect(position, 1.0f);
386        osgParticle::FireEffect* fire = new osgParticle::FireEffect(position, 1.0f);
387
388        root->addChild(explosion);
389        root->addChild(smoke);
390        root->addChild(fire);
391    }
392   
393    // create the moving models.
394    {
395        root->addChild(createMovingModel(osg::Vec3(500.0f,500.0f,500.0f),100.0f));
396    }
397}
398
399
400//////////////////////////////////////////////////////////////////////////////
401// main()
402//////////////////////////////////////////////////////////////////////////////
403
404
405int main(int argc, char **argv)
406{
407    // use an ArgumentParser object to manage the program arguments.
408    osg::ArgumentParser arguments(&argc,argv);
409   
410    // set up the usage document, in case we need to print out how to use this program.
411    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
412    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
413    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
414   
415
416    // construct the viewer.
417    osgProducer::Viewer viewer(arguments);
418
419    // set up the value with sensible default event handlers.
420    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
421
422    // get details on keyboard and mouse bindings used by the viewer.
423    viewer.getUsage(*arguments.getApplicationUsage());
424
425    // if user request help write it out to cout.
426    if (arguments.read("-h") || arguments.read("--help"))
427    {
428        arguments.getApplicationUsage()->write(std::cout);
429        return 1;
430    }
431
432    // any option left unread are converted into errors to write out later.
433    arguments.reportRemainingOptionsAsUnrecognized();
434
435    // report any errors if they have occured when parsing the program aguments.
436    if (arguments.errors())
437    {
438        arguments.writeErrorMessages(std::cout);
439        return 1;
440    }
441   
442    osg::Group *root = new osg::Group;
443    build_world(root);
444   
445    // add a viewport to the viewer and attach the scene graph.
446    viewer.setSceneData(root);
447       
448    // create the windows and run the threads.
449    viewer.realize();
450
451    while( !viewer.done() )
452    {
453        // wait for all cull and draw threads to complete.
454        viewer.sync();
455
456        // update the scene by traversing it with the the update visitor which will
457        // call all node update callbacks and animations.
458        viewer.update();
459         
460        // fire off the cull and draw traversals of the scene.
461        viewer.frame();
462       
463    }
464   
465    // wait for all cull and draw threads to complete before exit.
466    viewer.sync();
467
468    return 0;
469}
Note: See TracBrowser for help on using the browser.