3 // Copyright (C) 2013 Thomas Geymayer <tomgey@gmail.com>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Library General Public License for more details.
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "SGRotateTransform.hxx"
20 #include "SGTrackToAnimation.hxx"
22 #include <simgear/scene/util/OsgMath.hxx>
23 #include <osg/Transform>
29 static osg::NodePath requireNodePath( osg::Node* node,
30 osg::Node* haltTraversalAtNode = 0 )
32 const osg::NodePathList node_paths =
33 node->getParentalNodePaths(haltTraversalAtNode);
34 return node_paths.at(0);
38 * Get a subpath of an osg::NodePath
40 * @param path Path to extract subpath from
41 * @param start Number of elements to skip from start of #path
43 * @return Subpath starting with node at position #start
45 static osg::NodePath subPath( const osg::NodePath& path,
48 if( start >= path.size() )
49 return osg::NodePath();
51 osg::NodePath np(path.size() - start);
52 for(size_t i = start; i < path.size(); ++i)
53 np[i - start] = path[i];
59 * Visitor to find a group by its name.
61 class FindGroupVisitor:
62 public osg::NodeVisitor
66 FindGroupVisitor(const std::string& name):
67 osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
72 SG_LOG(SG_IO, SG_WARN, "FindGroupVisitor: empty name provided");
75 osg::Group* getGroup() const
80 virtual void apply(osg::Group& group)
82 if( _name != group.getName() )
83 return traverse(group);
92 "FindGroupVisitor: name not unique '" << _name << "'"
103 * Get angle of a triangle given by three side lengths
105 * @return Angle enclosed by @c side1 and @c side2
107 double angleFromSSS(double side1, double side2, double opposite)
111 ( SGMiscd::pow<2>(side1)
112 + SGMiscd::pow<2>(side2)
113 - SGMiscd::pow<2>(opposite)
114 ) / (2 * side1 * side2)
118 //------------------------------------------------------------------------------
119 class SGTrackToAnimation::UpdateCallback:
120 public osg::NodeCallback
123 UpdateCallback( osg::Group* target,
124 const SGTrackToAnimation* anim,
125 SGRotateTransform* slave_tf ):
130 _root_initial_angle(0),
131 _condition(anim->getCondition()),
132 _root_disabled_value(
133 anim->readOffsetValue("disabled-rotation-deg")
135 _slave_disabled_value(
136 anim->readOffsetValue("slave-disabled-rotation-deg")
139 setName("SGTrackToAnimation::UpdateCallback");
141 _node_center = toOsg( anim->readVec3("center", "-m") );
142 _slave_center = toOsg( anim->readVec3("slave-center", "-m") );
143 _target_center = toOsg( anim->readVec3("target-center", "-m") );
144 _lock_axis = toOsg( anim->readVec3("lock-axis") );
145 _track_axis = toOsg( anim->readVec3("track-axis") );
147 if( _lock_axis.normalize() == 0.0 )
149 anim->log(SG_WARN, "invalid lock-axis");
150 _lock_axis.set(0, 1, 0);
153 if( _slave_center != osg::Vec3() )
155 _root_length = (_slave_center - _node_center).length();
156 _slave_length = (_target_center - _slave_center).length();
157 double dist = (_target_center - _node_center).length();
159 _root_initial_angle = angleFromSSS(_root_length, dist, _slave_length);
161 // If no rotation should be applied to the slave element it is looking
162 // in the same direction then the root node. Inside the triangle given
163 // by the root length, slave length and distance from the root node to
164 // the target node, this equals an angle of 180 degrees.
165 _slave_initial_angle = angleFromSSS(_root_length, _slave_length, dist)
168 _track_axis = _target_center - _node_center;
173 float proj = _lock_axis * _track_axis;
176 anim->log(SG_WARN, "track-axis not perpendicular to lock-axis");
178 // Make tracking axis perpendicular to locked axis
179 _track_axis -= _lock_axis * proj;
182 if( _track_axis.normalize() == 0.0 )
184 anim->log(SG_WARN, "invalid track-axis");
185 if( std::fabs(_lock_axis.x()) < 0.1 )
186 _track_axis.set(1, 0, 0);
188 _track_axis.set(0, 1, 0);
194 _up_axis = _lock_axis ^ _track_axis;
197 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
199 SGRotateTransform* tf = static_cast<SGRotateTransform*>(node);
201 // We need to wait with this initialization steps until the first update
202 // as this allows us to be sure all animations have already been installed
203 // and are therefore also accounted for calculating the animation.
206 // Get path to animated node and calculated simplified paths to the
207 // nearest common parent node of both the animated node and the target
210 // start at parent to not get false results by
211 // also including animation transformation
212 osg::NodePath node_path = requireNodePath(node->getParent(0)),
213 target_path = requireNodePath(_target);
214 size_t tp_size = target_path.size(),
215 np_size = node_path.size();
216 size_t common_parents = 0;
218 for(; common_parents < std::min(tp_size, np_size); ++common_parents)
220 if( target_path[common_parents] != node_path[common_parents] )
224 _node_path = subPath(node_path, common_parents);
225 _target_path = subPath(target_path, common_parents);
228 tf->setCenter( toSG(_node_center) );
229 tf->setAxis( toSG(_lock_axis) );
233 _slave_tf->setCenter( toSG(_slave_center) );
234 _slave_tf->setAxis( toSG(_lock_axis) );
238 osg::Vec3 target_pos = ( osg::computeLocalToWorld(_target_path)
239 * osg::computeWorldToLocal(_node_path)
240 ).preMult(_target_center),
241 dir = target_pos - _node_center;
246 if( !_condition || _condition->test() )
248 root_angle = -_root_initial_angle;
249 slave_angle = -_slave_initial_angle;
251 if( _root_length > 0 )
253 double dist = dir.length();
254 if( dist < _root_length + _slave_length )
256 root_angle += angleFromSSS(_root_length, dist, _slave_length);
259 slave_angle += angleFromSSS(_root_length, _slave_length, dist)
264 // Ensure direction is perpendicular to lock axis
265 float proj = _lock_axis * dir;
267 dir -= _lock_axis * proj;
269 float x = dir * _track_axis,
271 root_angle += std::atan2(y, x);
275 root_angle = _root_disabled_value
276 ? SGMiscd::deg2rad(_root_disabled_value->getValue())
278 slave_angle = _slave_disabled_value
279 ? SGMiscd::deg2rad(_slave_disabled_value->getValue())
283 tf->setAngleRad( root_angle );
285 _slave_tf->setAngleRad(slave_angle);
291 osg::Vec3 _node_center,
298 SGRotateTransform *_slave_tf;
299 osg::NodePath _node_path,
304 _slave_initial_angle;
306 SGSharedPtr<SGCondition const> _condition;
307 SGExpressiond_ref _root_disabled_value,
308 _slave_disabled_value;
311 //------------------------------------------------------------------------------
312 SGTrackToAnimation::SGTrackToAnimation( osg::Node* node,
313 const SGPropertyNode* configNode,
314 SGPropertyNode* modelRoot ):
315 SGAnimation(configNode, modelRoot),
319 std::string target = configNode->getStringValue("target-name");
320 FindGroupVisitor target_finder(target);
321 node->accept(target_finder);
323 if( !(_target_group = target_finder.getGroup()) )
324 log(SG_ALERT, "target not found: '" + target + '\'');
326 std::string slave = configNode->getStringValue("slave-name");
329 FindGroupVisitor slave_finder(slave);
330 node->accept(slave_finder);
331 _slave_group = slave_finder.getGroup();
335 //------------------------------------------------------------------------------
336 osg::Group* SGTrackToAnimation::createAnimationGroup(osg::Group& parent)
341 SGRotateTransform* slave_tf = 0;
344 slave_tf = new SGRotateTransform;
345 slave_tf->setName("locked-track slave animation");
347 osg::Group* parent = _slave_group->getParent(0);
348 slave_tf->addChild(_slave_group);
349 parent->removeChild(_slave_group);
350 parent->addChild(slave_tf);
353 SGRotateTransform* tf = new SGRotateTransform;
354 tf->setName("locked-track animation");
355 tf->setUpdateCallback(new UpdateCallback(_target_group, this, slave_tf));
361 //------------------------------------------------------------------------------
362 void SGTrackToAnimation::log(sgDebugPriority p, const std::string& msg) const
368 // TODO handle multiple object-names?
369 "SGTrackToAnimation(" << getConfig()->getStringValue("object-name") << "): "