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

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