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

Revision 3996, 11.2 kB (checked in by robert, 9 years ago)

Reverted back to not test version of osgsimulation

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1#ifdef WIN32
2/////////////////////////////////////////////////////////////////////////////
3// Disable unavoidable warning messages:
4
5//  4103: used #pragma pack to change alignment
6//  4114: same type qualifier used more than once
7//  4201: nonstandard extension used : nameless struct/union
8//  4237: "keyword" reserved for future use
9//  4251: class needs to have dll-interface to export class
10//  4275: non DLL-interface class used as base for DLL-interface class
11//  4290: C++ Exception Specification ignored
12//  4503: decorated name length exceeded, name was truncated
13//  4786: string too long - truncated to 255 characters
14
15#pragma warning(disable : 4103 4114 4201 4237 4251 4275 4290 4503 4335 4786)
16
17#endif // WIN32
18
19#include <osgProducer/Viewer>
20
21#include <osg/Group>
22#include <osg/Geode>
23#include <osg/ShapeDrawable>
24#include <osg/Texture2D>
25#include <osg/PositionAttitudeTransform>
26#include <osg/MatrixTransform>
27#include <osg/CoordinateSystemNode>
28
29#include <osgDB/FileUtils>
30#include <osgDB/ReadFile>
31
32#include <osgText/Text>
33
34#include <osgTerrain/DataSet>
35
36#include <osgGA/NodeTrackerManipulator>
37
38class GraphicsContext {
39    public:
40        GraphicsContext()
41        {
42            rs = new Producer::RenderSurface;
43            rs->setWindowRectangle(0,0,1,1);
44            rs->useBorder(false);
45            rs->useConfigEventThread(false);
46            rs->realize();
47        }
48
49        virtual ~GraphicsContext()
50        {
51        }
52       
53    private:
54        Producer::ref_ptr<Producer::RenderSurface> rs;
55};
56
57osg::Node* createEarth()
58{
59    osg::ref_ptr<osg::Node> scene;
60   
61    {
62        std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
63
64        // make osgTerrain::DataSet quieter..
65        osgTerrain::DataSet::setNotifyOffset(1);
66
67        osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
68
69        // register the source imagery
70        {
71            osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
72
73            source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
74            source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
75
76            source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
77            source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
78
79            dataSet->addSource(source);
80        }
81
82        // set up destination database paramters.
83        dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
84        dataSet->setConvertFromGeographicToGeocentric(true);
85        dataSet->setDestinationName("test.osg");
86
87        // load the source data and record sizes.
88        dataSet->loadSources();
89
90        GraphicsContext context;
91        dataSet->createDestination(30);
92
93        if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
94        else dataSet->writeDestination();
95       
96        scene = dataSet->getDestinationRootNode();
97    }
98       
99    return scene.release();
100   
101}
102
103
104class ModelPositionCallback : public osg::NodeCallback
105{
106public:
107
108    ModelPositionCallback():
109        _latitude(0.0),
110        _longitude(0.0),
111        _height(100000.0)
112    {
113        _rotation.makeRotate(osg::DegreesToRadians(90.0),0.0,0.0,1.0);
114    }
115   
116    void updateParameters()
117    {
118        _longitude += ((2.0*osg::PI)/360.0)/20.0;
119    }
120
121
122    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
123    {
124        updateParameters();
125       
126        osg::NodePath nodePath = nv->getNodePath();
127
128        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
129        if (mt)
130        {
131            osg::CoordinateSystemNode* csn = 0;
132
133            // find coordinate system node from our parental chain
134            unsigned int i;
135            for(i=0; i<nodePath.size() && csn==0; ++i)
136            {
137                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
138            }
139           
140            if (csn)
141            {
142
143
144                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
145                if (ellipsoid)
146                {
147                    osg::Matrixd matrix;
148                    for(i+=1; i<nodePath.size()-1; ++i)
149                    {
150                        osg::Transform* transform = nodePath[i]->asTransform();
151                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
152                    }
153
154                    //osg::Matrixd matrix;
155                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
156                    matrix.preMult(osg::Matrixd::rotate(_rotation));
157                   
158                    mt->setMatrix(matrix);
159                }
160
161            }       
162        }
163           
164        traverse(node,nv);
165    }   
166   
167    double                  _latitude;
168    double                  _longitude;
169    double                  _height;
170    osg::Quat               _rotation;
171};
172
173
174class FindNamedNodeVisitor : public osg::NodeVisitor
175{
176public:
177    FindNamedNodeVisitor(const std::string& name):
178        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
179        _name(name) {}
180   
181    virtual void apply(osg::Node& node)
182    {
183        if (node.getName()==_name)
184        {
185            _foundNodes.push_back(&node);
186        }
187        traverse(node);
188    }
189   
190    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
191
192    std::string _name;
193    NodeList _foundNodes;
194};
195
196
197int main(int argc, char **argv)
198{
199    // use an ArgumentParser object to manage the program arguments.
200    osg::ArgumentParser arguments(&argc,argv);
201   
202    // set up the usage document, in case we need to print out how to use this program.
203    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
204    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
205    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
206   
207
208    // construct the viewer.
209    osgProducer::Viewer viewer(arguments);
210
211    // set up the value with sensible default event handlers.
212    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
213
214    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
215    viewer.getCullSettings().setNearFarRatio(0.00001f);
216
217    // get details on keyboard and mouse bindings used by the viewer.
218    viewer.getUsage(*arguments.getApplicationUsage());
219
220    osg::Quat rotation;
221    osg::Vec4 vec4;
222    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
223    {
224        osg::Quat local_rotate;
225        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
226       
227        rotation = rotation * local_rotate;
228    }
229
230    osg::NodeCallback* nc = 0;
231    std::string flightpath_filename;
232    while (arguments.read("--flight-path",flightpath_filename))
233    {
234        std::ifstream fin(flightpath_filename.c_str());
235        if (fin)
236        {
237            osg::AnimationPath* path = new osg::AnimationPath;
238            path->read(fin);
239            nc = new osg::AnimationPathCallback(path);
240        }
241    }
242   
243    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
244    std::string mode;
245    while (arguments.read("--tracker-mode",mode))
246    {
247        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
248        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
249        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
250        else
251        {
252            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
253            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
254            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
255            std::cout<<"    NODE_CENTER"<<std::endl;
256            return 1;
257        }
258    }
259   
260   
261    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
262    while (arguments.read("--rotation-mode",mode))
263    {
264        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
265        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
266        else
267        {
268            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
269            std::cout<<"    TRACKBALL"<<std::endl;
270            std::cout<<"    ELEVATION_AZIM"<<std::endl;
271            return 1;
272        }
273    }
274
275    // if user request help write it out to cout.
276    if (arguments.read("-h") || arguments.read("--help"))
277    {
278        arguments.getApplicationUsage()->write(std::cout);
279        return 1;
280    }
281
282    // any option left unread are converted into errors to write out later.
283    arguments.reportRemainingOptionsAsUnrecognized();
284
285    // report any errors if they have occured when parsing the program aguments.
286    if (arguments.errors())
287    {
288        arguments.writeErrorMessages(std::cout);
289        return 1;
290    }
291   
292    osg::ref_ptr<osg::Node> root = createEarth();
293   
294    if (!root) return 0;
295
296    // add a viewport to the viewer and attach the scene graph.
297    viewer.setSceneData(root.get());
298
299    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
300    if (csn)
301    {
302        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
303        if (cessna)
304        {
305            double s = 30000.0 / cessna->getBound().radius();
306       
307            osg::MatrixTransform* scaler = new osg::MatrixTransform;
308            scaler->addChild(cessna);
309            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
310            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);       
311       
312            osg::MatrixTransform* mt = new osg::MatrixTransform;
313            mt->addChild(scaler);
314
315
316            if (!nc) nc = new ModelPositionCallback;
317
318            mt->setUpdateCallback(nc);
319
320            csn->addChild(mt);
321
322            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
323            tm->setTrackerMode(trackerMode);
324            tm->setRotationMode(rotationMode);
325            tm->setTrackNode(scaler);
326
327            unsigned int num = viewer.addCameraManipulator(tm);
328            viewer.selectCameraManipulator(num);
329        }
330        else
331        {
332             std::cout<<"Failed to read cessna.osg"<<std::endl;
333        }
334    }   
335
336       
337
338    // create the windows and run the threads.
339    viewer.realize();
340
341    while( !viewer.done() )
342    {
343        // wait for all cull and draw threads to complete.
344        viewer.sync();
345
346        // update the scene by traversing it with the the update visitor which will
347        // call all node update callbacks and animations.
348        viewer.update();
349         
350        // fire off the cull and draw traversals of the scene.
351        viewer.frame();
352       
353    }
354   
355    // wait for all cull and draw threads to complete before exit.
356    viewer.sync();
357
358    return 0;
359}
Note: See TracBrowser for help on using the browser.