source: osgVisual/trunk/src/object/visual_object.cpp @ 203

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

Created environment to parse models from XML

File size: 13.0 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#include <visual_object.h>
18
19using namespace osgVisual;
20
21visual_object::visual_object( osg::CoordinateSystemNode* sceneRoot_, std::string nodeName_)
22{
23        // Add this node to Scenegraph
24        sceneRoot_->addChild( this );
25
26        // Set Nodename for further identification
27        this->setName( nodeName_ );
28
29        // Set callback.
30        /** \todo: welcher update ist der richtige? voraussichtlich event.) */
31        //this->setUpdateCallback( new visual_objectPositionCallback() );
32        this->setEventCallback( new visual_objectPositionCallback() );
33
34        // Init Position and Attitude
35        lat = 0;
36        lon = 0;
37        alt = 0;
38
39        azimuthAngle_psi = 0;
40        pitchAngle_theta = 0;
41        bankAngle_phi = 0;
42
43        geometry_offset_rotation.makeRotate( 0.0, 1.0, 1.0, 1.0 );
44
45        // Init Scale
46        scaleX = 1.0;
47        scaleY = 1.0;
48        scaleZ = 1.0;
49
50        // Init cameraOffset
51        cameraTranslationOffset.makeTranslate( osg::Vec3d(0.0, 0.0, 0.0) );     // Trans: (y, x, -z_down)
52        cameraRotationOffset.makeRotate( osg::DegreesToRadians( 90.0 ), osg::Vec3(1, 0, 0) );   // Rot: (-y, +x , -z)
53
54        // Geometrynode hinzufügen
55        geometry = new osg::Group();
56        this->addChild( geometry );
57
58        // Labelnode hinzufügen
59        labels = new osg::Geode();
60        this->addChild( labels ); 
61}
62
63visual_object::~visual_object()
64{
65
66}
67
68visual_object* visual_object::createNodeFromXMLConfig(osg::CoordinateSystemNode* sceneRoot_, xmlNode* a_node)
69{
70        if(a_node == NULL)
71                return NULL;
72
73        OSG_NOTIFY( osg::ALWAYS ) << __FUNCTION__ << "Try to creating a new Model.." << std::endl;
74        //osg::ref<visual_object> object = new visual_object( root, nodeName);
75
76
77                        /*
78                        <models>
79                          <model filename="cessna" type="plain" label="TestText!" dynamic="yes">
80                                <position lat="47.12345" lon="11.234567" alt="1500.0"></position>
81                                <attitude rot_x="0.0" rot_y="0.0" rot_z="0.0"></attitude>
82                                <cameraoffset>
83                                  <translation trans_x="0.0" trans_y="0.0" trans_z="0.0"></translation>
84                                  <rotation rot_x="0.0" rot_y="0.0" rot_z="0.0"></rotation>
85                                </cameraoffset>
86                          </model>
87                        </models>
88                        */
89
90        OSG_NOTIFY( osg::ALWAYS ) << "Done." << std::endl;
91        return NULL;
92}
93
94void visual_object::setNewPositionAttitude( double lat_, double lon_, double alt_, double azimuthAngle_psi_, double pitchAngle_theta_, double bankAngle_phi_ )
95{
96        lat = lat_;
97        lon = lon_;
98        alt = alt_;
99
100        azimuthAngle_psi = azimuthAngle_psi_;
101        pitchAngle_theta = pitchAngle_theta_;
102        bankAngle_phi = bankAngle_phi_;
103}
104
105void visual_object::setNewPosition( double lat_, double lon_, double alt_ )
106{
107        lat = lat_;
108        lon = lon_;
109        alt = alt_;
110}
111
112void visual_object::setNewAttitude( double azimuthAngle_psi_, double pitchAngle_theta_, double bankAngle_phi_ )
113{
114        azimuthAngle_psi = azimuthAngle_psi_;
115        pitchAngle_theta = pitchAngle_theta_;
116        bankAngle_phi = bankAngle_phi_;
117}
118
119void visual_object::setGeometryOffset( double rotX_, double rotY_, double rotZ_ )
120{
121        geometry_offset_rotation.makeRotate( rotX_, osg::Vec3f(1.0, 0.0, 0.0), 
122                                                rotY_, osg::Vec3f(0.0, 1.0, 0.0),
123                                                rotZ_, osg::Vec3f(0.0, 0.0, 1.0) );
124}
125
126void visual_object::setScale( double scale_ )
127{
128        scaleX = scale_;
129        scaleY = scale_;
130        scaleZ = scale_;
131}
132
133void visual_object::setScale( double scaleX_, double scaleY_, double scaleZ_ )
134{
135        scaleX = scaleX_;
136        scaleY = scaleY_;
137        scaleZ = scaleZ_;
138}
139
140bool visual_object::loadGeometry(std::string filename_)
141{
142        // Check if file exists
143        if( !osgDB::fileExists(filename_) )
144        {
145                OSG_NOTIFY(osg::FATAL) << "Error: Model not loaded. File '" << filename_ << "' does not exist." << std::endl;
146        }
147
148        osg::ref_ptr<osg::Node> tmpModel = osgDB::readNodeFile( filename_ );
149       
150        if( tmpModel.valid() )
151        {
152                // remove old geometry
153                geometry->removeChildren(0, geometry->getNumChildren());
154
155                // add new geometry
156                geometry->addChild( tmpModel.get() );
157                return true;
158        }
159        else
160        {
161                std::cout <<": No model loaded: " << filename_ << std::endl;
162        return false;
163    }
164}
165
166bool visual_object::setGeometry(osg::Node* geometry_)
167{
168        // remove old geometry
169        geometry->removeChildren(0, geometry->getNumChildren());
170
171        // add new geometry
172        geometry->addChild( geometry_ );
173
174        return true;
175}
176
177void visual_object::unsetGeometry()
178{
179        // remove old geometry
180        geometry->removeChildren(0, geometry->getNumChildren());
181}
182
183void visual_object::addUpdater( object_updater* updater_ )
184{
185        if ( updater.valid() )
186                updater->addUpdater( updater_ );
187        else
188                updater = updater_;
189}
190
191void visual_object::clearAllUpdater()
192{
193        // release only first updater. Because smartpointer: Will be deleted if not referenced.
194        if ( updater.valid() )
195                updater = NULL;
196}
197
198std::vector<object_updater*> visual_object::getUpdaterList()
199{
200        // iterate through updater and add all pointer.
201        std::vector<object_updater*> updaterList;
202        osg::ref_ptr<object_updater> tmpUpdater = updater;
203
204        while (tmpUpdater.valid())
205        {
206                updaterList.push_back( tmpUpdater );
207                tmpUpdater = tmpUpdater->getPointer();
208        }
209
210        // return list
211        return updaterList;
212}
213
214void visual_object::visual_objectPositionCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
215{
216        visual_object* object = dynamic_cast<visual_object*>(node);
217        if ( !object )
218        {
219                OSG_NOTIFY(osg::FATAL) << "ERROR : No object found. Unable to apply this callback!" << std::endl;
220                return;
221        }
222
223        // execute preUpdater to get new data of this object.
224        if ( object->updater.valid() )
225                object->updater->preUpdate(object);
226   
227        // Nodepath from this node to absolute parent (if no endnode specified)
228        osg::NodePath nodePath = nv->getNodePath();
229
230        // If Nodepath != empty, then mt = last element of node path
231        osg::MatrixTransform* mt = nodePath.empty() ? 0 : dynamic_cast<osg::MatrixTransform*>(nodePath.back());
232        if (mt)
233        {
234                osg::CoordinateSystemNode* csn = 0;
235
236                // find coordinate system node from our parental chain: traverse chain and try to convert every node to a csn.
237                unsigned int i;
238                for(i=0; i<nodePath.size() && csn==0; ++i)      // "&& csn" means: exit loop if csn found
239                {
240                        csn = dynamic_cast<osg::CoordinateSystemNode*>(nodePath[i]);    // dynamic_cast returns 0 if dynamic_cast fails.
241                }
242       
243                // Wenn csn gefunden:
244                if (csn)
245                {
246                        // Ellipsoidmodel erfragen
247                        osg::EllipsoidModel* ellipsoid = csn->getEllipsoidModel();
248                        if (ellipsoid)
249                        {
250                                osg::Matrix inheritedMatrix;
251
252                                // durch den _restlichen_ Nodepath durchgehen und alle anfallenden Transformationen durchführen.
253                                for(i+=1; i<nodePath.size()-1; ++i)
254                                {
255                                        osg::Transform* transform = nodePath[i]->asTransform(); // Versuchen, den Node zu einer Transformation zu konvertieren
256                   
257                                        // wenn Node wirklich Trafo, dann die Tranformationsmatrix von Nodekoordinaten nach Global auf inheritedMatrix draufschlagen.
258                                        if (transform) transform->computeLocalToWorldMatrix(inheritedMatrix, nv);
259                                }
260               
261                                osg::Matrixd matrix(inheritedMatrix);
262
263                                // Set position
264                                ellipsoid->computeLocalToWorldTransformFromLatLongHeight(object->lat, object->lon, object->alt, matrix);
265
266                                // Set Upvector for position
267                                double X,Y,Z;
268                                util::calculateXYZAtWGS84Coordinate(object->lat, object->lon, object->alt, csn, X, Y, Z );
269                                object->upVector = ellipsoid->computeLocalUpVector(X,Y,Z);
270
271                                // Set scale
272                                osg::Matrixd scaleMatrix;
273                                scaleMatrix.makeScale( object->scaleX, object->scaleY, object->scaleZ );
274                                matrix.preMult( scaleMatrix );
275
276                                // Set rotation
277                                // rotation von links ranmultiplizieren, entspricht: matrix = rotation * matrix. Da rotation ein Quat ist, wäre die direkte Multiplikation nur über Umwege machbar.
278                                // Rotate Object to Attitude.
279                                osg::Matrixd rotationMatrix;
280                                // Move Model by Azimuth
281                                rotationMatrix.makeRotate( -object->azimuthAngle_psi, osg::Vec3d(0.0, 0.0, 1.0) );
282                                matrix.preMult(rotationMatrix); 
283                                // Move Model by Pitch
284                                rotationMatrix.makeRotate( object->pitchAngle_theta, osg::Vec3d(1.0, 0.0, 0.0) );
285                                matrix.preMult(rotationMatrix);
286                                // Move Model by Bank
287                                rotationMatrix.makeRotate( object->bankAngle_phi, osg::Vec3d(0.0, 1.0, 0.0) );
288                                matrix.preMult(rotationMatrix);
289
290                                // Also update camera matrix (without geometry offset, because camera is interested in the objects matrix, not in the model's matrix.)
291                                object->cameraMatrix = matrix;
292                                /** \todo : Clean up camera matrix management: try to solve it with a single matrix. (each frame two matrix mults less) */
293                                // dont know, why this rotation is necessary - maybe manipulator and node MatrixTransform interpret a matrix in different way?
294                                object->cameraMatrix.preMult( object->cameraTranslationOffset );
295                                object->cameraMatrix.preMult( object->cameraRotationOffset );
296                                                       
297
298                                // Set geometry correction
299                                matrix.preMultRotate( object->geometry_offset_rotation );
300
301                                // Set cumulated object matrix as the matrix of this matrix transform
302                                mt->setMatrix(matrix);
303                        }
304                }       
305        }
306     
307        // Call any nested callbacks.
308        traverse(node,nv);
309
310        // If SLAVE: execute postUpdater to pass new data of this object to dataIO.
311        if( visual_dataIO::getInstance()->isSlave() )
312        {
313                if ( object->updater.valid() )
314                        object->updater->postUpdate(object);
315        }
316
317}   // Callbackfunction [ Operater() ] END
318
319void visual_object::setCameraOffsetTranslation( double x_, double y_, double z_)
320{
321        cameraTranslationOffset.makeTranslate( osg::Vec3d(x_, y_, z_) );        // Trans: (rechts davon, longitudinal, vertikal)
322}
323
324void visual_object::setCameraOffset(double x_, double y_, double z_, double rotX_, double rotY_, double rotZ_)
325{
326        setCameraOffsetTranslation( x_, y_, z_);
327        setCameraOffsetRotation( rotX_, rotY_, rotZ_);
328}
329
330void visual_object::setCameraOffsetRotation(double rotX_, double rotY_, double rotZ_)
331{
332        osg::Matrix tmp;
333        cameraRotationOffset.makeRotate( osg::DegreesToRadians( 90.0 ), osg::Vec3(1, 0, 0) );
334        tmp.makeRotate( -rotZ_, osg::Vec3d(0.0, 1.0, 0.0) );
335        cameraRotationOffset.preMult(tmp);
336        tmp.makeRotate( rotY_, osg::Vec3d(1.0, 0.0, 0.0) );     
337        cameraRotationOffset.preMult(tmp);
338        tmp.makeRotate( -rotX_, osg::Vec3d(0.0, 0.0, 1.0) );   
339        cameraRotationOffset.preMult(tmp);
340}
341
342void visual_object::clearLabels()
343{
344        labels->removeDrawables(0, labels->getNumDrawables());
345}
346
347void visual_object::addLabel(std::string idString_, std::string label_, osg::Vec4 color_, osg::Vec3 offset_)
348{
349        osg::ref_ptr<osgText::Text> text = new osgText::Text();
350
351        text->setName(idString_);
352        text->setText(label_);
353        text->setColor(color_);
354        text->setFont("fonts/arial.ttf");
355        text->setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
356        text->setAutoRotateToScreen(true);
357        text->setPosition(offset_);
358
359        text->getOrCreateStateSet()->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
360        labels->addDrawable( text );
361}
362
363bool visual_object::removeLabel(std::string idString_)
364{
365        osg::Node* labelToRemove = util::findNamedNode(idString_, this);
366
367        if(labelToRemove)
368        {
369                removeChild( labelToRemove );
370                return true;
371        }
372        else
373                return false;
374}
375
376bool visual_object::updateLabelText(std::string idString_, std::string label_)
377{
378        osg::Node* labelToUpdate = util::findNamedNode(idString_, this);
379
380        if(labelToUpdate)
381        {
382                osgText::Text* text = dynamic_cast<osgText::Text*>(labelToUpdate);
383                if(text)
384                {
385                        text->setText(label_);
386                        return true;
387                }
388                return false;
389        }
390        return false;
391}
392
393osgText::Text* visual_object::getLabel(std::string idString_)
394{
395        osg::Node* labelToFind = util::findNamedNode(idString_, this);
396
397        if(labelToFind)
398        {
399                osgText::Text* text = dynamic_cast<osgText::Text*>(labelToFind);
400                if(text)
401                        return text;
402        }
403        return NULL;
404
405}
406
407bool visual_object::setDrawLabelAsOverlay(std::string idString_, bool drawAsOverlay)
408{
409        osg::Node* labelToFind = util::findNamedNode(idString_, this);
410
411        if(labelToFind)
412        {
413                if (drawAsOverlay)
414                        labelToFind->getOrCreateStateSet()->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
415                else
416                        labelToFind->getOrCreateStateSet()->setMode(GL_DEPTH_TEST,osg::StateAttribute::ON);
417                return true;
418        }
419        else 
420                return false;
421}
422
423bool visual_object::getDrawLabelAsOverlay(std::string idString_)
424{
425        osg::Node* labelToFind = util::findNamedNode(idString_, this);
426
427        if(labelToFind)
428        {
429                if(labelToFind->getOrCreateStateSet()->getMode(GL_DEPTH_TEST) == osg::StateAttribute::OFF)
430                        return false;
431                else 
432                        return true;
433        }
434        return false;
435}
Note: See TracBrowser for help on using the repository browser.