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

Last change on this file since 122 was 122, checked in by Torben Dannhauer, 14 years ago
File size: 14.5 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
18#include <visual_core.h>
19
20using namespace osgVisual;
21
22visual_core::visual_core(osg::ArgumentParser& arguments_) : arguments(arguments_)
23{
24        OSG_NOTIFY( osg::ALWAYS ) << "visual_core instantiated." << std::endl;
25}
26
27visual_core::~visual_core(void)
28{
29        OSG_NOTIFY( osg::ALWAYS ) << "visual_core destroyed." << std::endl;
30}
31
32void visual_core::initialize()
33{
34        OSG_NOTIFY( osg::ALWAYS ) << "Initialize visual_core..." << std::endl;
35
36        // Configure osg to use KdTrees
37        osgDB::Registry::instance()->setBuildKdTreesHint(osgDB::ReaderWriter::Options::BUILD_KDTREES);
38
39        // Setup pathes
40        osgDB::Registry::instance()->getDataFilePathList().push_back( "D:\\DA\\osgVisual\\models" );
41       
42        // Setup viewer
43        viewer = new osgViewer::Viewer(arguments);
44
45        // Setup coordinate system node
46        rootNode = new osg::CoordinateSystemNode;       // todo memleakf
47        rootNode->setEllipsoidModel(new osg::EllipsoidModel());
48
49        // Test memory leak (todo)
50        double* test = new double[1000];
51
52        #ifdef USE_SPACENAVIGATOR
53                mouse = NULL;
54        #endif
55
56        //osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( 8 );
57
58        // Show model
59        viewer->setSceneData( rootNode );
60
61        osg::Group* distortedSceneGraph = NULL;
62#ifdef USE_DISTORTION
63        // Initialize distortion
64        OSG_NOTIFY( osg::ALWAYS ) << "Using distortion." << std::endl;
65        distortion = new visual_distortion( viewer, arguments );
66        distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
67        distortedSceneGraph = distortion->getDistortedSceneGraph();
68#endif
69
70#ifdef USE_SKY_SILVERLINING
71        // Initialize sky
72        sky = new visual_skySilverLining( viewer );
73        sky->init(distortedSceneGraph, rootNode);       // Without distortedSceneGraph=NULL
74#endif
75
76        // Initialize DataIO interface
77        visual_dataIO::getInstance()->init(viewer, arguments);
78
79        // Add manipulators for user interaction - after dataIO to be able to skip it in slaves.
80        addManipulators();
81
82        loadTerrain(arguments);
83
84        // All modules are initialized - now check arguments for any unused parameter.
85        checkCommandlineArgumentsForFinalErrors();
86
87        // create the windows and run the threads.
88        viewer->realize();
89
90        // setup scenery
91        setupScenery();
92
93        // Run visual main loop
94        mainLoop();
95}
96
97void visual_core::mainLoop()
98{
99        // run main loop
100        while( !viewer->done() )
101    {
102                // next frame please....
103        viewer->advance();
104
105                /*double hat, hot, lat, lon, height;
106                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
107                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
108                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
109       
110                // perform all queued events
111                viewer->eventTraversal();
112
113                // update the scene by traversing it with the the update visitor which will
114        // call all node update callbacks and animations.
115        viewer->updateTraversal();
116               
117        // Render the Frame.
118        viewer->renderingTraversals();
119
120    }   // END WHILE
121}
122
123void visual_core::shutdown()
124{
125        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
126
127        // Shutdown Dbug HUD
128        if(hud.valid())
129                hud->shutdown();
130        // Unset scene data
131        viewer->setSceneData( NULL );
132
133#ifdef USE_SKY_SILVERLINING
134        // Shutdown sky
135        if( sky.valid() )
136                sky->shutdown();
137#endif
138
139#ifdef USE_DISTORTION
140        // Shutdown distortion
141        if( distortion.valid() )
142                distortion->shutdown();
143#endif
144
145        // Shutdown data
146        rootNode = NULL;
147
148        // Shutdown dataIO
149        visual_dataIO::getInstance()->shutdown();
150
151       
152#ifdef USE_SPACENAVIGATOR
153        //Delete SpaceMouse driver
154        if(mouse)
155        {
156                mouse->shutdown();
157                delete mouse;
158        }
159#endif
160
161        // Destroy osgViewer
162        viewer = NULL;
163}
164
165bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
166{
167        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
168        if( model.valid() )
169        {
170        rootNode->addChild( model.get() );
171                return true;
172        }
173        else
174        {
175        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
176        return false;
177    }   
178
179        return false;
180}
181
182void visual_core::addManipulators()
183{
184        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
185    {
186        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
187
188        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
189        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
190        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
191                nt = new osgGA::NodeTrackerManipulator();
192                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
193               
194#ifdef USE_SPACENAVIGATOR
195                // SpaceNavigator manipulator
196                mouse = new SpaceMouse();
197                mouse->initialize();
198                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
199                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
200                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
201                mouseTrackerManip->setAutoComputeHomePosition( true );
202                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
203                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
204#endif
205
206                // objectMounted Manipulator for Camera control by Nodes
207                objectMountedCameraManip = new objectMountedManipulator();
208                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
209
210                // Animation path manipulator
211        std::string pathfile;
212        char keyForAnimationPath = '8';
213        while (arguments.read("-p",pathfile))
214        {
215            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
216            if (apm || !apm->valid()) 
217            {
218                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
219                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
220                keyswitchManipulator->selectMatrixManipulator(num);
221                ++keyForAnimationPath;
222            }
223        }
224
225        viewer->setCameraManipulator( keyswitchManipulator.get() );
226    }   // If not Slave END
227
228    // add the state manipulator
229    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
230   
231    // add the thread model handler
232    viewer->addEventHandler(new osgViewer::ThreadingHandler);
233
234    // add the window size toggle handler
235    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
236       
237    // add the stats handler
238    viewer->addEventHandler(new osgViewer::StatsHandler);
239
240    // add the help handler
241    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
242
243    // add the record camera path handler
244    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
245
246    // add the LOD Scale handler
247    viewer->addEventHandler(new osgViewer::LODScaleHandler);
248
249    // add the screen capture handler
250    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
251}
252
253
254bool visual_core::checkCommandlineArgumentsForFinalErrors()
255{
256        // Setup Application Usage
257        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
258        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
259    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
260        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
261
262    // if user request help write it out to cout.
263    if (arguments.read("-h") || arguments.read("--help"))
264    {
265        arguments.getApplicationUsage()->write(std::cout);
266                //cause the viewer to exit and shut down clean.
267        viewer->setDone(true);
268    }
269
270    // report any errors if they have occurred when parsing the program arguments.
271    if (arguments.errors())
272    {
273        arguments.writeErrorMessages(std::cout);
274                //cause the viewer to exit and shut down clean.
275        viewer->setDone(true);
276    }
277
278         // any option left unread are converted into errors to write out later.
279    arguments.reportRemainingOptionsAsUnrecognized();
280
281    // report any errors if they have occurred when parsing the program arguments.
282    if (arguments.errors())
283    {
284        arguments.writeErrorMessages(std::cout);
285        return false;
286    }
287        return true;
288}
289
290void visual_core::setupScenery()
291{
292        // iterate manually through one frame to allow some modules like Sky_Silverlining to initialize properly befor we configure it according to the scenery data.
293        viewer->advance();
294        viewer->eventTraversal();
295        viewer->updateTraversal();
296        viewer->renderingTraversals();
297
298        // Sky settings:       
299        sky->setTime(12,00,23);
300        sky->setVisibility(50000);
301        //addWindVolume( 0.0, 15000.0, 300.0, 90.0 );
302       
303        //sky->addCloudLayer( 0, 300000, 300000, 600.0, 2351.0, 0.5, STRATUS );
304        //sky->addCloudLayer( 0, 5000000, 5000000, 600.0, 7351.0, 0.2, CIRRUS_FIBRATUS );
305        //sky->addCloudLayer( 0, 50000, 50000, 600.0, 7351.0, 0.2, CIRROCUMULUS );
306        ///sky->addCloudLayer( 1, 200000, 200000, 3000, 2000.0, 0.05, CUMULUS_CONGESTUS );
307        //cloudLayerSlots[1].cloudLayerPointer->SetPrecipitation(SilverLining::CloudLayer::SLEET, 25.0 );
308
309        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
310        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
311        ///* using a huge cylinder to test position & orientation */
312        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
313        //testObj->addUpdater( new object_updater(testObj) );
314
315        //osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "neuschwanstein" );       // todo memleak
316        ////testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
317        //testObj2->setNewPosition( osg::DegreesToRadians(47.557523564234), osg::DegreesToRadians(10.749646398595), 950 );
318        //testObj2->loadGeometry( "../models/neuschwanstein.osgb" );
319        ////testObj2->addUpdater( new object_updater(testObj2) );       // todo memleak
320
321        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );       // todo memleak
322        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
323        testObj3->loadGeometry( "../models/saenger1.flt" );
324        testObj3->addUpdater( new object_updater(testObj3) );   // todo memleak
325       
326
327        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );       // todo memleak
328        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
329        testObj4->loadGeometry( "../models/saenger2.flt" );
330        testObj4->addUpdater( new object_updater(testObj4) );   // todo memleak
331        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
332
333        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );        // todo memleak
334        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
335        testObj5->loadGeometry( "../models/saengerCombine.flt" );
336        //testObj5->setScale( 2 );
337        testObj5->addUpdater( new object_updater(testObj5) );   // todo memleak
338
339#ifdef USE_SPACENAVIGATOR
340        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
341        if (objectMountedCameraManip.valid())
342                objectMountedCameraManip->setAttachedObject( testObj4 );
343        if (mouseTrackerManip.valid())
344        {
345                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
346                mouseTrackerManip->setMinimumDistance( 100 );
347        }
348#endif
349
350        if(nt.valid())
351        {
352                osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
353                osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
354                nt->setTrackerMode(trackerMode);
355                nt->setRotationMode(rotationMode);
356                //nt->setAutoComputeHomePosition( true );
357                nt->setMinimumDistance( 100 );
358                nt->setTrackNode(testObj4->getGeometry());
359                //nt->computeHomePosition();
360                nt->setAutoComputeHomePosition( true );
361                nt->setDistance( 250 );
362        }
363
364
365        // Load EDDF
366        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
367        //if( !osgDB::fileExists(filename) )
368        //{
369        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
370        //}
371        //// read model
372        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
373        //if (tmpModel.valid())
374        //      rootNode->addChild( tmpModel );
375       
376 
377        visual_draw2D::getInstance()->init( rootNode, viewer );
378        //osg::ref_ptr<visual_hud> hud = new visual_hud();
379        hud = new visual_debug_hud();
380        hud->init( viewer, rootNode );
381       
382       
383
384        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
385        //test->init( rootNode, viewer );
386
387        //// Creating Testclasses
388        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
389        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
390        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
391        //test->setFrameID( 22 );
392        //test->setName("ugamoep");
393        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
394        //testSlot->setVariableName(std::string("HalloName"));
395        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
396        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
397        //testSlot->setValue( 0.12345 );
398        //test->addExecuter( testEx );
399        //test->addSlot( testSlot );
400
401        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
402}
Note: See TracBrowser for help on using the repository browser.