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

Revision 3725, 11.2 kB (checked in by don, 10 years ago)

Added pragma to shut VS 6 up.

  • 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
114    void updateParameters()
115    {
116        _latitude -= ((2.0*osg::PI)/360.0)/20.0;
117    }
118
119
120    virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
121    {
122        updateParameters();
123       
124        osg::NodePath nodePath = nv->getNodePath();
125
126        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
127        if (mt)
128        {
129            osg::CoordinateSystemNode* csn = 0;
130
131            // find coordinate system node from our parental chain
132            unsigned int i;
133            for(i=0; i<nodePath.size() && csn==0; ++i)
134            {
135                csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);
136            }
137           
138            if (csn)
139            {
140
141
142                osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
143                if (ellipsoid)
144                {
145                    osg::Matrixd matrix;
146                    for(i+=1; i<nodePath.size()-1; ++i)
147                    {
148                        osg::Transform* transform = nodePath[i]->asTransform();
149                        if (transform) transform->computeLocalToWorldMatrix(matrix, nv);
150                    }
151
152                    //osg::Matrixd matrix;
153                    ellipsoid->computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix);
154                    matrix.preMult(osg::Matrixd::rotate(_rotation));
155                   
156                    mt->setMatrix(matrix);
157                }
158
159            }       
160        }
161           
162        traverse(node,nv);
163    }   
164   
165    double                  _latitude;
166    double                  _longitude;
167    double                  _height;
168    osg::Quat               _rotation;
169};
170
171
172class FindNamedNodeVisitor : public osg::NodeVisitor
173{
174public:
175    FindNamedNodeVisitor(const std::string& name):
176        osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
177        _name(name) {}
178   
179    virtual void apply(osg::Node& node)
180    {
181        if (node.getName()==_name)
182        {
183            _foundNodes.push_back(&node);
184        }
185        traverse(node);
186    }
187   
188    typedef std::vector< osg::ref_ptr<osg::Node> > NodeList;
189
190    std::string _name;
191    NodeList _foundNodes;
192};
193
194
195int main(int argc, char **argv)
196{
197    // use an ArgumentParser object to manage the program arguments.
198    osg::ArgumentParser arguments(&argc,argv);
199   
200    // set up the usage document, in case we need to print out how to use this program.
201    arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.");
202    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye");
203    arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
204   
205
206    // construct the viewer.
207    osgProducer::Viewer viewer(arguments);
208
209    // set up the value with sensible default event handlers.
210    viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
211
212    viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
213    viewer.getCullSettings().setNearFarRatio(0.00001f);
214
215    // get details on keyboard and mouse bindings used by the viewer.
216    viewer.getUsage(*arguments.getApplicationUsage());
217
218    osg::Quat rotation;
219    osg::Vec4 vec4;
220    while (arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]))
221    {
222        osg::Quat local_rotate;
223        local_rotate.makeRotate(osg::DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3]);
224       
225        rotation = rotation * local_rotate;
226    }
227
228    osg::NodeCallback* nc = 0;
229    std::string flightpath_filename;
230    while (arguments.read("--flight-path",flightpath_filename))
231    {
232        std::ifstream fin(flightpath_filename.c_str());
233        if (fin)
234        {
235            osg::AnimationPath* path = new osg::AnimationPath;
236            path->read(fin);
237            nc = new osg::AnimationPathCallback(path);
238        }
239    }
240   
241    osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
242    std::string mode;
243    while (arguments.read("--tracker-mode",mode))
244    {
245        if (mode=="NODE_CENTER_AND_ROTATION") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_ROTATION;
246        else if (mode=="NODE_CENTER_AND_AZIM") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER_AND_AZIM;
247        else if (mode=="NODE_CENTER") trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
248        else
249        {
250            std::cout<<"Unrecognized --tracker-mode option "<<mode<<", valid options are:"<<std::endl;
251            std::cout<<"    NODE_CENTER_AND_ROTATION"<<std::endl;
252            std::cout<<"    NODE_CENTER_AND_AZIM"<<std::endl;
253            std::cout<<"    NODE_CENTER"<<std::endl;
254            return 1;
255        }
256    }
257   
258   
259    osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
260    while (arguments.read("--rotation-mode",mode))
261    {
262        if (mode=="TRACKBALL") rotationMode = osgGA::NodeTrackerManipulator::TRACKBALL;
263        else if (mode=="ELEVATION_AZIM") rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
264        else
265        {
266            std::cout<<"Unrecognized --rotation-mode option "<<mode<<", valid options are:"<<std::endl;
267            std::cout<<"    TRACKBALL"<<std::endl;
268            std::cout<<"    ELEVATION_AZIM"<<std::endl;
269            return 1;
270        }
271    }
272
273    // if user request help write it out to cout.
274    if (arguments.read("-h") || arguments.read("--help"))
275    {
276        arguments.getApplicationUsage()->write(std::cout);
277        return 1;
278    }
279
280    // any option left unread are converted into errors to write out later.
281    arguments.reportRemainingOptionsAsUnrecognized();
282
283    // report any errors if they have occured when parsing the program aguments.
284    if (arguments.errors())
285    {
286        arguments.writeErrorMessages(std::cout);
287        return 1;
288    }
289   
290    osg::ref_ptr<osg::Node> root = createEarth();
291   
292    if (!root) return 0;
293
294    // add a viewport to the viewer and attach the scene graph.
295    viewer.setSceneData(root.get());
296
297    osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
298    if (csn)
299    {
300        osg::Node* cessna = osgDB::readNodeFile("cessna.osg");
301        if (cessna)
302        {
303            double s = 30000.0 / cessna->getBound().radius();
304       
305            osg::MatrixTransform* scaler = new osg::MatrixTransform;
306            scaler->addChild(cessna);
307            scaler->setMatrix(osg::Matrixd::scale(s,s,s)*osg::Matrixd::rotate(rotation));
308            scaler->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL,osg::StateAttribute::ON);       
309       
310            osg::MatrixTransform* mt = new osg::MatrixTransform;
311            mt->addChild(scaler);
312
313
314            if (!nc) nc = new ModelPositionCallback;
315
316            mt->setUpdateCallback(nc);
317
318            csn->addChild(mt);
319
320            osgGA::NodeTrackerManipulator* tm = new osgGA::NodeTrackerManipulator;
321            tm->setTrackerMode(trackerMode);
322            tm->setRotationMode(rotationMode);
323            tm->setTrackNode(scaler);
324
325            unsigned int num = viewer.addCameraManipulator(tm);
326            viewer.selectCameraManipulator(num);
327        }
328        else
329        {
330             std::cout<<"Failed to read cessna.osg"<<std::endl;
331        }
332    }   
333
334       
335
336    // create the windows and run the threads.
337    viewer.realize();
338
339    while( !viewer.done() )
340    {
341        // wait for all cull and draw threads to complete.
342        viewer.sync();
343
344        // update the scene by traversing it with the the update visitor which will
345        // call all node update callbacks and animations.
346        viewer.update();
347         
348        // fire off the cull and draw traversals of the scene.
349        viewer.frame();
350       
351    }
352   
353    // wait for all cull and draw threads to complete before exit.
354    viewer.sync();
355
356    return 0;
357}
Note: See TracBrowser for help on using the browser.