source: osgVisual/src/core/visual_core.cpp @ 70

Last change on this file since 70 was 70, checked in by Torben Dannhauer, 14 years ago

sky silverlining vereinfacht.

File size: 15.4 KB
Line 
1/* -*-c++-*- osgVisual - Copyright (C) 2009-2010 Torben Dannhauer
2 *
3 * This library is based on OpenSceneGraph, open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version.  The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * osgVisual requires for some proprietary modules a license from the correspondig manufacturer.
9 * You have to aquire licenses for all used proprietary modules.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * OpenSceneGraph Public License for more details.
15*/
16
17#include <visual_core.h>
18
19using namespace osgVisual;
20
21visual_core::visual_core(osg::ArgumentParser& arguments_) : arguments(arguments_)
22{
23        OSG_NOTIFY( osg::ALWAYS ) << "visual_core instantiated." << std::endl;
24
25        // Setup pathes
26        osgDB::Registry::instance()->getDataFilePathList().push_back( "D:\\DA\\osgVisual\\models" );
27       
28        // Setup viewer
29        viewer = new osgViewer::Viewer(arguments);
30
31        // Setup coordinate system node
32        rootNode = new osg::CoordinateSystemNode;
33        rootNode->setEllipsoidModel(new osg::EllipsoidModel());
34
35        // Test memory leak (todo)
36        //double* test = new double[1000];
37
38        #ifdef USE_SPACENAVIGATOR
39                mouse = NULL;
40        #endif
41
42        //osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( 8 );
43}
44
45visual_core::~visual_core(void)
46{
47        // shut osgVisual down
48        shutdown();
49
50        OSG_NOTIFY( osg::ALWAYS ) << "visual_core destroyed." << std::endl;
51
52}
53
54void visual_core::initialize()
55{
56        OSG_NOTIFY( osg::ALWAYS ) << "Initialize visual_core..." << std::endl;
57
58        // Add manipulators for user interaction
59        addManipulators();
60
61        // Load terrain
62        //loadTerrain(arguments);
63
64        // Show model
65        viewer->setSceneData( rootNode );
66
67#ifdef USE_DISTORTION
68        // Initialize distortion
69        distortion = new visual_distortion( viewer, arguments );
70        distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
71#endif
72
73#ifdef USE_SKY_SILVERLINING
74        // Initialize sky
75        sky = new visual_skySilverLining( viewer );
76        #ifdef USE_DISTORTION
77                if ( distortion.valid() )
78                {
79                        OSG_NOTIFY( osg::ALWAYS ) << "Using sky with distortion." << std::endl;
80                        sky->init( distortion->getDistortedSceneGraph(), rootNode);
81                }
82        #else
83                OSG_NOTIFY( osg::ALWAYS ) << "Using Sky without distortion." << std::endl;
84                sky->init(NULL, rootNode);
85        #endif
86#endif
87
88        // Initialize DataIO interface
89        visual_dataIO::getInstance()->init(viewer, arguments);
90
91        loadTerrain(arguments);
92
93        // All modules are initialized - now check arguments for any unused parameter.
94        checkCommandlineArgumentsForFinalErrors();
95
96        // create the windows and run the threads.
97        viewer->realize();
98
99        // setup scenery
100        setupScenery();
101
102        // Run visual main loop
103        mainLoop();
104}
105
106void visual_core::mainLoop()
107{
108        // run main loop
109        while( !viewer->done() )
110    {
111                // next frame please....
112        viewer->advance();
113                std::cout << "New frame----------------------------" << std::endl;
114
115                /*double hat, hot, lat, lon, height;
116                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
117                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
118                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
119       
120                // perform all queued events
121                viewer->eventTraversal();
122
123                // update the scene by traversing it with the the update visitor which will
124        // call all node update callbacks and animations.
125       
126        viewer->updateTraversal();
127               
128        // Render the Frame.
129        viewer->renderingTraversals();
130
131    }   // END WHILE
132}
133
134void visual_core::shutdown()
135{
136        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
137
138        // Unset scene data
139        viewer->setSceneData( NULL );
140
141#ifdef USE_SKY_SILVERLINING
142        // Shutdown sky
143        if( sky.valid() )
144                sky->shutdown();
145#endif
146
147#ifdef USE_DISTORTION
148        // Shutdown distortion
149        if( distortion.valid() )
150                distortion->shutdown();
151#endif
152
153        // Shutdown dataIO
154        visual_dataIO::getInstance()->shutdown();
155
156       
157#ifdef USE_SPACENAVIGATOR
158        //Delete SpaceMouse driver
159        if(mouse)
160        {
161                mouse->shutdown();
162                delete mouse;
163        }
164#endif
165}
166
167bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
168{
169        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
170        if( model.valid() )
171        {
172        rootNode->addChild( model.get() );
173                return true;
174        }
175        else
176        {
177        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
178        return false;
179    }   
180
181        return false;
182}
183
184void visual_core::addManipulators()
185{
186        // set up the camera manipulators.
187    {
188        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
189
190        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
191        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
192        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
193                nt = new osgGA::NodeTrackerManipulator();
194                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
195               
196#ifdef USE_SPACENAVIGATOR
197                // SpaceNavigator manipulator
198                mouse = new SpaceMouse();
199                mouse->initialize();
200                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
201                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
202                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
203                mouseTrackerManip->setAutoComputeHomePosition( true );
204                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
205                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
206#endif
207
208                // objectMounted Manipulator for Camera control by Nodes
209                objectMountedCameraManip = new objectMountedManipulator();
210                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
211
212                // Animation path manipulator
213        std::string pathfile;
214        char keyForAnimationPath = '8';
215        while (arguments.read("-p",pathfile))
216        {
217            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
218            if (apm || !apm->valid()) 
219            {
220                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
221                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
222                keyswitchManipulator->selectMatrixManipulator(num);
223                ++keyForAnimationPath;
224            }
225        }
226
227        viewer->setCameraManipulator( keyswitchManipulator.get() );
228    }
229
230    // add the state manipulator
231    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
232   
233    // add the thread model handler
234    viewer->addEventHandler(new osgViewer::ThreadingHandler);
235
236    // add the window size toggle handler
237    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
238       
239    // add the stats handler
240    viewer->addEventHandler(new osgViewer::StatsHandler);
241
242    // add the help handler
243    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
244
245    // add the record camera path handler
246    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
247
248    // add the LOD Scale handler
249    viewer->addEventHandler(new osgViewer::LODScaleHandler);
250
251    // add the screen capture handler
252    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
253}
254
255
256bool visual_core::checkCommandlineArgumentsForFinalErrors()
257{
258        // Setup Application Usage
259        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
260        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
261    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
262        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
263
264    // if user request help write it out to cout.
265    if (arguments.read("-h") || arguments.read("--help"))
266    {
267        arguments.getApplicationUsage()->write(std::cout);
268                //cause the viewer to exit and shut down clean.
269        viewer->setDone(true);
270    }
271
272    // report any errors if they have occurred when parsing the program arguments.
273    if (arguments.errors())
274    {
275        arguments.writeErrorMessages(std::cout);
276                //cause the viewer to exit and shut down clean.
277        viewer->setDone(true);
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 occurred when parsing the program arguments.
284    if (arguments.errors())
285    {
286        arguments.writeErrorMessages(std::cout);
287        return false;
288    }
289        return true;
290}
291
292void visual_core::setupScenery()
293{
294        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
295        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
296        ///* using a huge cylinder to test position & orientation */
297        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
298        //testObj->addUpdater( new object_updater(testObj) );
299
300        osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "cessna" );
301        //testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
302        testObj2->setNewPosition( osg::DegreesToRadians(50.8123), osg::DegreesToRadians(8.94088), 600 );
303        testObj2->loadGeometry( "../models/cessna.osg" );
304        testObj2->addUpdater( new object_updater(testObj2) );
305
306        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );
307        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
308        testObj3->loadGeometry( "../models/saenger1.flt" );
309        testObj3->addUpdater( new object_updater(testObj3) );
310       
311
312        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );
313        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
314        testObj4->loadGeometry( "../models/saenger2.flt" );
315        testObj4->addUpdater( new object_updater(testObj4) );
316        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
317
318        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );
319        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
320        testObj5->loadGeometry( "../models/saengerCombine.flt" );
321        //testObj5->setScale( 2 );
322        testObj5->addUpdater( new object_updater(testObj5) );
323
324#ifdef USE_SPACENAVIGATOR
325        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
326        if (objectMountedCameraManip.valid())
327                objectMountedCameraManip->setAttachedObject( testObj4 );
328        if (mouseTrackerManip.valid())
329        {
330                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
331                mouseTrackerManip->setMinimumDistance( 100 );
332        }
333#endif
334
335        osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
336        osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
337        nt->setTrackerMode(trackerMode);
338    nt->setRotationMode(rotationMode);
339        //nt->setAutoComputeHomePosition( true );
340        nt->setMinimumDistance( 100 );
341        nt->setTrackNode(testObj4->getGeometry());
342        //nt->computeHomePosition();
343        nt->setAutoComputeHomePosition( true );
344        nt->setDistance( 250 );
345
346
347        // Load EDDF
348        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
349        //if( !osgDB::fileExists(filename) )
350        //{
351        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
352        //}
353        //// read model
354        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
355        //if (tmpModel.valid())
356        //      rootNode->addChild( tmpModel );
357       
358 
359        visual_draw2D::getInstance()->init( rootNode, viewer );
360        //osg::ref_ptr<visual_hud> hud = new visual_hud();
361        osg::ref_ptr<visual_debug_hud> hud = new visual_debug_hud();
362        hud->init( viewer, rootNode );
363       
364
365        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
366        //test->init( rootNode, viewer );
367
368        //// Creating Testclasses
369        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
370        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
371        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
372        //test->setFrameID( 22 );
373        //test->setName("ugamoep");
374        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
375        //testSlot->setVariableName(std::string("HalloName"));
376        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
377        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
378        //testSlot->setValue( 0.12345 );
379        //test->addExecuter( testEx );
380        //test->addSlot( testSlot );
381
382        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
383
384
385        //// Writing object to stream
386        ////std::ofstream myOstream("test.txt" );
387        //std::stringstream myOstream;
388        //std::string extension = "osgb";
389        //bool compressed = false;
390        //osgDB::ReaderWriter* rw = osgDB::Registry::instance()->getReaderWriterForExtension(extension.c_str());
391        //if ( rw )
392        //{
393        //      osgDB::ReaderWriter::WriteResult wr;
394
395        //      if (extension == "osgb")
396        //      {
397        //              if (compressed)
398        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Compressor=zlib") );
399        //              else
400        //                      wr = rw->writeObject( *test, myOstream );
401        //      }
402
403        //      if (extension == "osgt")
404        //      {
405        //              if (compressed)
406        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Ascii Compressor=zlib") );
407        //              else
408        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("Ascii") );
409        //      }
410
411        //      if (extension == "osgx")
412        //      {
413        //              if (compressed)
414        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("XML Compressor=zlib") );
415        //              else
416        //                      wr = rw->writeObject( *test, myOstream, new osgDB::Options("XML") );
417        //      }
418
419
420        //      if (!wr.success() )     OSG_NOTIFY( osg::WARN ) << "ERROR: Save failed: " << wr.message() << std::endl;
421        //}
422        //else
423        //      OSG_NOTIFY( osg::WARN ) << "error getting readerWriter for osgt" << std::endl;
424
425        //// Size ermitteln.
426        //std::stringbuf *pbuf;
427        //pbuf = myOstream.rdbuf();
428        //OSG_NOTIFY( osg::WARN ) << "PBUF Bytes available: " << pbuf->in_avail() << std::endl;
429        //OSG_NOTIFY( osg::ALWAYS ) << "STRING Bytes available: " << myOstream.str().length() << std::endl;
430        //OSG_NOTIFY( osg::ALWAYS ) << "STRING content: " << myOstream.str() << std::endl;
431
432        ////Reading Stream to node
433        //if ( rw )
434        //{
435        //      osgDB::ReaderWriter::ReadResult rr = rw->readObject( myOstream );
436        //      osg::ref_ptr<osgVisual::dataIO_transportContainer> test2 = dynamic_cast<osgVisual::dataIO_transportContainer*>(rr.takeObject());
437        //      if (test2)
438        //      {
439        //              OSG_NOTIFY( osg::WARN ) << "TEST::FrameID is: " << test->getFrameID() << std::endl;
440        //      }
441        //      else
442        //              OSG_NOTIFY( osg::WARN ) << "Error converting stream to Node" << std::endl;
443        //}
444}
Note: See TracBrowser for help on using the repository browser.