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

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

implemented technique to debug memory leaks

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