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

Last change on this file since 128 was 128, checked in by Torben Dannhauer, 14 years ago
File size: 17.7 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        // create the windows and run the threads.
85        viewer->realize();
86
87        // setup scenery
88        setupScenery();
89
90        // parse Configuration file
91        parseConfigFile(arguments);
92
93        // All modules are initialized - now check arguments for any unused parameter.
94        checkCommandlineArgumentsForFinalErrors();
95
96        // Run visual main loop
97        mainLoop();
98}
99
100void visual_core::mainLoop()
101{
102        // run main loop
103        while( !viewer->done() )
104    {
105                // next frame please....
106        viewer->advance();
107
108                /*double hat, hot, lat, lon, height;
109                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
110                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
111                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
112       
113                // perform all queued events
114                viewer->eventTraversal();
115
116                // update the scene by traversing it with the the update visitor which will
117        // call all node update callbacks and animations.
118        viewer->updateTraversal();
119               
120        // Render the Frame.
121        viewer->renderingTraversals();
122
123    }   // END WHILE
124}
125
126void visual_core::shutdown()
127{
128        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
129
130        // Shutdown Dbug HUD
131        if(hud.valid())
132                hud->shutdown();
133        // Unset scene data
134        viewer->setSceneData( NULL );
135
136#ifdef USE_SKY_SILVERLINING
137        // Shutdown sky
138        if( sky.valid() )
139                sky->shutdown();
140#endif
141
142#ifdef USE_DISTORTION
143        // Shutdown distortion
144        if( distortion.valid() )
145                distortion->shutdown();
146#endif
147
148        // Shutdown data
149        rootNode = NULL;
150
151        // Shutdown dataIO
152        visual_dataIO::getInstance()->shutdown();
153
154       
155#ifdef USE_SPACENAVIGATOR
156        //Delete SpaceMouse driver
157        if(mouse)
158        {
159                mouse->shutdown();
160                delete mouse;
161        }
162#endif
163
164        // Destroy osgViewer
165        viewer = NULL;
166}
167
168bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
169{
170        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
171        if( model.valid() )
172        {
173        rootNode->addChild( model.get() );
174                return true;
175        }
176        else
177        {
178        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
179        return false;
180    }   
181
182        return false;
183}
184
185void visual_core::addManipulators()
186{
187        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
188    {
189        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
190
191        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
192        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
193        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
194                nt = new osgGA::NodeTrackerManipulator();
195                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
196               
197#ifdef USE_SPACENAVIGATOR
198                // SpaceNavigator manipulator
199                mouse = new SpaceMouse();
200                mouse->initialize();
201                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
202                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
203                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
204                mouseTrackerManip->setAutoComputeHomePosition( true );
205                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
206                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
207#endif
208
209                // objectMounted Manipulator for Camera control by Nodes
210                objectMountedCameraManip = new objectMountedManipulator();
211                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
212
213                // Animation path manipulator
214        std::string pathfile;
215        char keyForAnimationPath = '8';
216        while (arguments.read("-p",pathfile))
217        {
218            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
219            if (apm || !apm->valid()) 
220            {
221                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
222                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
223                keyswitchManipulator->selectMatrixManipulator(num);
224                ++keyForAnimationPath;
225            }
226        }
227
228        viewer->setCameraManipulator( keyswitchManipulator.get() );
229    }   // If not Slave END
230
231    // add the state manipulator
232    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
233   
234    // add the thread model handler
235    viewer->addEventHandler(new osgViewer::ThreadingHandler);
236
237    // add the window size toggle handler
238    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
239       
240    // add the stats handler
241    viewer->addEventHandler(new osgViewer::StatsHandler);
242
243    // add the help handler
244    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
245
246    // add the record camera path handler
247    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
248
249    // add the LOD Scale handler
250    viewer->addEventHandler(new osgViewer::LODScaleHandler);
251
252    // add the screen capture handler
253    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
254}
255
256void visual_core::parseConfigFile(osg::ArgumentParser& arguments_)
257{
258        configFileValid = false;
259
260        std::string filename;
261        if( arguments.read("-c", filename) || arguments.read("--config", filename) )
262        {
263                OSG_ALWAYS << "Using configuration file.." << std::endl;
264                if( osgDB::fileExists(filename) )
265                {
266                        configFileValid = false;
267                        xmlDoc *doc = NULL;
268                        xmlNode *root_element = NULL;
269                       
270                        doc = xmlReadFile(filename.c_str(), NULL, 0);
271                        if (doc == NULL)
272                        {
273                                configFileValid = false;
274                                OSG_ALWAYS << "visual_core::parseConfigFile() - ERROR: could not parse osgVisual config file" << filename  << std::endl;
275                        }
276                        else
277                        {
278                                //  Get the root element node
279                                root_element = xmlDocGetRootElement(doc);
280
281                                // Parse the XML document.
282                                checkXMLNode(root_element);
283
284                                // free the document
285                                xmlFreeDoc(doc);;
286                        }
287                        // Free the global variables that may have been allocated by the parser.
288                        xmlCleanupParser();
289
290                        if(!configFileValid)
291                                OSG_ALWAYS << "visual_core::parseConfigFile() - ERROR: XML file seems not to be a valid osgVisual configuration file!" << std::endl;
292
293                }       // IF configfile exists
294        }       // IF -c END
295}
296
297void visual_core::checkXMLNode(xmlNode * a_node)
298{
299  for (xmlNode *cur_node = a_node; cur_node; cur_node = cur_node->next)
300        {
301                std::string node_name=reinterpret_cast<const char*>(cur_node->name);
302                if(cur_node->type == XML_ELEMENT_NODE && node_name == "osgvisualconfiguration")
303                {
304                        OSG_DEBUG << "XML node osgvisualconfiguration found" << std::endl;
305                        configFileValid = true;
306                        // Iterate to the next nodes to configure modules and scenery.
307                        checkXMLNode(cur_node->children);               
308                }
309
310        if (cur_node->type == XML_ELEMENT_NODE && node_name == "module")
311                {
312                        OSG_DEBUG << "XML node module found" << std::endl;
313
314                        parseModule(cur_node);
315       
316            //OSG_DEBUG << "node type=Element, name:" << cur_node->name << std::endl;
317                        //OSG_DEBUG << "Processing children at " << cur_node->children << std::endl;
318        }       // IF(module) END
319
320                if (cur_node->type == XML_ELEMENT_NODE && node_name == "scenery")
321                {
322                        OSG_DEBUG << "XML node scenery found" << std::endl;
323
324                        parseScenery(cur_node);
325       
326            //OSG_DEBUG << "node type=Element, name:" << cur_node->name << std::endl;
327                        //OSG_DEBUG << "Processing children at " << cur_node->children << std::endl;
328        }       // IF(scenery) END
329    }   // FOR END
330}
331
332void visual_core::parseModule(xmlNode * a_node)
333{
334        OSG_ALWAYS << "parseModule()" << std::endl;
335
336// Extract infos
337        std::string name = "";
338        bool enabled = false;
339
340        xmlAttr  *attr = a_node->properties;
341        while ( attr ) 
342        { 
343                std::string attr_name=reinterpret_cast<const char*>(attr->name);
344                std::string attr_value=reinterpret_cast<const char*>(attr->children->content);
345                if( attr_name == "name" )
346                        name = reinterpret_cast<const char*>(attr->children->content);
347                if( attr_name == "enabled" && attr_value== "yes" )
348                        enabled = true;
349                if( attr_name == "enabled" && attr_value== "no" )
350                        enabled = false;
351
352
353                std::cout << "Attribute name: " << attr->name << " value: " << attr_value << std::endl;
354                attr = attr->next; 
355        } 
356
357
358}
359
360void visual_core::parseScenery(xmlNode * a_node)
361{
362        OSG_ALWAYS << "parseScenery()" << std::endl;
363}
364
365bool visual_core::checkCommandlineArgumentsForFinalErrors()
366{
367        // Setup Application Usage
368        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
369        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
370    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
371        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
372
373    // if user request help write it out to cout.
374    if (arguments.read("-h") || arguments.read("--help"))
375    {
376        arguments.getApplicationUsage()->write(std::cout);
377                //cause the viewer to exit and shut down clean.
378        viewer->setDone(true);
379    }
380
381    // report any errors if they have occurred when parsing the program arguments.
382    if (arguments.errors())
383    {
384        arguments.writeErrorMessages(std::cout);
385                //cause the viewer to exit and shut down clean.
386        viewer->setDone(true);
387    }
388
389         // any option left unread are converted into errors to write out later.
390    arguments.reportRemainingOptionsAsUnrecognized();
391
392    // report any errors if they have occurred when parsing the program arguments.
393    if (arguments.errors())
394    {
395        arguments.writeErrorMessages(std::cout);
396        return false;
397    }
398        return true;
399}
400
401void visual_core::setupScenery()
402{
403        // iterate manually through one frame to allow some modules like Sky_Silverlining to initialize properly befor we configure it according to the scenery data.
404        viewer->advance();
405        viewer->eventTraversal();
406        viewer->updateTraversal();
407        viewer->renderingTraversals();
408
409        // Sky settings:       
410        sky->setTime(12,00,23);
411        sky->setVisibility(50000);
412        //addWindVolume( 0.0, 15000.0, 300.0, 90.0 );
413       
414        sky->addCloudLayer( 0, 300000, 300000, 600.0, 2351.0, 0.5, STRATUS );
415        //sky->addCloudLayer( 0, 5000000, 5000000, 600.0, 7351.0, 0.2, CIRRUS_FIBRATUS );
416        //sky->addCloudLayer( 0, 50000, 50000, 600.0, 7351.0, 0.2, CIRROCUMULUS );
417        ///sky->addCloudLayer( 1, 200000, 200000, 3000, 2000.0, 0.05, CUMULUS_CONGESTUS );
418        //cloudLayerSlots[1].cloudLayerPointer->SetPrecipitation(SilverLining::CloudLayer::SLEET, 25.0 );
419
420        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
421        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
422        ///* using a huge cylinder to test position & orientation */
423        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
424        //testObj->addUpdater( new object_updater(testObj) );
425
426        //osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "neuschwanstein" );       // todo memleak
427        ////testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
428        //testObj2->setNewPosition( osg::DegreesToRadians(47.557523564234), osg::DegreesToRadians(10.749646398595), 950 );
429        //testObj2->loadGeometry( "../models/neuschwanstein.osgb" );
430        ////testObj2->addUpdater( new object_updater(testObj2) );       // todo memleak
431
432        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );       // todo memleak
433        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
434        testObj3->loadGeometry( "../models/saenger1.flt" );
435        testObj3->addUpdater( new object_updater(testObj3) );   // todo memleak
436       
437
438        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );       // todo memleak
439        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
440        testObj4->loadGeometry( "../models/saenger2.flt" );
441        testObj4->addUpdater( new object_updater(testObj4) );   // todo memleak
442        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
443
444        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );        // todo memleak
445        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
446        testObj5->loadGeometry( "../models/saengerCombine.flt" );
447        //testObj5->setScale( 2 );
448        testObj5->addUpdater( new object_updater(testObj5) );   // todo memleak
449
450#ifdef USE_SPACENAVIGATOR
451        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
452        if (objectMountedCameraManip.valid())
453                objectMountedCameraManip->setAttachedObject( testObj4 );
454        if (mouseTrackerManip.valid())
455        {
456                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
457                mouseTrackerManip->setMinimumDistance( 100 );
458        }
459#endif
460
461        if(nt.valid())
462        {
463                osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
464                osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
465                nt->setTrackerMode(trackerMode);
466                nt->setRotationMode(rotationMode);
467                //nt->setAutoComputeHomePosition( true );
468                nt->setMinimumDistance( 100 );
469                nt->setTrackNode(testObj4->getGeometry());
470                //nt->computeHomePosition();
471                nt->setAutoComputeHomePosition( true );
472                nt->setDistance( 250 );
473        }
474
475
476        // Load EDDF
477        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
478        //if( !osgDB::fileExists(filename) )
479        //{
480        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
481        //}
482        //// read model
483        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
484        //if (tmpModel.valid())
485        //      rootNode->addChild( tmpModel );
486       
487 
488        visual_draw2D::getInstance()->init( rootNode, viewer );
489        //osg::ref_ptr<visual_hud> hud = new visual_hud();
490        hud = new visual_debug_hud();
491        hud->init( viewer, rootNode );
492       
493       
494
495        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
496        //test->init( rootNode, viewer );
497
498        //// Creating Testclasses
499        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
500        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
501        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
502        //test->setFrameID( 22 );
503        //test->setName("ugamoep");
504        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
505        //testSlot->setVariableName(std::string("HalloName"));
506        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
507        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
508        //testSlot->setValue( 0.12345 );
509        //test->addExecuter( testEx );
510        //test->addSlot( testSlot );
511
512        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
513}
Note: See TracBrowser for help on using the repository browser.