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

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

Introductes VS 2008 Memory Leak Debugging.
Todo: Compile on Linux and compare with Valgrind, VS 2008 seems to be awkward in leak debugging

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