root/OpenSceneGraph/trunk/examples/osgsimulation/osgsimulation.cpp @ 6962

Revision 6962, 16.7 kB (checked in by robert, 8 years ago)

Added passing of arugments into viewer constructor

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1/* OpenSceneGraph example, osgsimulation.
2*
3*  Permission is hereby granted, free of charge, to any person obtaining a copy
4*  of this software and associated documentation files (the "Software"), to deal
5*  in the Software without restriction, including without limitation the rights
6*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7*  copies of the Software, and to permit persons to whom the Software is
8*  furnished to do so, subject to the following conditions:
9*
10*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
16*  THE SOFTWARE.
17*/
18
19#ifdef WIN32
20/////////////////////////////////////////////////////////////////////////////
21// Disable unavoidable warning messages:
22
23//  4103: used #pragma pack to change alignment
24//  4114: same type qualifier used more than once
25//  4201: nonstandard extension used : nameless struct/union
26//  4237: "keyword" reserved for future use
27//  4251: class needs to have dll-interface to export class
28//  4275: non DLL-interface class used as base for DLL-interface class
29//  4290: C++ Exception Specification ignored
30//  4503: decorated name length exceeded, name was truncated
31//  4786: string too long - truncated to 255 characters
32
33#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)
34
35#endif // WIN32
36
37#include <osgViewer/Viewer>
38#include <osgViewer/ViewerEventHandlers>
39
40#include <osg/Group>
41#include <osg/Geode>
42#include <osg/ShapeDrawable>
43#include <osg/Texture2D>
44#include <osg/PositionAttitudeTransform>
45#include <osg/MatrixTransform>
46#include <osg/CoordinateSystemNode>
47
48#include <osgDB/FileUtils>
49#include <osgDB/ReadFile>
50
51#include <osgText/Text>
52
53#include <osg/CoordinateSystemNode>
54
55#include <osgSim/OverlayNode>
56#include <osgSim/SphereSegment>
57
58#include <osgGA/NodeTrackerManipulator>
59#include <osgGA/StateSetManipulator>
60#include <osgGA/TrackballManipulator>
61#include <osgGA/FlightManipulator>
62#include <osgGA/DriveManipulator>
63#include <osgGA/KeySwitchMatrixManipulator>
64#include <osgGA/AnimationPathManipulator>
65#include <osgGA/TerrainManipulator>
66
67#include <iostream>
68
69osg::Node* createEarth()
70{
71    osg::TessellationHints* hints = new osg::TessellationHints;
72    hints->setDetailRatio(5.0f);
73
74   
75    osg::ShapeDrawable* sd = new osg::ShapeDrawable(new osg::Sphere(osg::Vec3(0.0,0.0,0.0), osg::WGS_84_RADIUS_POLAR), hints);
76   
77    osg::Geode* geode = new osg::Geode;
78    geode->addDrawable(sd);
79   
80    std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
81    geode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile(filename)));
82   
83    osg::CoordinateSystemNode* csn = new osg::CoordinateSystemNode;
84    csn->setEllipsoidModel(new osg::EllipsoidModel());
85    csn->addChild(geode);
86   
87    return csn;
88   
89}
90
91
92class ModelPositionCallback : public osg::NodeCallback
93{
94public:
95
96    ModelPositionCallback(double speed):
97        _latitude(0.0),
98        _longitude(0.0),
99        _height(100000.0),
100        _speed(speed)
101    {
102        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
103    }
104   
105    void updateParameters()
106    {
107        _longitude += _speed * ((2.0*osg::PI)/360.0)/20.0;
108    }
109
110
111    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
112    {
113        updateParameters();
114       
115        osg::NodePath nodePath = nv->getNodePath();
116
117        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
118        if (mt)
119        {
120            osg::CoordinateSystemNode* csn = 0;
121
122            // find coordinate system node from our parental chain
123            unsigned int i;
124            for(i=0; i<nodePath.size() && csn==0; ++i)
125            {
126                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
127            }
128           
129            if (csn)
130            {
131
132
133                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
134                if (ellipsoid)
135                {
136                    osg::Matrix inheritedMatrix;
137                    for(i+=1; i<nodePath.size()-1; ++i)
138                    {
139                        osg::Transform* transform = nodePath[i]->asTransform();
140                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
141                    }
142                   
143                    osg::Matrixd matrix(inheritedMatrix);
144
145                    //osg::Matrixd matrix;
146                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
147                    matrix.preMult(osg::Matrix::rotate(_rotation));
148                   
149                    mt->setMatrix(matrix);
150                }
151
152            }       
153        }
154           
155        traverse(node,nv);
156    }   
157   
158    double                  _latitude;
159    double                  _longitude;
160    double                  _height;
161    osg::Quat               _rotation;
162    double                  _speed;
163};
164
165
166class FindNamedNodeVisitor : public osg::NodeVisitor
167{
168public:
169    FindNamedNodeVisitor(const std::string& name):
170        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
171        _name(name) {}
172   
173    virtual void apply(osg::Node& node)
174    {
175        if (node.getName()==_name)
176        {
177            _foundNodes.push_back(&node);
178        }
179        traverse(node);
180    }
181   
182    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
183
184    std::string _name;
185    NodeList _foundNodes;
186};
187
188
189int main(int argc, char **argv)
190{
191    // use an ArgumentParser object to manage the program arguments.
192    osg::ArgumentParser arguments(&argc,argv);
193   
194    // set up the usage document, in case we need to print out how to use this program.
195    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
196    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
197    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
198   
199
200    // construct the viewer.
201    osgViewer::Viewer viewer(arguments);
202
203    // add the state manipulator
204    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
205   
206    // add the thread model handler
207    viewer.addEventHandler(new osgViewer::ThreadingHandler);
208
209    // add the window size toggle handler
210    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
211       
212    // add the stats handler
213    viewer.addEventHandler(new osgViewer::StatsHandler);
214       
215    // add the record camera path  handler
216    viewer.addEventHandler(new osgViewer::RecordCameraPathHandler);
217
218    // add the help handler
219    viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
220
221    // set the near far ration computation up.
222    viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
223    viewer.getCamera()->setNearFarRatio(0.000003f);
224
225
226    double speed = 1.0;
227    while (arguments.read("-f") || arguments.read("--fixed")) speed = 0.0;
228
229
230    osg::Quat rotation;
231    osg::Vec4 vec4;
232    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
233    {
234        osg::Quat local_rotate;
235        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
236       
237        rotation = rotation * local_rotate;
238    }
239
240    osg::NodeCallback* nc = 0;
241    std::string flightpath_filename;
242    while (arguments.read("--flight-path",flightpath_filename))
243    {
244        std::ifstream fin(flightpath_filename.c_str());
245        if (fin)
246        {
247            osg::AnimationPath* path = new osg::AnimationPath;
248            path->read(fin);
249            nc = new osg::AnimationPathCallback(path);
250        }
251    }
252   
253    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
254    std::string mode;
255    while (arguments.read("--tracker-mode",mode))
256    {
257        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
258        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
259        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
260        else
261        {
262            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
263            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
264            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
265            std::cout<<"    NODE_CENTER"<<std::endl;
266            return 1;
267        }
268    }
269   
270   
271    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
272    while (arguments.read("--rotation-mode",mode))
273    {
274        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
275        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
276        else
277        {
278            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
279            std::cout<<"    TRACKBALL"<<std::endl;
280            std::cout<<"    ELEVATION_AZIM"<<std::endl;
281            return 1;
282        }
283    }
284
285    bool useOverlay = true;
286    while (arguments.read("--no-overlay") || arguments.read("-n")) useOverlay = false;
287   
288    osgSim::OverlayNode::OverlayTechnique technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
289    while (arguments.read("--object")) technique = osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
290    while (arguments.read("--ortho") || arguments.read("--orthographic")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY;
291    while (arguments.read("--persp") || arguments.read("--perspective")) technique = osgSim::OverlayNode::VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY;
292
293    std::string pathfile;
294    while (arguments.read("-p",pathfile)) {}
295
296
297    // if user request help write it out to cout.
298    if (arguments.read("-h") || arguments.read("--help"))
299    {
300        arguments.getApplicationUsage()->write(std::cout);
301        return 1;
302    }
303   
304   
305    osg::ref_ptr<osgGA::NodeTrackerManipulator> tm;
306   
307    std::string overlayFilename;
308    while(arguments.read("--overlay", overlayFilename)) {}
309
310    // read the scene from the list of file specified commandline args.
311    osg::ref_ptr<osg::Node> root = osgDB::readNodeFiles(arguments);
312
313    if (!root) root = createEarth();
314
315    if (!root) return 0;
316
317
318    if (!overlayFilename.empty())
319    {
320        //osg::Object *pObj = osgDB::readObjectFile("alaska_clean.shp");
321        //osg::ref_ptr<osg::Geode> shapefile = dynamic_cast<osg::Geode*> (pObj);
322        //
323        //ConvertLatLon2EllipsoidCoordinates latlon2em;
324        //shapefile->accept(latlon2em);
325
326        osg::ref_ptr<osg::Node> shapefile = osgDB::readNodeFile(overlayFilename);
327       
328        if (!shapefile)
329        {
330            osg::notify(osg::NOTICE)<<"File `"<<overlayFilename<<"` not found"<<std::endl;
331            return 1;
332        }
333
334        osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
335        if (csn)
336        {
337
338            osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);
339            overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
340            overlayNode->setOverlaySubgraph(shapefile.get());
341            overlayNode->setOverlayTextureSizeHint(1024);
342
343            // insert the OverlayNode between the coordinate system node and its children.
344            for(unsigned int i=0; i<csn->getNumChildren(); ++i)
345            {
346                overlayNode->addChild( csn->getChild(i) );
347            }
348
349            csn->removeChildren(0, csn->getNumChildren());
350            csn->addChild(overlayNode);
351
352            viewer.setSceneData(csn);
353        }
354        else
355        {
356            osgSim::OverlayNode* overlayNode = new osgSim::OverlayNode(technique);
357            overlayNode->getOrCreateStateSet()->setTextureAttribute(1, new osg::TexEnv(osg::TexEnv::DECAL));
358            overlayNode->setOverlaySubgraph(shapefile.get());
359            overlayNode->setOverlayTextureSizeHint(1024);
360            overlayNode->addChild(root.get());
361
362            viewer.setSceneData(overlayNode);
363        }
364    }
365    else
366    {
367   
368
369        // add a viewport to the viewer and attach the scene graph.
370        viewer.setSceneData(root.get());
371
372        osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
373        if (csn)
374        {
375
376            osg::ref_ptr<osgSim::OverlayNode> overlayNode;
377            if (useOverlay)
378            {
379                overlayNode = new osgSim::OverlayNode(technique);
380
381                // insert the OverlayNode between the coordinate system node and its children.
382                for(unsigned int i=0; i<csn->getNumChildren(); ++i)
383                {
384                    overlayNode->addChild( csn->getChild(i) );
385                }
386
387                csn->removeChildren(0, csn->getNumChildren());
388                csn->addChild(overlayNode.get());
389
390                // tell the overlay node to continously update its overlay texture
391                // as we know we'll be tracking a moving target.
392                overlayNode->setContinuousUpdate(true);
393            }
394
395
396            osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
397            if (cessna)
398            {
399                double s = 200000.0 / cessna->getBound().radius();
400
401                osg::MatrixTransform* scaler = new osg::MatrixTransform;
402                scaler->addChild(cessna);
403                scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
404                scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);       
405
406                if (false)
407                {
408                    osgSim::SphereSegment* ss = new osgSim::SphereSegment(
409                                        osg::Vec3(0.0f,0.0f,0.0f), // center
410                                        19.9f, // radius
411                                        osg::DegreesToRadians(135.0f),
412                                        osg::DegreesToRadians(240.0f),
413                                        osg::DegreesToRadians(-10.0f),
414                                        osg::DegreesToRadians(30.0f),
415                                        60);
416
417                    scaler->addChild(ss);
418                }
419
420                osg::MatrixTransform* mt = new osg::MatrixTransform;
421                mt->addChild(scaler);
422
423
424                if (!nc) nc = new ModelPositionCallback(speed);
425
426                mt->setUpdateCallback(nc);
427
428                csn->addChild(mt);
429
430                // if we are using an overaly node, use the cessna subgraph as the overlay subgraph
431                if (overlayNode.valid())
432                {
433                    overlayNode->setOverlaySubgraph(mt);
434                }
435
436                tm = new osgGA::NodeTrackerManipulator;
437                tm->setTrackerMode(trackerMode);
438                tm->setRotationMode(rotationMode);
439                tm->setTrackNode(scaler);
440            }
441            else
442            {
443                 std::cout<<"Failed to read cessna.osg"<<std::endl;
444            }
445
446        }   
447    }
448
449    // set up camera manipulators.
450    {
451        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
452
453        if (tm.valid()) keyswitchManipulator->addMatrixManipulator( '0', "NodeTracker", tm.get() );
454
455        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
456        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
457        keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );
458        keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );
459
460        if (!pathfile.empty())
461        {
462            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
463            if (apm || !apm->valid())
464            {
465                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
466                keyswitchManipulator->addMatrixManipulator( '5', "Path", apm );
467                keyswitchManipulator->selectMatrixManipulator(num);
468            }
469        }
470
471        viewer.setCameraManipulator( keyswitchManipulator.get() );
472    }
473
474    // viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
475
476    return viewer.run();
477}
Note: See TracBrowser for help on using the browser.