source: osgVisual/trunk/src/core/visual_core.cpp @ 188

Last change on this file since 188 was 188, checked in by Torben Dannhauer, 13 years ago

working on scenery configuration via XML: prototype status... :)

File size: 17.1 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        // Check for config file to provide it to all modules during initialization.
37        if( arguments.read("-c", configFilename) || arguments.read("--config", configFilename) )
38        {
39                if( !osgDB::fileExists(configFilename) )
40                        configFilename = "";
41                else
42                        OSG_ALWAYS << "Using configuration file: " << configFilename << std::endl;
43        }
44
45        // Configure osg to use KdTrees
46        osgDB::Registry::instance()->setBuildKdTreesHint(osgDB::ReaderWriter::Options::BUILD_KDTREES);
47
48        // Setup pathes
49        osgDB::Registry::instance()->getDataFilePathList().push_back( "D:\\DA\\osgVisual\\models" );
50       
51        // Setup viewer
52        viewer = new osgViewer::Viewer(arguments);
53
54        // Setup coordinate system node
55        rootNode = new osg::CoordinateSystemNode;       // todo memleakf
56        rootNode->setEllipsoidModel(new osg::EllipsoidModel());
57
58        // Test memory leak (todo)
59        double* test = new double[1000];
60
61        #ifdef USE_SPACENAVIGATOR
62                mouse = NULL;
63        #endif
64
65        //osg::DisplaySettings::instance()->setNumOfDatabaseThreadsHint( 8 );
66
67        // Show model
68        viewer->setSceneData( rootNode );
69
70        osg::Group* distortedSceneGraph = NULL;
71#ifdef USE_DISTORTION
72        // Initialize distortion
73        distortion = new visual_distortion( viewer, arguments, configFilename );
74        distortedSceneGraph = distortion->initialize( rootNode, viewer->getCamera()->getClearColor() );
75#endif
76
77#ifdef USE_SKY_SILVERLINING
78        // Initialize sky
79        bool disabled = false;  // to ask if the skyp is disabled or enabled
80        sky = new visual_skySilverLining( viewer, configFilename, disabled );
81        if(disabled)
82                sky = NULL;
83        if(sky.valid())
84                sky->init(distortedSceneGraph, rootNode);       // Without distortion: distortedSceneGraph=NULL
85#endif
86
87        // Initialize DataIO interface
88        visual_dataIO::getInstance()->init(viewer, configFilename);
89
90        // Add manipulators for user interaction - after dataIO to be able to skip it in slaves rendering machines.
91        addManipulators();
92
93        loadTerrain(arguments);
94
95        // create the windows and run the threads.
96        viewer->realize();
97
98        // parse Configuration file
99        xmlDoc* tmpDoc;
100        xmlNode* sceneryNode = util::getSceneryXMLConfig( "osgVisualConfig.xml", tmpDoc);
101        parseScenery(sceneryNode);
102        if(sceneryNode)
103        {
104                xmlFreeDoc(tmpDoc); xmlCleanupParser();
105        }
106
107        // All modules are initialized - now check arguments for any unused parameter.
108        checkCommandlineArgumentsForFinalErrors();
109
110        // Run visual main loop
111        mainLoop();
112}
113
114void visual_core::mainLoop()
115{
116        int framestoScenerySetup = 5;
117        // run main loop
118        while( !viewer->done() )
119    {
120                // setup scenery
121                if(framestoScenerySetup-- == 0)
122                        setupScenery();
123
124                // next frame please....
125        viewer->advance();
126
127                /*double hat, hot, lat, lon, height;
128                util::getWGS84ofCamera( viewer->getCamera(), rootNode, lat, lon, height);
129                if (util::queryHeightOfTerrain( hot, rootNode, lat, lon) && util::queryHeightAboveTerrainInWGS84( hat, rootNode, lat, lon, height ) )
130                        OSG_NOTIFY( osg::ALWAYS ) << "HOT is: " << hot << ", HAT is: " << hat << std::endl;*/
131       
132                // perform all queued events
133                viewer->eventTraversal();
134
135                // update the scene by traversing it with the the update visitor which will
136        // call all node update callbacks and animations.
137        viewer->updateTraversal();
138               
139        // Render the Frame.
140        viewer->renderingTraversals();
141
142    }   // END WHILE
143}
144
145void visual_core::shutdown()
146{
147        OSG_NOTIFY( osg::ALWAYS ) << "Shutdown visual_core..." << std::endl;
148
149        // Shutdown Dbug HUD
150        if(hud.valid())
151                hud->shutdown();
152        // Unset scene data
153        viewer->setSceneData( NULL );
154
155#ifdef USE_SKY_SILVERLINING
156        // Shutdown sky
157        if( sky.valid() )
158                sky->shutdown();
159#endif
160
161#ifdef USE_DISTORTION
162        // Shutdown distortion
163        if( distortion.valid() )
164                distortion->shutdown();
165#endif
166
167        // Shutdown data
168        rootNode = NULL;
169
170        // Shutdown dataIO
171        visual_dataIO::getInstance()->shutdown();
172
173       
174#ifdef USE_SPACENAVIGATOR
175        //Delete SpaceMouse driver
176        if(mouse)
177        {
178                mouse->shutdown();
179                delete mouse;
180        }
181#endif
182
183        // Destroy osgViewer
184        viewer = NULL;
185}
186
187bool visual_core::loadTerrain(osg::ArgumentParser& arguments_)
188{
189        osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments_);
190        if( model.valid() )
191        {
192        rootNode->addChild( model.get() );
193                return true;
194        }
195        else
196        {
197        OSG_NOTIFY( osg::FATAL ) << "Load terrain: No data loaded" << std::endl;
198        return false;
199    }   
200
201        return false;
202}
203
204void visual_core::addManipulators()
205{
206        if(!visual_dataIO::getInstance()->isSlave()) // set up the camera manipulators if not slave.
207    {
208        osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;
209
210        keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
211        keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
212        keyswitchManipulator->addMatrixManipulator( '3', "Terrain", new osgGA::TerrainManipulator() );
213                nt = new osgGA::NodeTrackerManipulator();
214                keyswitchManipulator->addMatrixManipulator( '4', "NodeTrackerManipulator", nt );
215               
216#ifdef USE_SPACENAVIGATOR
217                // SpaceNavigator manipulator
218                mouse = new SpaceMouse();
219                mouse->initialize();
220                mouseTrackerManip = new NodeTrackerSpaceMouse(mouse);
221                mouseTrackerManip->setTrackerMode(NodeTrackerSpaceMouse::NODE_CENTER);
222                mouseTrackerManip->setRotationMode(NodeTrackerSpaceMouse::ELEVATION_AZIM);
223                mouseTrackerManip->setAutoComputeHomePosition( true );
224                keyswitchManipulator->addMatrixManipulator( '5', "Spacemouse Node Tracker", mouseTrackerManip );
225                keyswitchManipulator->addMatrixManipulator( '6', "Spacemouse Free (Airplane)", new FreeManipulator(mouse) );
226#endif
227
228                // objectMounted Manipulator for Camera control by Nodes
229                objectMountedCameraManip = new objectMountedManipulator();
230                keyswitchManipulator->addMatrixManipulator( '7', "Object mounted Camera", objectMountedCameraManip );
231
232                // Animation path manipulator
233        std::string pathfile;
234        char keyForAnimationPath = '8';
235        while (arguments.read("-p",pathfile))
236        {
237            osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
238            if (apm || !apm->valid()) 
239            {
240                unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
241                keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
242                keyswitchManipulator->selectMatrixManipulator(num);
243                ++keyForAnimationPath;
244            }
245        }
246
247        viewer->setCameraManipulator( keyswitchManipulator.get() );
248    }   // If not Slave END
249
250    // add the state manipulator
251    viewer->addEventHandler( new osgGA::StateSetManipulator(rootNode->getOrCreateStateSet()) );
252   
253    // add the thread model handler
254    viewer->addEventHandler(new osgViewer::ThreadingHandler);
255
256    // add the window size toggle handler
257    viewer->addEventHandler(new osgViewer::WindowSizeHandler);
258       
259    // add the stats handler
260    viewer->addEventHandler(new osgViewer::StatsHandler);
261
262    // add the help handler
263    viewer->addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage()));
264
265    // add the record camera path handler
266    viewer->addEventHandler(new osgViewer::RecordCameraPathHandler);
267
268    // add the LOD Scale handler
269    viewer->addEventHandler(new osgViewer::LODScaleHandler);
270
271    // add the screen capture handler
272    viewer->addEventHandler(new osgViewer::ScreenCaptureHandler);
273}
274
275void visual_core::parseScenery(xmlNode* a_node)
276{
277        OSG_ALWAYS << "parseScenery()" << std::endl;
278
279        a_node = a_node->children;
280
281        for (xmlNode *cur_node = a_node; cur_node; cur_node = cur_node->next)
282        {
283                std::string node_name=reinterpret_cast<const char*>(cur_node->name);
284
285                if(cur_node->type == XML_ELEMENT_NODE && node_name == "terrain")
286                {
287                        //<terrain filename="d:\my\path\database.ive"></terrain>
288                }
289
290                if(cur_node->type == XML_ELEMENT_NODE && node_name == "animationpath")
291                {
292                        //<animationpath filename="salzburgerEcke.path"></animationpath>
293                }
294
295                if(cur_node->type == XML_ELEMENT_NODE && node_name == "models")
296                {
297                        /*
298                        <models>
299                          <model filename="cessna" type="plain" label="TestText!" dynamic="yes">
300                                <position lat="47.12345" lon="11.234567" alt="1500.0"></position>
301                                <attitude rot_x="0.0" rot_y="0.0" rot_z="0.0"></attitude>
302                                <cameraoffset>
303                                  <translation trans_x="0.0" trans_y="0.0" trans_z="0.0"></translation>
304                                  <rotation rot_x="0.0" rot_y="0.0" rot_z="0.0"></rotation>
305                                </cameraoffset>
306                          </model>
307                        </models>
308                        */
309                }
310
311                if(cur_node->type == XML_ELEMENT_NODE && node_name == "datetime")
312                {
313                        //<datetime day="01" month="02" year="2010" hour="23" minute="45"></datetime>
314                }
315
316                if(cur_node->type == XML_ELEMENT_NODE && node_name == "visibility")
317                {
318                        //<visibility range="50000" turbidity="2.2" ></visibility>
319                }
320
321                if(cur_node->type == XML_ELEMENT_NODE && node_name == "cloudlayer")
322                {
323                        /*
324                        <cloudlayer slot="1" type="cumulusCongestus" enabled="true" fadetime="15">
325                          <geometry baselength="50000" basewidth="50000" thickness="500" baseHeight="1700" density="0.3"></geometry>
326                          <precipitation rate_mmPerHour_rain="5.0" rate_mmPerHour_drySnow="7.0" rate_mmPerHour_wetSnow="10.0" rate_mmPerHour_sleet="0.0"></precipitation>
327                        </cloudlayer>
328                        */
329                }
330
331                if(cur_node->type == XML_ELEMENT_NODE && node_name == "windlayer")
332                {
333                        //<windlayer bottom="500.0" top="700." speed="25.0" direction="90.0"></windlayer>
334                }
335        }// FOR all nodes END
336
337}
338
339bool visual_core::checkCommandlineArgumentsForFinalErrors()
340{
341        // Setup Application Usage
342        arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
343        arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the new FSD visualization tool, written by Torben Dannhauer");
344    arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] Terrain_filename");
345        arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
346
347    // if user request help write it out to cout.
348    if (arguments.read("-h") || arguments.read("--help"))
349    {
350        arguments.getApplicationUsage()->write(std::cout);
351                //cause the viewer to exit and shut down clean.
352        viewer->setDone(true);
353    }
354
355    // report any errors if they have occurred when parsing the program arguments.
356    if (arguments.errors())
357    {
358        arguments.writeErrorMessages(std::cout);
359                //cause the viewer to exit and shut down clean.
360        viewer->setDone(true);
361    }
362
363         // any option left unread are converted into errors to write out later.
364    arguments.reportRemainingOptionsAsUnrecognized();
365
366    // report any errors if they have occurred when parsing the program arguments.
367    if (arguments.errors())
368    {
369        arguments.writeErrorMessages(std::cout);
370        return false;
371    }
372        return true;
373}
374
375void visual_core::setupScenery()
376{
377
378        // Sky settings:
379        if(sky.valid())
380        {
381                sky->setTime(15,30,00);
382                sky->setVisibility(50000);
383                sky->addWindVolume( 0.0, 15000.0, 25.0, 90.0 );
384               
385                //sky->addCloudLayer( 0, 20000, 20000, 600.0, 1000.0, 0.5, CUMULONIMBUS_CAPPILATUS );
386                //sky->addCloudLayer( 1, 5000000, 5000000, 600.0, 7351.0, 0.2, CIRRUS_FIBRATUS );
387                //sky->addCloudLayer( 2, 50000, 50000, 600.0, 7351.0, 0.2, CIRROCUMULUS );
388                ///sky->addCloudLayer( 2, 100000, 100000, 600.0, 2351.0, 0.75, STRATUS );
389                sky->addCloudLayer( 3, 50000, 50000, 1300.0, 700.0, 0.07, CUMULUS_CONGESTUS );
390                //sky->addCloudLayer( 1, 100000, 100000, 3500.0, 2000.0, 0.30, STRATOCUMULUS );
391
392                //sky->setSlotPrecipitation( 1, 0.0, 0.0, 0.0, 25.0 );
393        }
394
395
396        //testObj = new visual_object( rootNode, "testStab", objectMountedCameraManip );
397        //testObj->setNewPosition( osg::DegreesToRadians(47.7123), osg::DegreesToRadians(12.84088), 600 );
398        ///* using a huge cylinder to test position & orientation */
399        //testObj->setGeometry( util::getDemoCylinder(5000.0, 20.0 ) );
400        //testObj->addUpdater( new object_updater(testObj) );
401
402        //osg::ref_ptr<visual_object> testObj2 = new visual_object( rootNode, "neuschwanstein" );       // todo memleak
403        ////testObj2->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
404        //testObj2->setNewPosition( osg::DegreesToRadians(47.557523564234), osg::DegreesToRadians(10.749646398595), 950 );
405        //testObj2->loadGeometry( "../models/neuschwanstein.osgb" );
406        ////testObj2->addUpdater( new object_updater(testObj2) );       // todo memleak
407
408        osg::ref_ptr<visual_object> testObj3 = new visual_object( rootNode, "SAENGER1" );       // todo memleak
409        testObj3->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 600 );
410        testObj3->loadGeometry( "../models/saenger1.flt" );
411        testObj3->addUpdater( new object_updater(testObj3) );   // todo memleak
412       
413
414        osg::ref_ptr<visual_object> testObj4 = new visual_object( rootNode, "SAENGER2" );       // todo memleak
415        testObj4->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 650 );
416        testObj4->loadGeometry( "../models/saenger2.flt" );
417        testObj4->addUpdater( new object_updater(testObj4) );   // todo memleak
418        testObj4->addLabel("testLabel", "LabelTest!!\nnächste Zeile :)",osg::Vec4(1.0f,0.25f,1.0f,1.0f));
419
420        osg::ref_ptr<visual_object> testObj5 = new visual_object( rootNode, "SAENGER" );        // todo memleak
421        testObj5->setNewPosition( osg::DegreesToRadians(47.8123), osg::DegreesToRadians(12.94088), 550 );
422        testObj5->loadGeometry( "../models/saengerCombine.flt" );
423        //testObj5->setScale( 2 );
424        testObj5->addUpdater( new object_updater(testObj5) );   // todo memleak
425
426#ifdef USE_SPACENAVIGATOR
427        // Manipulatoren auf dieses Objekt binden (Primärobjekt)
428        if (objectMountedCameraManip.valid())
429                objectMountedCameraManip->setAttachedObject( testObj4 );
430        if (mouseTrackerManip.valid())
431        {
432                mouseTrackerManip->setTrackNode( testObj4->getGeometry() );
433                mouseTrackerManip->setMinimumDistance( 100 );
434        }
435#endif
436
437        if(nt.valid())
438        {
439                osgGA::NodeTrackerManipulator::TrackerMode trackerMode = osgGA::NodeTrackerManipulator::NODE_CENTER;
440                osgGA::NodeTrackerManipulator::RotationMode rotationMode = osgGA::NodeTrackerManipulator::ELEVATION_AZIM;
441                nt->setTrackerMode(trackerMode);
442                nt->setRotationMode(rotationMode);
443                //nt->setAutoComputeHomePosition( true );
444                nt->setMinimumDistance( 100 );
445                nt->setTrackNode(testObj4->getGeometry());
446                //nt->computeHomePosition();
447                nt->setAutoComputeHomePosition( true );
448                nt->setDistance( 250 );
449        }
450
451
452        // Load EDDF
453        //std::string filename = "D:\\DA\\EDDF_test\\eddf.ive";
454        //if( !osgDB::fileExists(filename) )
455        //{
456        //      OSG_NOTIFY(osg::ALWAYS) << "Warning: EDDF Model not loaded. File '" << filename << "' does not exist. Skipping.";
457        //}
458        //// read model
459        //osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename );
460        //if (tmpModel.valid())
461        //      rootNode->addChild( tmpModel );
462       
463 
464        visual_draw2D::getInstance()->init( rootNode, viewer );
465        //osg::ref_ptr<visual_hud> hud = new visual_hud();
466        hud = new visual_debug_hud();
467        hud->init( viewer, rootNode );
468       
469       
470
471        //osg::ref_ptr<visual_draw3D> test = new visual_draw3D();
472        //test->init( rootNode, viewer );
473
474        //// Creating Testclasses
475        //osg::ref_ptr<osgVisual::dataIO_transportContainer> test = new osgVisual::dataIO_transportContainer();
476        //osg::ref_ptr<osgVisual::dataIO_executer> testEx = new osgVisual::dataIO_executer();
477        //osg::ref_ptr<osgVisual::dataIO_slot> testSlot = new osgVisual::dataIO_slot();
478        //test->setFrameID( 22 );
479        //test->setName("ugamoep");
480        //testEx->setexecuterID( osgVisual::dataIO_executer::IS_COLLISION );
481        //testSlot->setVariableName(std::string("HalloName"));
482        //testSlot->setdataDirection( osgVisual::dataIO_slot::TO_OBJ );
483        //testSlot->setvarType( osgVisual::dataIO_slot::DOUBLE );
484        //testSlot->setValue( 0.12345 );
485        //test->addExecuter( testEx );
486        //test->addSlot( testSlot );
487
488        visual_dataIO::getInstance()->setSlotData("TestSlot1", osgVisual::dataIO_slot::TO_OBJ, 0.12345);
489
490}
Note: See TracBrowser for help on using the repository browser.